title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
CSS Tutorial
CSS is used to control the style of a web document in a simple and easy way. CSS is the acronym for "Cascading Style Sheet". This tutorial covers both the versions CSS1,CSS2 and CSS3, and gives a complete understanding of CSS, starting from its basics to advanced concepts. Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify the process of making web pages presentable. CSS is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development Domain. I will list down some of the key advantages of learning CSS: Create Stunning Web site - CSS handles the look and feel part of a web page. Using CSS, you can control the color of the text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out, what background images or colors are used, layout designs,variations in display for different devices and screen sizes as well as a variety of other effects. Create Stunning Web site - CSS handles the look and feel part of a web page. Using CSS, you can control the color of the text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out, what background images or colors are used, layout designs,variations in display for different devices and screen sizes as well as a variety of other effects. Become a web designer - If you want to start a carrer as a professional web designer, HTML and CSS designing is a must skill. Become a web designer - If you want to start a carrer as a professional web designer, HTML and CSS designing is a must skill. Control web - CSS is easy to learn and understand but it provides powerful control over the presentation of an HTML document. Most commonly, CSS is combined with the markup languages HTML or XHTML. Control web - CSS is easy to learn and understand but it provides powerful control over the presentation of an HTML document. Most commonly, CSS is combined with the markup languages HTML or XHTML. Learn other languages - Once you understands the basic of HTML and CSS then other related technologies like javascript, php, or angular are become easier to understand. Learn other languages - Once you understands the basic of HTML and CSS then other related technologies like javascript, php, or angular are become easier to understand. Just to give you a little excitement about CSS, I'm going to give you a small conventional CSS Hello World program, You can try it using Demo link. <!DOCTYPE html> <html> <head> <title>This is document title</title> <style> h1 { color: #36CFFF; } </style> </head> <body> <h1>Hello World!</h1> </body> </html> As mentioned before, CSS is one of the most widely used style language over the web. I'm going to list few of them here: CSS saves time - You can write CSS once and then reuse same sheet in multiple HTML pages. You can define a style for each HTML element and apply it to as many Web pages as you want. CSS saves time - You can write CSS once and then reuse same sheet in multiple HTML pages. You can define a style for each HTML element and apply it to as many Web pages as you want. Pages load faster - If you are using CSS, you do not need to write HTML tag attributes every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag. So less code means faster download times. Pages load faster - If you are using CSS, you do not need to write HTML tag attributes every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag. So less code means faster download times. Easy maintenance - To make a global change, simply change the style, and all elements in all the web pages will be updated automatically. Easy maintenance - To make a global change, simply change the style, and all elements in all the web pages will be updated automatically. Superior styles to HTML - CSS has a much wider array of attributes than HTML, so you can give a far better look to your HTML page in comparison to HTML attributes. Superior styles to HTML - CSS has a much wider array of attributes than HTML, so you can give a far better look to your HTML page in comparison to HTML attributes. Multiple Device Compatibility - Style sheets allow content to be optimized for more than one type of device. By using the same HTML document, different versions of a website can be presented for handheld devices such as PDAs and cell phones or for printing. Multiple Device Compatibility - Style sheets allow content to be optimized for more than one type of device. By using the same HTML document, different versions of a website can be presented for handheld devices such as PDAs and cell phones or for printing. Global web standards - Now HTML attributes are being deprecated and it is being recommended to use CSS. So its a good idea to start using CSS in all the HTML pages to make them compatible to future browsers. Global web standards - Now HTML attributes are being deprecated and it is being recommended to use CSS. So its a good idea to start using CSS in all the HTML pages to make them compatible to future browsers. This CSS tutorial will help both students as well as professionals who want to make their websites or personal blogs more attractive. You should be familiar with: Basic word processing using any text editor. How to create directories and files. How to navigate through different directories. Internet browsing using popular browsers like Internet Explorer or Firefox. Developing simple Web Pages using HTML or XHTML. If you are new to HTML and XHTML, then we would suggest you to go through our HTML Tutorial or XHTML Tutorial first. 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2703, "s": 2626, "text": "CSS is used to control the style of a web document in a simple and easy way." }, { "code": null, "e": 2900, "s": 2703, "text": "CSS is the acronym for \"Cascading Style Sheet\". This tutorial covers both the versions CSS1,CSS2 and CSS3, and gives a complete understanding of CSS, starting from its basics to advanced concepts." }, { "code": null, "e": 3045, "s": 2900, "text": "Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify the process of making web pages presentable." }, { "code": null, "e": 3254, "s": 3045, "text": "CSS is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development Domain. I will list down some of the key advantages of learning CSS:" }, { "code": null, "e": 3627, "s": 3254, "text": "Create Stunning Web site - CSS handles the look and feel part of a web page. Using CSS, you can control the color of the text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out, what background images or colors are used, layout designs,variations in display for different devices and screen sizes as well as a variety of other effects." }, { "code": null, "e": 4000, "s": 3627, "text": "Create Stunning Web site - CSS handles the look and feel part of a web page. Using CSS, you can control the color of the text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out, what background images or colors are used, layout designs,variations in display for different devices and screen sizes as well as a variety of other effects." }, { "code": null, "e": 4126, "s": 4000, "text": "Become a web designer - If you want to start a carrer as a professional web designer, HTML and CSS designing is a must skill." }, { "code": null, "e": 4252, "s": 4126, "text": "Become a web designer - If you want to start a carrer as a professional web designer, HTML and CSS designing is a must skill." }, { "code": null, "e": 4450, "s": 4252, "text": "Control web - CSS is easy to learn and understand but it provides powerful control over the presentation of an HTML document. Most commonly, CSS is combined with the markup languages HTML or XHTML." }, { "code": null, "e": 4648, "s": 4450, "text": "Control web - CSS is easy to learn and understand but it provides powerful control over the presentation of an HTML document. Most commonly, CSS is combined with the markup languages HTML or XHTML." }, { "code": null, "e": 4817, "s": 4648, "text": "Learn other languages - Once you understands the basic of HTML and CSS then other related technologies like javascript, php, or angular are become easier to understand." }, { "code": null, "e": 4986, "s": 4817, "text": "Learn other languages - Once you understands the basic of HTML and CSS then other related technologies like javascript, php, or angular are become easier to understand." }, { "code": null, "e": 5134, "s": 4986, "text": "Just to give you a little excitement about CSS, I'm going to give you a small conventional CSS Hello World program, You can try it using Demo link." }, { "code": null, "e": 5355, "s": 5134, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>This is document title</title>\n <style>\n h1 {\n color: #36CFFF; \n }\n </style>\n </head>\t\n <body>\n <h1>Hello World!</h1>\n </body>\t\n</html>" }, { "code": null, "e": 5476, "s": 5355, "text": "As mentioned before, CSS is one of the most widely used style language over the web. I'm going to list few of them here:" }, { "code": null, "e": 5658, "s": 5476, "text": "CSS saves time - You can write CSS once and then reuse same sheet in multiple HTML pages. You can define a style for each HTML element and apply it to as many Web pages as you want." }, { "code": null, "e": 5840, "s": 5658, "text": "CSS saves time - You can write CSS once and then reuse same sheet in multiple HTML pages. You can define a style for each HTML element and apply it to as many Web pages as you want." }, { "code": null, "e": 6063, "s": 5840, "text": "Pages load faster - If you are using CSS, you do not need to write HTML tag attributes every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag. So less code means faster download times." }, { "code": null, "e": 6286, "s": 6063, "text": "Pages load faster - If you are using CSS, you do not need to write HTML tag attributes every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag. So less code means faster download times." }, { "code": null, "e": 6424, "s": 6286, "text": "Easy maintenance - To make a global change, simply change the style, and all elements in all the web pages will be updated automatically." }, { "code": null, "e": 6562, "s": 6424, "text": "Easy maintenance - To make a global change, simply change the style, and all elements in all the web pages will be updated automatically." }, { "code": null, "e": 6726, "s": 6562, "text": "Superior styles to HTML - CSS has a much wider array of attributes than HTML, so you can give a far better look to your HTML page in comparison to HTML attributes." }, { "code": null, "e": 6890, "s": 6726, "text": "Superior styles to HTML - CSS has a much wider array of attributes than HTML, so you can give a far better look to your HTML page in comparison to HTML attributes." }, { "code": null, "e": 7148, "s": 6890, "text": "Multiple Device Compatibility - Style sheets allow content to be optimized for more than one type of device. By using the same HTML document, different versions of a website can be presented for handheld devices such as PDAs and cell phones or for printing." }, { "code": null, "e": 7406, "s": 7148, "text": "Multiple Device Compatibility - Style sheets allow content to be optimized for more than one type of device. By using the same HTML document, different versions of a website can be presented for handheld devices such as PDAs and cell phones or for printing." }, { "code": null, "e": 7614, "s": 7406, "text": "Global web standards - Now HTML attributes are being deprecated and it is being recommended to use CSS. So its a good idea to start using CSS in all the HTML pages to make them compatible to future browsers." }, { "code": null, "e": 7822, "s": 7614, "text": "Global web standards - Now HTML attributes are being deprecated and it is being recommended to use CSS. So its a good idea to start using CSS in all the HTML pages to make them compatible to future browsers." }, { "code": null, "e": 7956, "s": 7822, "text": "This CSS tutorial will help both students as well as professionals who want to make their websites or personal blogs more attractive." }, { "code": null, "e": 7985, "s": 7956, "text": "You should be familiar with:" }, { "code": null, "e": 8030, "s": 7985, "text": "Basic word processing using any text editor." }, { "code": null, "e": 8067, "s": 8030, "text": "How to create directories and files." }, { "code": null, "e": 8114, "s": 8067, "text": "How to navigate through different directories." }, { "code": null, "e": 8190, "s": 8114, "text": "Internet browsing using popular browsers like Internet Explorer or Firefox." }, { "code": null, "e": 8239, "s": 8190, "text": "Developing simple Web Pages using HTML or XHTML." }, { "code": null, "e": 8356, "s": 8239, "text": "If you are new to HTML and XHTML, then we would suggest you to go through our HTML Tutorial or XHTML Tutorial first." }, { "code": null, "e": 8391, "s": 8356, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8405, "s": 8391, "text": " Anadi Sharma" }, { "code": null, "e": 8440, "s": 8405, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8457, "s": 8440, "text": " Frahaan Hussain" }, { "code": null, "e": 8492, "s": 8457, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8523, "s": 8492, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8558, "s": 8523, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8589, "s": 8558, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8624, "s": 8589, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8655, "s": 8624, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8688, "s": 8655, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 8719, "s": 8688, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8726, "s": 8719, "text": " Print" }, { "code": null, "e": 8737, "s": 8726, "text": " Add Notes" } ]
How to disable ScrollView Programmatically in Android?
This example demonstrates how to do I disable ScrollView 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" android:padding="16dp" tools:context=".MainActivity"> <ScrollView android:id="@+id/scrollView" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" android:padding="16dp"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> </LinearLayout>; </ScrollView> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import android.os.Build; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.ScrollView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @RequiresApi(api = Build.VERSION_CODES.M) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ScrollView scrollView = findViewById(R.id.scrollView); scrollView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Toast.makeText(MainActivity.this, "ScrollView Disabled", Toast.LENGTH_SHORT).show(); return true; } }); } } Step 4 − 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.com.sample"> <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" /> <ategory 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 the 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": 1148, "s": 1062, "text": "This example demonstrates how to do I disable ScrollView programmatically in android." }, { "code": null, "e": 1277, "s": 1148, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1342, "s": 1277, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 5530, "s": 1342, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\nxmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"16dp\"\n tools:context=\".MainActivity\">\n <ScrollView\n android:id=\"@+id/scrollView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n android:orientation=\"vertical\"\n android:padding=\"16dp\">\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n </LinearLayout>;\n </ScrollView>\n</RelativeLayout>" }, { "code": null, "e": 5587, "s": 5530, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 6461, "s": 5587, "text": "import androidx.annotation.RequiresApi;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.ScrollView;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n @RequiresApi(api = Build.VERSION_CODES.M)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n ScrollView scrollView = findViewById(R.id.scrollView);\n scrollView.setOnTouchListener(new View.OnTouchListener() {\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n Toast.makeText(MainActivity.this, \"ScrollView Disabled\", Toast.LENGTH_SHORT).show();\n return true;\n }\n });\n }\n}" }, { "code": null, "e": 6516, "s": 6461, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 7185, "s": 6516, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <ategory android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 7536, "s": 7185, "text": "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 the 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 −" }, { "code": null, "e": 7577, "s": 7536, "text": "Click here to download the project code." } ]
Advanced Excel Statistical - STEYX Function
The STEYX function returns the standard error of the predicted y-value for each x in the regression. The standard error is a measure of the amount of error in the prediction of y for an individual x. STEYX (known_y's, known_x's) The equation for the standard error of the predicted y is − $$\sqrt{\frac{1}{2}\left [ \sum \left ( y-\bar{y} \right )^2 - \frac{\left [ \sum \left ( x-\bar{x} \right )\left ( y-\bar{y} \right ) \right ]^2}{\sum \left ( x-\bar{x} \right )^2} \right ]}$$ Where x and y are the sample means AVERAGE (known_x’s) and AVERAGE (known_y’s), and n is the sample size. The equation for the standard error of the predicted y is − $$\sqrt{\frac{1}{2}\left [ \sum \left ( y-\bar{y} \right )^2 - \frac{\left [ \sum \left ( x-\bar{x} \right )\left ( y-\bar{y} \right ) \right ]^2}{\sum \left ( x-\bar{x} \right )^2} \right ]}$$ Where x and y are the sample means AVERAGE (known_x’s) and AVERAGE (known_y’s), and n is the sample size. Arguments can either be numbers or names, arrays, or references that contain numbers. Arguments can either be numbers or names, arrays, or references that contain numbers. Logical values and text representations of numbers that you type directly into the list of arguments are counted. Logical values and text representations of numbers that you type directly into the list of arguments are counted. If an array or reference argument contains text, logical values, or empty cells, those values are ignored; however, cells with the value zero are included. If an array or reference argument contains text, logical values, or empty cells, those values are ignored; however, cells with the value zero are included. Arguments that are error values or text that cannot be translated into numbers cause errors. Arguments that are error values or text that cannot be translated into numbers cause errors. If known_y's and known_x's have a different number of data points, STEYX returns the #N/A error value. If known_y's and known_x's have a different number of data points, STEYX returns the #N/A error value. If known_y's and known_x's are empty or have less than three data points, STEYX returns the #DIV/0! error value. Excel 2007, Excel 2010, Excel 2013, Excel 2016 296 Lectures 146 hours Arun Motoori 56 Lectures 5.5 hours Pavan Lalwani 120 Lectures 6.5 hours Inf Sid 134 Lectures 8.5 hours Yoda Learning 46 Lectures 7.5 hours William Fiset 25 Lectures 1.5 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2054, "s": 1854, "text": "The STEYX function returns the standard error of the predicted y-value for each x in the regression. The standard error is a measure of the amount of error in the prediction of y for an individual x." }, { "code": null, "e": 2084, "s": 2054, "text": "STEYX (known_y's, known_x's)\n" }, { "code": null, "e": 2445, "s": 2084, "text": "The equation for the standard error of the predicted y is −\n$$\\sqrt{\\frac{1}{2}\\left [ \\sum \\left ( y-\\bar{y} \\right )^2 - \\frac{\\left [ \\sum \\left ( x-\\bar{x} \\right )\\left ( y-\\bar{y} \\right ) \\right ]^2}{\\sum \\left ( x-\\bar{x} \\right )^2} \\right ]}$$\nWhere x and y are the sample means AVERAGE (known_x’s) and AVERAGE (known_y’s), and n is the sample size.\n" }, { "code": null, "e": 2505, "s": 2445, "text": "The equation for the standard error of the predicted y is −" }, { "code": null, "e": 2699, "s": 2505, "text": "$$\\sqrt{\\frac{1}{2}\\left [ \\sum \\left ( y-\\bar{y} \\right )^2 - \\frac{\\left [ \\sum \\left ( x-\\bar{x} \\right )\\left ( y-\\bar{y} \\right ) \\right ]^2}{\\sum \\left ( x-\\bar{x} \\right )^2} \\right ]}$$" }, { "code": null, "e": 2805, "s": 2699, "text": "Where x and y are the sample means AVERAGE (known_x’s) and AVERAGE (known_y’s), and n is the sample size." }, { "code": null, "e": 2891, "s": 2805, "text": "Arguments can either be numbers or names, arrays, or references that contain numbers." }, { "code": null, "e": 2977, "s": 2891, "text": "Arguments can either be numbers or names, arrays, or references that contain numbers." }, { "code": null, "e": 3091, "s": 2977, "text": "Logical values and text representations of numbers that you type directly into the list of arguments are counted." }, { "code": null, "e": 3205, "s": 3091, "text": "Logical values and text representations of numbers that you type directly into the list of arguments are counted." }, { "code": null, "e": 3361, "s": 3205, "text": "If an array or reference argument contains text, logical values, or empty cells, those values are ignored; however, cells with the value zero are included." }, { "code": null, "e": 3517, "s": 3361, "text": "If an array or reference argument contains text, logical values, or empty cells, those values are ignored; however, cells with the value zero are included." }, { "code": null, "e": 3610, "s": 3517, "text": "Arguments that are error values or text that cannot be translated into numbers cause errors." }, { "code": null, "e": 3703, "s": 3610, "text": "Arguments that are error values or text that cannot be translated into numbers cause errors." }, { "code": null, "e": 3806, "s": 3703, "text": "If known_y's and known_x's have a different number of data points, STEYX returns the #N/A error value." }, { "code": null, "e": 3909, "s": 3806, "text": "If known_y's and known_x's have a different number of data points, STEYX returns the #N/A error value." }, { "code": null, "e": 4022, "s": 3909, "text": "If known_y's and known_x's are empty or have less than three data points, STEYX returns the #DIV/0! error value." }, { "code": null, "e": 4069, "s": 4022, "text": "Excel 2007, Excel 2010, Excel 2013, Excel 2016" }, { "code": null, "e": 4105, "s": 4069, "text": "\n 296 Lectures \n 146 hours \n" }, { "code": null, "e": 4119, "s": 4105, "text": " Arun Motoori" }, { "code": null, "e": 4154, "s": 4119, "text": "\n 56 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4169, "s": 4154, "text": " Pavan Lalwani" }, { "code": null, "e": 4205, "s": 4169, "text": "\n 120 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4214, "s": 4205, "text": " Inf Sid" }, { "code": null, "e": 4250, "s": 4214, "text": "\n 134 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4265, "s": 4250, "text": " Yoda Learning" }, { "code": null, "e": 4300, "s": 4265, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4315, "s": 4300, "text": " William Fiset" }, { "code": null, "e": 4350, "s": 4315, "text": "\n 25 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4364, "s": 4350, "text": " Sasha Miller" }, { "code": null, "e": 4371, "s": 4364, "text": " Print" }, { "code": null, "e": 4382, "s": 4371, "text": " Add Notes" } ]
Check if a number can be expressed as a sum of consecutive numbers in C++
Here we will see if one number can be represented as sum of two or more consecutive numbers or not. Suppose a number is 12. This can be represented as 3+4+5. There is a direct and easiest method to solve this problem. If a number is power of 2, then it cannot be expressed as sum of some consecutive numbers. There are two facts that we have to keep in mind. Sum of any two consecutive numbers is odd, then one of them will be odd, another one is even. Second fact is 2n = 2(n-1) + 2(n-1). Live Demo #include <iostream> using namespace std; bool isSumofconsecutiveNumbers(int n) { if((n & (n-1)) && n){ return true; } else { return false; } } int main() { int num = 36; if(isSumofconsecutiveNumbers(num)){ cout << "Can be represented"; } else { cout << "Cannot be represented"; } } Can be represented
[ { "code": null, "e": 1220, "s": 1062, "text": "Here we will see if one number can be represented as sum of two or more consecutive numbers or not. Suppose a number is 12. This can be represented as 3+4+5." }, { "code": null, "e": 1421, "s": 1220, "text": "There is a direct and easiest method to solve this problem. If a number is power of 2, then it cannot be expressed as sum of some consecutive numbers. There are two facts that we have to keep in mind." }, { "code": null, "e": 1515, "s": 1421, "text": "Sum of any two consecutive numbers is odd, then one of them will be odd, another one is even." }, { "code": null, "e": 1552, "s": 1515, "text": "Second fact is 2n = 2(n-1) + 2(n-1)." }, { "code": null, "e": 1563, "s": 1552, "text": " Live Demo" }, { "code": null, "e": 1890, "s": 1563, "text": "#include <iostream>\nusing namespace std;\nbool isSumofconsecutiveNumbers(int n) {\n if((n & (n-1)) && n){\n return true;\n } else {\n return false;\n }\n}\nint main() {\n int num = 36;\n if(isSumofconsecutiveNumbers(num)){\n cout << \"Can be represented\";\n } else {\n cout << \"Cannot be represented\";\n }\n}" }, { "code": null, "e": 1909, "s": 1890, "text": "Can be represented" } ]
Jackson Annotations - @JsonRawValue
@JsonRawValue allows to serialize a text without escaping or without any decoration. import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonTester { public static void main(String args[]){ ObjectMapper mapper = new ObjectMapper(); try { Student student = new Student("Mark", 1, "{\"attr\":false}"); String jsonString = mapper .writerWithDefaultPrettyPrinter() .writeValueAsString(student); System.out.println(jsonString); } catch (IOException e) { e.printStackTrace(); } } } class Student { private String name; private int rollNo; private String json; public Student(String name, int rollNo, String json){ this.name = name; this.rollNo = rollNo; this.json = json; } public String getName(){ return name; } public int getRollNo(){ return rollNo; } public String getJson(){ return json; } } { "name" : "Mark", "rollNo" : 1, "json" : {\"attr\":false} } import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.annotation.JsonRawValue; public class JacksonTester { public static void main(String args[]){ ObjectMapper mapper = new ObjectMapper(); try { Student student = new Student("Mark", 1, "{\"attr\":false}"); String jsonString = mapper .writerWithDefaultPrettyPrinter() .writeValueAsString(student); System.out.println(jsonString); } catch (IOException e) { e.printStackTrace(); } } } class Student { private String name; private int rollNo; @JsonRawValue private String json; public Student(String name, int rollNo, String json) { this.name = name; this.rollNo = rollNo; this.json = json; } public String getName(){ return name; } public int getRollNo(){ return rollNo; } public String getJson(){ return json; } } { "name" : "Mark", "rollNo" : 1, "json" : {"attr":false} } Print Add Notes Bookmark this page
[ { "code": null, "e": 2560, "s": 2475, "text": "@JsonRawValue allows to serialize a text without escaping or without any decoration." }, { "code": null, "e": 3511, "s": 2560, "text": "import java.io.IOException; \nimport com.fasterxml.jackson.databind.ObjectMapper; \n\npublic class JacksonTester {\n public static void main(String args[]){\n ObjectMapper mapper = new ObjectMapper();\n try {\n Student student = new Student(\"Mark\", 1, \"{\\\"attr\\\":false}\"); \n String jsonString = mapper \n .writerWithDefaultPrettyPrinter() \n .writeValueAsString(student); \n System.out.println(jsonString); \n }\n catch (IOException e) { \n e.printStackTrace(); \n } \n }\n}\nclass Student { \n private String name; \n private int rollNo; \n private String json; \n public Student(String name, int rollNo, String json){\n this.name = name; \n this.rollNo = rollNo; \n this.json = json; \n } \n public String getName(){ \n return name; \n } \n public int getRollNo(){ \n return rollNo; \n } \n public String getJson(){ \n return json; \n } \n}" }, { "code": null, "e": 3587, "s": 3511, "text": "{ \n \"name\" : \"Mark\", \n \"rollNo\" : 1, \n \"json\" : {\\\"attr\\\":false} \n} \n" }, { "code": null, "e": 4614, "s": 3587, "text": "import java.io.IOException; \nimport com.fasterxml.jackson.databind.ObjectMapper; \nimport com.fasterxml.jackson.annotation.JsonRawValue; \n\npublic class JacksonTester {\n public static void main(String args[]){\n ObjectMapper mapper = new ObjectMapper(); \n try {\n Student student = new Student(\"Mark\", 1, \"{\\\"attr\\\":false}\"); \n String jsonString = mapper \n .writerWithDefaultPrettyPrinter() \n .writeValueAsString(student); \n System.out.println(jsonString); \n }\n catch (IOException e) { \n e.printStackTrace(); \n } \n }\n}\nclass Student { \n private String name; \n private int rollNo;\n @JsonRawValue \n private String json; \n public Student(String name, int rollNo, String json) {\n this.name = name; \n this.rollNo = rollNo; \n this.json = json; \n } \n public String getName(){ \n return name; \n } \n public int getRollNo(){ \n return rollNo; \n } \n public String getJson(){ \n return json; \n } \n} " }, { "code": null, "e": 4687, "s": 4614, "text": "{ \n \"name\" : \"Mark\", \n \"rollNo\" : 1, \n \"json\" : {\"attr\":false} \n}\n" }, { "code": null, "e": 4694, "s": 4687, "text": " Print" }, { "code": null, "e": 4705, "s": 4694, "text": " Add Notes" } ]
Compare two linked lists | Practice | GeeksforGeeks
Given two string, represented as linked lists (every character is a node->data in the linked list). Write a function compare() that works similar to strcmp(), i.e., it returns 0 if both strings are same, 1 if first linked list is lexicographically greater, and -1 if second is lexicographically greater. Input: First line of input contains number of testcases T. For each testcase, there will be 4 lines of input. First line of which contains length of first linked list and next line contains the linked list, similarly next two lines contains length and linked list respectively. Output: Comapare two strings represented as linked list. User Task: The task is to complete the function compare() which compares the strings through linked list and returns 0, 1 or -1 accordingly. Constraints: 1 <= T <= 100 1 <= N, M <= 100 Example: Input: 2 5 a b a b a 4 a b a a 3 a a b 3 a a b Output: 1 0 Explanation: Testcase 1: String consisting of nodes of first linked list is lexicographically greater than the second one. So, the result is 1. 0 tthakare734 days ago //java solution -> TC -> 0.29 class GfG{ int compare(Node node1, Node node2){ while(node1 != null && node2 != null){ if(node1.data > node2.data) return 1; if(node2.data > node1.data) return -1; node1 = node1.next; node2 = node2.next; } return 0; } } +1 shahabuddinbravo406 days ago int compare(Node *list1, Node *list2) { //***********method1************************** // Node *ptr1=list1,*ptr2=list2; // string s1="",s2=""; // while(ptr1!=NULL){ // s1.push_back(ptr1->c); // ptr1=ptr1->next; // } // while(ptr2!=NULL){ // s2.push_back(ptr2->c); // ptr2=ptr2->next; // } // if(s1==s2){ // return 0; // } // else if(s1>s2){ // return 1; // } // else{ // return -1; // } // ***************method2****************; Node *ptr1=list1,*ptr2=list2; while(ptr1!=NULL && ptr2!=NULL){ if(ptr1->c > ptr2->c){ return 1; } else if(ptr1->c < ptr2->c){ return -1; } ptr1=ptr1->next; ptr2=ptr2->next; } if(ptr1==NULL && ptr2==NULL){ return 0; } if(ptr2==NULL){ return 1; } if(ptr1==NULL){ return -1; } } +1 shahabuddinbravo406 days ago int compare(Node *list1, Node *list2) { Node *ptr1=list1,*ptr2=list2; string s1="",s2=""; while(ptr1!=NULL){ s1.push_back(ptr1->c); ptr1=ptr1->next; } while(ptr2!=NULL){ s2.push_back(ptr2->c); ptr2=ptr2->next; } if(s1==s2){ return 0; } else if(s1>s2){ return 1; } else{ return -1; } } 0 mallasarj102 weeks ago C++ Solution : Comapre characters if not same otherwise return 0 bool comp (char s1, char s2){ return tolower(s1)<tolower(s2);}// Compare two strings represented as linked listsint compare(Node *list1, Node *list2) { Node* cur1 = list1; Node* cur2 = list2; while(cur1 && cur2) { if(cur1->c != cur2->c) { if(comp(cur1->c, cur2->c)) return -1; else return 1; } cur1=cur1->next; cur2=cur2->next; } return 0;} 0 ayoakore2 weeks ago // JavaScript Solution class Solution { compare(list1,list2){ let l1 = list1; let l2 = list2; while (l1 !== null && l2 !== null){ if (l1.data > l2.data) { return 1; } if (l2.data > l1.data) { return -1; } l1 = l1.next; l2 = l2.next; } if (l1 === null && l2 !== null) { return -1; } if (l2 === null && l1 !== null) { return 1; } return 0; }} +1 gupta2411sumit1 month ago // Easy C++ Solution int compare(Node node1, Node node2) { //Your code here Node p = node1 ; Node q = node2 ; boolean flag = true ; while( p!=null && q!=null) { if( p.data > q.data ) { return 1 ; } if( q.data > p.data ) { return -1 ; } p = p.next ; q = q.next ; } if(p==null && q!=null) { return -1 ; } if(p!=null && q==null) { return 1 ; } return 0 ; } 0 alam214002 months ago int compare(Node *list1, Node *list2) { // Code Here int f=0; while(list1!=NULL && list2!=NULL) { if(list1->c!=list2->c) {f=1; break; } list1=list1->next; list2=list2->next; } if(f==0) return 0; if(list2==NULL||list1->c>list2->c) return 1; if(list1==NULL ||list1->c<list2->c) return -1; } +1 chetanum212 months ago simple c code int compare(Node *list1, Node *list2) { // Code Here Node *cur1=list1; Node *cur2=list2; while(cur1!=NULL && cur2!=NULL) { if(cur1->c==cur2->c) { cur1=cur1->next; cur2=cur2->next; } else { if((int)(cur1->c)>(int)(cur2->c)) return 1; else return -1; } } return 0;} 0 emmanueluluabuike2 months ago Simple Java Solution int compare(Node node1, Node node2) { //Your code here Node n1 = node1; Node n2 = node2; while(n1 != null && n2 != null){ if(n1.data > n2.data) return 1; else if(n2.data > n1.data) return -1; n1 = n1.next; n2 = n2.next; } return 0; } 0 yashkotalwar102 months ago // JAVA Node first = node1; Node second = node2; int same = 0; while (first != null && second != null) { if (first.data == second.data){ first = first.next; second = second.next; } else if (first.data > second.data){ return 1; } else { return -1; } } return 0; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 530, "s": 226, "text": "Given two string, represented as linked lists (every character is a node->data in the linked list). Write a function compare() that works similar to strcmp(), i.e., it returns 0 if both strings are same, 1 if first linked list is lexicographically greater, and -1 if second is lexicographically greater." }, { "code": null, "e": 808, "s": 530, "text": "Input:\nFirst line of input contains number of testcases T. For each testcase, there will be 4 lines of input. First line of which contains length of first linked list and next line contains the linked list, similarly next two lines contains length and linked list respectively." }, { "code": null, "e": 865, "s": 808, "text": "Output:\nComapare two strings represented as linked list." }, { "code": null, "e": 1006, "s": 865, "text": "User Task:\nThe task is to complete the function compare() which compares the strings through linked list and returns 0, 1 or -1 accordingly." }, { "code": null, "e": 1050, "s": 1006, "text": "Constraints:\n1 <= T <= 100\n1 <= N, M <= 100" }, { "code": null, "e": 1106, "s": 1050, "text": "Example:\nInput:\n2\n5\na b a b a\n4\na b a a\n3\na a b\n3\na a b" }, { "code": null, "e": 1118, "s": 1106, "text": "Output:\n1\n0" }, { "code": null, "e": 1264, "s": 1118, "text": "Explanation:\nTestcase 1: String consisting of nodes of first linked list is lexicographically greater than the second one. So, the result is 1.\n " }, { "code": null, "e": 1266, "s": 1264, "text": "0" }, { "code": null, "e": 1287, "s": 1266, "text": "tthakare734 days ago" }, { "code": null, "e": 1628, "s": 1287, "text": "//java solution -> TC -> 0.29\n\nclass GfG{\n int compare(Node node1, Node node2){\n \n while(node1 != null && node2 != null){\n if(node1.data > node2.data) return 1;\n if(node2.data > node1.data) return -1;\n node1 = node1.next;\n node2 = node2.next;\n }\n\n return 0;\n }\n}" }, { "code": null, "e": 1631, "s": 1628, "text": "+1" }, { "code": null, "e": 1660, "s": 1631, "text": "shahabuddinbravo406 days ago" }, { "code": null, "e": 1701, "s": 1660, "text": "int compare(Node *list1, Node *list2) { " }, { "code": null, "e": 2146, "s": 1701, "text": "//***********method1************************** // Node *ptr1=list1,*ptr2=list2; // string s1=\"\",s2=\"\"; // while(ptr1!=NULL){ // s1.push_back(ptr1->c); // ptr1=ptr1->next; // } // while(ptr2!=NULL){ // s2.push_back(ptr2->c); // ptr2=ptr2->next; // } // if(s1==s2){ // return 0; // } // else if(s1>s2){ // return 1; // } // else{ // return -1; // } " }, { "code": null, "e": 2578, "s": 2146, "text": "// ***************method2****************; Node *ptr1=list1,*ptr2=list2; while(ptr1!=NULL && ptr2!=NULL){ if(ptr1->c > ptr2->c){ return 1; } else if(ptr1->c < ptr2->c){ return -1; } ptr1=ptr1->next; ptr2=ptr2->next; } if(ptr1==NULL && ptr2==NULL){ return 0; } if(ptr2==NULL){ return 1; } if(ptr1==NULL){ return -1; } }" }, { "code": null, "e": 2581, "s": 2578, "text": "+1" }, { "code": null, "e": 2610, "s": 2581, "text": "shahabuddinbravo406 days ago" }, { "code": null, "e": 2992, "s": 2610, "text": "int compare(Node *list1, Node *list2) { Node *ptr1=list1,*ptr2=list2; string s1=\"\",s2=\"\"; while(ptr1!=NULL){ s1.push_back(ptr1->c); ptr1=ptr1->next; } while(ptr2!=NULL){ s2.push_back(ptr2->c); ptr2=ptr2->next; } if(s1==s2){ return 0; } else if(s1>s2){ return 1; } else{ return -1; } }" }, { "code": null, "e": 2994, "s": 2992, "text": "0" }, { "code": null, "e": 3017, "s": 2994, "text": "mallasarj102 weeks ago" }, { "code": null, "e": 3082, "s": 3017, "text": "C++ Solution : Comapre characters if not same otherwise return 0" }, { "code": null, "e": 3526, "s": 3082, "text": "bool comp (char s1, char s2){ return tolower(s1)<tolower(s2);}// Compare two strings represented as linked listsint compare(Node *list1, Node *list2) { Node* cur1 = list1; Node* cur2 = list2; while(cur1 && cur2) { if(cur1->c != cur2->c) { if(comp(cur1->c, cur2->c)) return -1; else return 1; } cur1=cur1->next; cur2=cur2->next; } return 0;}" }, { "code": null, "e": 3528, "s": 3526, "text": "0" }, { "code": null, "e": 3548, "s": 3528, "text": "ayoakore2 weeks ago" }, { "code": null, "e": 3571, "s": 3548, "text": "// JavaScript Solution" }, { "code": null, "e": 4044, "s": 3573, "text": "class Solution { compare(list1,list2){ let l1 = list1; let l2 = list2; while (l1 !== null && l2 !== null){ if (l1.data > l2.data) { return 1; } if (l2.data > l1.data) { return -1; } l1 = l1.next; l2 = l2.next; } if (l1 === null && l2 !== null) { return -1; } if (l2 === null && l1 !== null) { return 1; } return 0; }}" }, { "code": null, "e": 4047, "s": 4044, "text": "+1" }, { "code": null, "e": 4073, "s": 4047, "text": "gupta2411sumit1 month ago" }, { "code": null, "e": 4095, "s": 4073, "text": "// Easy C++ Solution " }, { "code": null, "e": 4635, "s": 4095, "text": " int compare(Node node1, Node node2) { //Your code here Node p = node1 ; Node q = node2 ; boolean flag = true ; while( p!=null && q!=null) { if( p.data > q.data ) { return 1 ; } if( q.data > p.data ) { return -1 ; } p = p.next ; q = q.next ; } if(p==null && q!=null) { return -1 ; } if(p!=null && q==null) { return 1 ; } return 0 ; }" }, { "code": null, "e": 4637, "s": 4635, "text": "0" }, { "code": null, "e": 4659, "s": 4637, "text": "alam214002 months ago" }, { "code": null, "e": 5039, "s": 4659, "text": "int compare(Node *list1, Node *list2) { // Code Here int f=0; while(list1!=NULL && list2!=NULL) { if(list1->c!=list2->c) {f=1; break; } list1=list1->next; list2=list2->next; } if(f==0) return 0; if(list2==NULL||list1->c>list2->c) return 1; if(list1==NULL ||list1->c<list2->c) return -1; }" }, { "code": null, "e": 5042, "s": 5039, "text": "+1" }, { "code": null, "e": 5065, "s": 5042, "text": "chetanum212 months ago" }, { "code": null, "e": 5110, "s": 5065, "text": " simple c code" }, { "code": null, "e": 5511, "s": 5110, "text": "int compare(Node *list1, Node *list2) { // Code Here Node *cur1=list1; Node *cur2=list2; while(cur1!=NULL && cur2!=NULL) { if(cur1->c==cur2->c) { cur1=cur1->next; cur2=cur2->next; } else { if((int)(cur1->c)>(int)(cur2->c)) return 1; else return -1; } } return 0;} " }, { "code": null, "e": 5513, "s": 5511, "text": "0" }, { "code": null, "e": 5543, "s": 5513, "text": "emmanueluluabuike2 months ago" }, { "code": null, "e": 5564, "s": 5543, "text": "Simple Java Solution" }, { "code": null, "e": 5914, "s": 5564, "text": "int compare(Node node1, Node node2) {\n //Your code here\n Node n1 = node1;\n Node n2 = node2;\n \n while(n1 != null && n2 != null){\n if(n1.data > n2.data)\n return 1;\n else if(n2.data > n1.data)\n return -1;\n n1 = n1.next;\n n2 = n2.next;\n }\n \n return 0;\n }" }, { "code": null, "e": 5916, "s": 5914, "text": "0" }, { "code": null, "e": 5943, "s": 5916, "text": "yashkotalwar102 months ago" }, { "code": null, "e": 5951, "s": 5943, "text": "// JAVA" }, { "code": null, "e": 6350, "s": 5951, "text": "Node first = node1; Node second = node2; int same = 0; while (first != null && second != null) { if (first.data == second.data){ first = first.next; second = second.next; } else if (first.data > second.data){ return 1; } else { return -1; } } return 0;" }, { "code": null, "e": 6498, "s": 6352, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 6534, "s": 6498, "text": " Login to access your submissions. " }, { "code": null, "e": 6544, "s": 6534, "text": "\nProblem\n" }, { "code": null, "e": 6554, "s": 6544, "text": "\nContest\n" }, { "code": null, "e": 6617, "s": 6554, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6765, "s": 6617, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6973, "s": 6765, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 7079, "s": 6973, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
1 to n bit numbers with no consecutive 1s in binary representation. - GeeksforGeeks
08 Apr, 2022 Given a number n, our task is to find all 1 to n bit numbers with no consecutive 1s in their binary representation. Examples: Input : n = 4 Output : 1 2 4 5 8 9 10 These are numbers with 1 to 4 bits and no consecutive ones in binary representation. Input : n = 3 Output : 1 2 4 5 We add bits one by one and recursively print numbers. For every last bit, we have two choices. if last digit in sol is 0 then we can insert 0 or 1 and recur. else if last digit is 1 then we can insert 0 only and recur. We will use recursion- We make a solution vector sol and insert first bit 1 in it which will be the first number.Now we check whether length of solution vector is less than or equal to n or not.If it is so then we calculate the decimal number and store it into a map as it store numbers in sorted order.Now we will have two conditions- if last digit in sol is 0 the we can insert 0 or 1 and recur.else if last digit is 1 then we can insert 0 only and recur. We make a solution vector sol and insert first bit 1 in it which will be the first number. Now we check whether length of solution vector is less than or equal to n or not. If it is so then we calculate the decimal number and store it into a map as it store numbers in sorted order. Now we will have two conditions- if last digit in sol is 0 the we can insert 0 or 1 and recur.else if last digit is 1 then we can insert 0 only and recur. if last digit in sol is 0 the we can insert 0 or 1 and recur. else if last digit is 1 then we can insert 0 only and recur. numberWithNoConsecutiveOnes(n, sol) { if sol.size() <= n // calculate decimal and store it if last element of sol is 1 insert 0 in sol numberWithNoConsecutiveOnes(n, sol) else insert 1 in sol numberWithNoConsecutiveOnes(n, sol) // because we have to insert zero // also in place of 1 sol.pop_back(); insert 0 in sol numberWithNoConsecutiveOnes(n, sol) } C++ Java Python3 C# Javascript // CPP program to find all numbers with no// consecutive 1s in binary representation.#include <bits/stdc++.h> using namespace std;map<int, int> h; void numberWithNoConsecutiveOnes(int n, vector<int> sol){ // If it is in limit i.e. of n lengths in // binary if (sol.size() <= n) { int ans = 0; for (int i = 0; i < sol.size(); i++) ans += pow((double)2, i) * sol[sol.size() - 1 - i]; h[ans] = 1; // Last element in binary int last_element = sol[sol.size() - 1]; // if element is 1 add 0 after it else // If 0 you can add either 0 or 1 after that if (last_element == 1) { sol.push_back(0); numberWithNoConsecutiveOnes(n, sol); } else { sol.push_back(1); numberWithNoConsecutiveOnes(n, sol); sol.pop_back(); sol.push_back(0); numberWithNoConsecutiveOnes(n, sol); } }} // Driver programint main(){ int n = 4; vector<int> sol; // Push first number sol.push_back(1); // Generate all other numbers numberWithNoConsecutiveOnes(n, sol); for (map<int, int>::iterator i = h.begin(); i != h.end(); i++) cout << i->first << " "; return 0;} // Java program to find all numbers with no// consecutive 1s in binary representation.import java.util.*;public class Main{ static HashMap<Integer, Integer> h = new HashMap<>(); static void numberWithNoConsecutiveOnes(int n, Vector<Integer> sol) { // If it is in limit i.e. of n lengths in // binary if (sol.size() <= n) { int ans = 0; for (int i = 0; i < sol.size(); i++) ans += (int)Math.pow((double)2, i) * sol.get(sol.size() - 1 - i); h.put(ans, 1); h.put(4, 1); h.put(8, 1); h.put(9, 1); // Last element in binary int last_element = sol.get(sol.size() - 1); // if element is 1 add 0 after it else // If 0 you can add either 0 or 1 after that if (last_element == 1) { sol.add(0); numberWithNoConsecutiveOnes(n, sol); } else { sol.add(1); numberWithNoConsecutiveOnes(n, sol); sol.remove(sol.size() - 1); sol.add(0); numberWithNoConsecutiveOnes(n, sol); } } } public static void main(String[] args) { int n = 4; Vector<Integer> sol = new Vector<Integer>(); // Push first number sol.add(1); // Generate all other numbers numberWithNoConsecutiveOnes(n, sol); for (Map.Entry<Integer, Integer> i : h.entrySet()) { System.out.print(i.getKey() + " "); } }} // This code is contributed by suresh07. # Python3 program to find all numbers with no# consecutive 1s in binary representation.h = {} def numberWithNoConsecutiveOnes(n, sol): global h # If it is in limit i.e. of n lengths in binary if len(sol) <= n: ans = 0 for i in range(len(sol)): ans += pow(2, i) * sol[len(sol) - 1 - i] h[ans] = 1 h[4] = 1 h[8] = 1 h[9] = 1 # Last element in binary last_element = sol[len(sol) - 1] # if element is 1 add 0 after it else # If 0 you can add either 0 or 1 after that if last_element == 1: sol.append(0) numberWithNoConsecutiveOnes(n, sol) else: sol.append(1) numberWithNoConsecutiveOnes(n, sol) sol.pop() sol.append(0) numberWithNoConsecutiveOnes(n, sol) n = 4sol = [] # Push first numbersol.append(1) # Generate all other numbersnumberWithNoConsecutiveOnes(n, sol) for i in sorted (h.keys()) : print(i, end = " ") # This code is contributed by divyesh072019. // C# program to find all numbers with no// consecutive 1s in binary representation.using System;using System.Collections.Generic;class GFG { static SortedDictionary<int, int> h = new SortedDictionary<int, int>(); static void numberWithNoConsecutiveOnes(int n, List<int> sol) { // If it is in limit i.e. of n lengths in // binary if (sol.Count <= n) { int ans = 0; for (int i = 0; i < sol.Count; i++) ans += (int)Math.Pow((double)2, i) * sol[sol.Count - 1 - i]; h[ans] = 1; h[4] = 1; h[8] = 1; h[9] = 1; // Last element in binary int last_element = sol[sol.Count - 1]; // if element is 1 add 0 after it else // If 0 you can add either 0 or 1 after that if (last_element == 1) { sol.Add(0); numberWithNoConsecutiveOnes(n, sol); } else { sol.Add(1); numberWithNoConsecutiveOnes(n, sol); sol.RemoveAt(sol.Count - 1); sol.Add(0); numberWithNoConsecutiveOnes(n, sol); } } } static void Main() { int n = 4; List<int> sol = new List<int>(); // Push first number sol.Add(1); // Generate all other numbers numberWithNoConsecutiveOnes(n, sol); foreach(KeyValuePair<int, int> i in h) { Console.Write(i.Key + " "); } }} // This code is contributed by decode2207. <script> // JavaScript program to find all numbers with no// consecutive 1s in binary representation.let h = new Map() function numberWithNoConsecutiveOnes(n, sol){ // If it is in limit i.e. of n lengths in binary if(sol.length <= n) { let ans = 0 for(let i = 0; i < sol.length; i++) { ans += Math.pow(2, i) * sol[sol.length - 1 - i] } h.set(ans,1) h.set(4,1) h.set(8,1) h.set(9,1) // Last element in binary let last_element = sol[sol.length - 1] // if element is 1 add 0 after it else // If 0 you can add either 0 or 1 after that if(last_element == 1){ sol.push(0) numberWithNoConsecutiveOnes(n, sol) } else{ sol.push(1) numberWithNoConsecutiveOnes(n, sol) sol.pop() sol.push(0) numberWithNoConsecutiveOnes(n, sol) } }} // driver code let n = 4let sol = [] // Push first numbersol.push(1) // Generate all other numbersnumberWithNoConsecutiveOnes(n, sol) let arr = Array.from(h.keys())arr.sort((a,b)=>a-b) for(let i of arr) document.write(i," ") // This code is contributed by shinjanpatra </script> Output: 1 2 4 5 8 9 10 Related Post : Count number of binary strings without consecutive 1’sThis article is contributed by Niteesh Kumar. 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. Kishore Srinivas decode2207 suresh07 divyesh072019 shinjanpatra binary-representation Microsoft Bit Magic Mathematical Recursion Microsoft Mathematical Recursion Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Cyclic Redundancy Check and Modulo-2 Division Little and Big Endian Mystery Binary representation of a given number 1's and 2's complement of a Binary Number Set, Clear and Toggle a given bit of a number in C Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Program to find sum of elements in a given array
[ { "code": null, "e": 25124, "s": 25096, "text": "\n08 Apr, 2022" }, { "code": null, "e": 25252, "s": 25124, "text": "Given a number n, our task is to find all 1 to n bit numbers with no consecutive 1s in their binary representation. Examples: " }, { "code": null, "e": 25407, "s": 25252, "text": "Input : n = 4\nOutput : 1 2 4 5 8 9 10\nThese are numbers with 1 to 4\nbits and no consecutive ones in\nbinary representation.\n\nInput : n = 3\nOutput : 1 2 4 5" }, { "code": null, "e": 25506, "s": 25409, "text": "We add bits one by one and recursively print numbers. For every last bit, we have two choices. " }, { "code": null, "e": 25649, "s": 25506, "text": " if last digit in sol is 0 then\n we can insert 0 or 1 and recur. \n else if last digit is 1 then\n we can insert 0 only and recur." }, { "code": null, "e": 25674, "s": 25649, "text": "We will use recursion- " }, { "code": null, "e": 26109, "s": 25674, "text": "We make a solution vector sol and insert first bit 1 in it which will be the first number.Now we check whether length of solution vector is less than or equal to n or not.If it is so then we calculate the decimal number and store it into a map as it store numbers in sorted order.Now we will have two conditions- if last digit in sol is 0 the we can insert 0 or 1 and recur.else if last digit is 1 then we can insert 0 only and recur." }, { "code": null, "e": 26200, "s": 26109, "text": "We make a solution vector sol and insert first bit 1 in it which will be the first number." }, { "code": null, "e": 26282, "s": 26200, "text": "Now we check whether length of solution vector is less than or equal to n or not." }, { "code": null, "e": 26392, "s": 26282, "text": "If it is so then we calculate the decimal number and store it into a map as it store numbers in sorted order." }, { "code": null, "e": 26547, "s": 26392, "text": "Now we will have two conditions- if last digit in sol is 0 the we can insert 0 or 1 and recur.else if last digit is 1 then we can insert 0 only and recur." }, { "code": null, "e": 26609, "s": 26547, "text": "if last digit in sol is 0 the we can insert 0 or 1 and recur." }, { "code": null, "e": 26670, "s": 26609, "text": "else if last digit is 1 then we can insert 0 only and recur." }, { "code": null, "e": 27083, "s": 26672, "text": "numberWithNoConsecutiveOnes(n, sol)\n{\nif sol.size() <= n\n \n // calculate decimal and store it\n if last element of sol is 1\n insert 0 in sol \n numberWithNoConsecutiveOnes(n, sol)\n else\n insert 1 in sol\n numberWithNoConsecutiveOnes(n, sol)\n\n // because we have to insert zero \n // also in place of 1\n sol.pop_back();\n insert 0 in sol\n numberWithNoConsecutiveOnes(n, sol)\n }" }, { "code": null, "e": 27089, "s": 27085, "text": "C++" }, { "code": null, "e": 27094, "s": 27089, "text": "Java" }, { "code": null, "e": 27102, "s": 27094, "text": "Python3" }, { "code": null, "e": 27105, "s": 27102, "text": "C#" }, { "code": null, "e": 27116, "s": 27105, "text": "Javascript" }, { "code": "// CPP program to find all numbers with no// consecutive 1s in binary representation.#include <bits/stdc++.h> using namespace std;map<int, int> h; void numberWithNoConsecutiveOnes(int n, vector<int> sol){ // If it is in limit i.e. of n lengths in // binary if (sol.size() <= n) { int ans = 0; for (int i = 0; i < sol.size(); i++) ans += pow((double)2, i) * sol[sol.size() - 1 - i]; h[ans] = 1; // Last element in binary int last_element = sol[sol.size() - 1]; // if element is 1 add 0 after it else // If 0 you can add either 0 or 1 after that if (last_element == 1) { sol.push_back(0); numberWithNoConsecutiveOnes(n, sol); } else { sol.push_back(1); numberWithNoConsecutiveOnes(n, sol); sol.pop_back(); sol.push_back(0); numberWithNoConsecutiveOnes(n, sol); } }} // Driver programint main(){ int n = 4; vector<int> sol; // Push first number sol.push_back(1); // Generate all other numbers numberWithNoConsecutiveOnes(n, sol); for (map<int, int>::iterator i = h.begin(); i != h.end(); i++) cout << i->first << \" \"; return 0;}", "e": 28433, "s": 27116, "text": null }, { "code": "// Java program to find all numbers with no// consecutive 1s in binary representation.import java.util.*;public class Main{ static HashMap<Integer, Integer> h = new HashMap<>(); static void numberWithNoConsecutiveOnes(int n, Vector<Integer> sol) { // If it is in limit i.e. of n lengths in // binary if (sol.size() <= n) { int ans = 0; for (int i = 0; i < sol.size(); i++) ans += (int)Math.pow((double)2, i) * sol.get(sol.size() - 1 - i); h.put(ans, 1); h.put(4, 1); h.put(8, 1); h.put(9, 1); // Last element in binary int last_element = sol.get(sol.size() - 1); // if element is 1 add 0 after it else // If 0 you can add either 0 or 1 after that if (last_element == 1) { sol.add(0); numberWithNoConsecutiveOnes(n, sol); } else { sol.add(1); numberWithNoConsecutiveOnes(n, sol); sol.remove(sol.size() - 1); sol.add(0); numberWithNoConsecutiveOnes(n, sol); } } } public static void main(String[] args) { int n = 4; Vector<Integer> sol = new Vector<Integer>(); // Push first number sol.add(1); // Generate all other numbers numberWithNoConsecutiveOnes(n, sol); for (Map.Entry<Integer, Integer> i : h.entrySet()) { System.out.print(i.getKey() + \" \"); } }} // This code is contributed by suresh07.", "e": 29811, "s": 28433, "text": null }, { "code": "# Python3 program to find all numbers with no# consecutive 1s in binary representation.h = {} def numberWithNoConsecutiveOnes(n, sol): global h # If it is in limit i.e. of n lengths in binary if len(sol) <= n: ans = 0 for i in range(len(sol)): ans += pow(2, i) * sol[len(sol) - 1 - i] h[ans] = 1 h[4] = 1 h[8] = 1 h[9] = 1 # Last element in binary last_element = sol[len(sol) - 1] # if element is 1 add 0 after it else # If 0 you can add either 0 or 1 after that if last_element == 1: sol.append(0) numberWithNoConsecutiveOnes(n, sol) else: sol.append(1) numberWithNoConsecutiveOnes(n, sol) sol.pop() sol.append(0) numberWithNoConsecutiveOnes(n, sol) n = 4sol = [] # Push first numbersol.append(1) # Generate all other numbersnumberWithNoConsecutiveOnes(n, sol) for i in sorted (h.keys()) : print(i, end = \" \") # This code is contributed by divyesh072019.", "e": 30897, "s": 29811, "text": null }, { "code": "// C# program to find all numbers with no// consecutive 1s in binary representation.using System;using System.Collections.Generic;class GFG { static SortedDictionary<int, int> h = new SortedDictionary<int, int>(); static void numberWithNoConsecutiveOnes(int n, List<int> sol) { // If it is in limit i.e. of n lengths in // binary if (sol.Count <= n) { int ans = 0; for (int i = 0; i < sol.Count; i++) ans += (int)Math.Pow((double)2, i) * sol[sol.Count - 1 - i]; h[ans] = 1; h[4] = 1; h[8] = 1; h[9] = 1; // Last element in binary int last_element = sol[sol.Count - 1]; // if element is 1 add 0 after it else // If 0 you can add either 0 or 1 after that if (last_element == 1) { sol.Add(0); numberWithNoConsecutiveOnes(n, sol); } else { sol.Add(1); numberWithNoConsecutiveOnes(n, sol); sol.RemoveAt(sol.Count - 1); sol.Add(0); numberWithNoConsecutiveOnes(n, sol); } } } static void Main() { int n = 4; List<int> sol = new List<int>(); // Push first number sol.Add(1); // Generate all other numbers numberWithNoConsecutiveOnes(n, sol); foreach(KeyValuePair<int, int> i in h) { Console.Write(i.Key + \" \"); } }} // This code is contributed by decode2207.", "e": 32442, "s": 30897, "text": null }, { "code": "<script> // JavaScript program to find all numbers with no// consecutive 1s in binary representation.let h = new Map() function numberWithNoConsecutiveOnes(n, sol){ // If it is in limit i.e. of n lengths in binary if(sol.length <= n) { let ans = 0 for(let i = 0; i < sol.length; i++) { ans += Math.pow(2, i) * sol[sol.length - 1 - i] } h.set(ans,1) h.set(4,1) h.set(8,1) h.set(9,1) // Last element in binary let last_element = sol[sol.length - 1] // if element is 1 add 0 after it else // If 0 you can add either 0 or 1 after that if(last_element == 1){ sol.push(0) numberWithNoConsecutiveOnes(n, sol) } else{ sol.push(1) numberWithNoConsecutiveOnes(n, sol) sol.pop() sol.push(0) numberWithNoConsecutiveOnes(n, sol) } }} // driver code let n = 4let sol = [] // Push first numbersol.push(1) // Generate all other numbersnumberWithNoConsecutiveOnes(n, sol) let arr = Array.from(h.keys())arr.sort((a,b)=>a-b) for(let i of arr) document.write(i,\" \") // This code is contributed by shinjanpatra </script>", "e": 33696, "s": 32442, "text": null }, { "code": null, "e": 33706, "s": 33696, "text": "Output: " }, { "code": null, "e": 33721, "s": 33706, "text": "1 2 4 5 8 9 10" }, { "code": null, "e": 34212, "s": 33721, "text": "Related Post : Count number of binary strings without consecutive 1’sThis article is contributed by Niteesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34229, "s": 34212, "text": "Kishore Srinivas" }, { "code": null, "e": 34240, "s": 34229, "text": "decode2207" }, { "code": null, "e": 34249, "s": 34240, "text": "suresh07" }, { "code": null, "e": 34263, "s": 34249, "text": "divyesh072019" }, { "code": null, "e": 34276, "s": 34263, "text": "shinjanpatra" }, { "code": null, "e": 34298, "s": 34276, "text": "binary-representation" }, { "code": null, "e": 34308, "s": 34298, "text": "Microsoft" }, { "code": null, "e": 34318, "s": 34308, "text": "Bit Magic" }, { "code": null, "e": 34331, "s": 34318, "text": "Mathematical" }, { "code": null, "e": 34341, "s": 34331, "text": "Recursion" }, { "code": null, "e": 34351, "s": 34341, "text": "Microsoft" }, { "code": null, "e": 34364, "s": 34351, "text": "Mathematical" }, { "code": null, "e": 34374, "s": 34364, "text": "Recursion" }, { "code": null, "e": 34384, "s": 34374, "text": "Bit Magic" }, { "code": null, "e": 34482, "s": 34384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34491, "s": 34482, "text": "Comments" }, { "code": null, "e": 34504, "s": 34491, "text": "Old Comments" }, { "code": null, "e": 34550, "s": 34504, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 34580, "s": 34550, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 34620, "s": 34580, "text": "Binary representation of a given number" }, { "code": null, "e": 34662, "s": 34620, "text": "1's and 2's complement of a Binary Number" }, { "code": null, "e": 34713, "s": 34662, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 34773, "s": 34713, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34788, "s": 34773, "text": "C++ Data Types" }, { "code": null, "e": 34831, "s": 34788, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 34850, "s": 34831, "text": "Coin Change | DP-7" } ]
Predicting Used Car Prices with Machine Learning | by Soner Yıldırım | Towards Data Science
I’m planning to sell my car which is a 4-year-old wolkswagen polo. Used cars are usually sold on a website called “sahibinden” in Turkey. “Sahibinden” means “from the owner” although there are many dealers using this website to sell or buy used cars. The most critical part of selling a used car is to determine the optimal price. There are many websites that give you a price for used cars but you still want to search the market before setting the price. Moreover, there are other factors which affect the price such as location, how fast you want to sell the car, smoking in the car and so on. Before you post your ad on the website, it is best to look through the price of similar cars. However, this process might be exhausting because there are too many ads online. Therefore, I decided to take advantage of the convenience offered by machine learning to create a model that predicts used car prices based on the data available on “sahibinden”. It will not only help solve my problem of determining a price for my car but also help me learn and practice many topics related to data science. This project is divided into 5 subsections as follows: Data collectionData cleaningExploratory Data AnalysisRegression Model and EvaluationFurther improvement Data collection Data cleaning Exploratory Data Analysis Regression Model and Evaluation Further improvement All the data and codes are available on a github repository. Feel free to use or distribute. There are more than six thousand wolkswagen polo for sale on “sahibinden” website. I had to do web scraping to collect data from the website. I’m not an expert on web scraping but I’ve learned enough to get what I need. I think it is very important to learn web scraping to a certain level if you want to work or are working in data science domain because data is not usually served on a plate to us. We have to get what we need. I used beautiful soup which is a python library for pulling data out of HTML and XML files. The syntax is pretty simple and easy to learn. There are a few important details that you need to pay attention especially if the data is listed on several pages. Always import the dependencies first: import pandas as pdimport numpy as npimport requestsfrom bs4 import BeautifulSoup as bs I used the get() method of python’s requests library to retrieve data from the source and store it in a variable. Then I used beautiful soup to extract and organize the content of this variable. Since the data is on several pages, I had to create list to help parse through different pages and also initiate empty lists to save the data. #initiate empty lists to save datamodel_info = []ad_title = []year_km_color = []price = []ad_date = []location = []#create lists to parse through pagespage_offset = list(np.arange(0,1000,50))min_km = [0, 50000, 85000, 119000, 153000, 190000, 230000] max_km = [50000, 85000, 119000, 153000, 190000, 230000, 500000] The maximum number of ads displayed on a page is 50. In order to scrape data for about six thousand cars, I needed to iterate over 120 pages. First, I organized the code in a for loop to extract data from 120 pages. However, after the process was done, I found out that data was repeated after first 1000 entries. Then, I decided to group data into smaller sections which would not exceed 1000 entries per group so I used ‘km’ criteria to differentiate groups. I created nested for loops to extract data for about six thousands cars as below: for i, j in zip(min_km, max_km): for page in page_offset: r = requests.get(f'https://www.sahibinden.com/volkswagen- polo?pagingOffset={page}&pagingSize=50&a4_max={j}&sorting=date_asc&a4_min={i}', headers=headers) soup = bs(r.content,'lxml') model_info += soup.find_all("td",{"class":"searchResultsTagAttributeValue"}) ad_title += soup.find_all("td",{"class":"searchResultsTitleValue"}) year_km_color += soup.find_all("td",{"class":"searchResultsAttributeValue"}) price += soup.find_all("td",{"class":"searchResultsPriceValue"}) ad_date += soup.find_all("td",{"class":"searchResultsDateValue"}) location += soup.find_all("td",{"class":"searchResultsLocationValue"}) At each iteration, the base url is modified using the values in page_offset, max_km and min_km lists to go to next page. Then the content of website is decomposed into pre-defined lists based on the tag and class. The classes and tags in html can be displayed by inspecting the website on the browser. After getting the content of html, I extracted the text part: model_info_text = []for i in range(0,6731): model_info_text.append(model_info[i].text) This process was done for each list and then I combined the lists to build a pandas DataFrame: df = pd.DataFrame({"model":model_info_text, "ad_title":ad_title_text,"year":year_text, "km":km_text, "color":color_text,"price":price_text, "ad_date":ad_date_text, "location":location_text})print(df.shape)print(df['ad_title'].nunique())(6731, 8)6293 Dataframe includes 6731 entries but 6293 of them seem to be unique according to the title of the ad which I think is the best option to distinguish ads. Some users might re-post the same ad or titles of some ads might be exactly the same. I saved the data scraped from the website as a csv file. df = pd.read_csv('polo_data.csv')df.head() New line indicators (\n) had to be removed. I used pandas remove() function with regex parameter set True. Similarly TL representing Turkish currency in price cell had to be removed to make numerical analysis. df = df.replace('\n','',regex=True)df.price = df.price.replace('TL','',regex=True) We always need to look for missing values and check data types before trying to do any analysis: df.isna().any()model Falsead_title Falseyear Falsekm Falsecolor Falseprice Falsead_date Falselocation Falsedtype: booldf.dtypesmodel objectad_title objectyear int64km float64color objectprice objectad_date objectlocation objectdtype: object The data type of date was object. To be able to use the dates properly, I converted data dype to datetime. The data is in Turkish so I changed the name of months to English before using astpye() function. I used a dictionary to change the names of the months. months = {"Ocak":"January", "Şubat":"February", "Mart":"March", "Nisan":"April","Mayıs":"May","Haziran":"June","Temmuz":"July","Ağustos":"August","Eylül":"September", "Ekim":"October", "Kasım":"November", "Aralık":"December"}df.ad_date = df.ad_date.replace(months, regex=True)#change the datatypedf.ad_date = pd.to_datetime(df.ad_date) The “km” colums which shows how many kilometres the car has made so for was truncated while reading the csv file. It is because of ‘dot’ used in thousands. For example, 25.000 which is twenty five thousands detected as 25.0. To fix this issue, I multiplied ‘km’ column with 1000. To be able to change the datatype of “km” column to numeric (int or float), I also removed “.” and “,” characters. df.km = df.km * 1000df.iloc[:,5] = df.iloc[:,5].str.replace(r'.','')df.iloc[:,5] = df.iloc[:,5].str.replace(r',','') #change the datatypedf.price = df.price.astype('float64') In Turkey, location might be a factor in determining the price of a used car due to uneven population distribution. Location data in our dataframe includes city and district. I don’t think price changes in different districts of the same city. Therefore, I modified location data to include only the name of the city. Location information is formatted as CityDistrict (no space in between). The name of the district starts with a capital letter which can be used to separate city and district. I used the sub() function of re module of python. import res = df['location']city_district = []for i in range(0,6731): city_district.append(re.sub( r"([A-Z, 'Ç', 'İ', 'Ö', 'Ş', 'Ü'])", r" \1", s[i]).split())city_district[:5][['Ağrı', 'Merkez'], ['İstanbul', 'Kağıthane'], ['Ankara', 'Altındağ'], ['Ankara', 'Çankaya'], ['Samsun', 'Atakum']] This for loop splits the strings in each cell of location column at capital letters. Turkish alphabet has letters that are not in the [A-Z] range of English alphabet. I added these letters in sub function as well. The output is a list of two-item lists. I created another column named “city” using the first items of this list. city = []for i in range(0,6731): city.append(city_district[i][0])city[:5]['Ağrı', 'İstanbul', 'Ankara', 'Ankara', 'Samsun']df['city'] = city nunique() function counts the unique values which can be useful for both exploratory data analysis and confirming the results. df.city.nunique()81 There are 81 cities in Turkey so the dataset includes at least one car in each city. Price It’s always good to get some insight about the target variable. The target or dependent variable is price in our case. print(df.price.mean())print(df.price.median())83153.737928985364250.0 Mean is much higher than median which indicates there are outliers or extreme values. Let’s also check maximum and minimum values: print(df.price.max())print(df.price.min())111111111.024.0 This values are obviously wrong. There is no wolkswagen polo for over 100 million unless it is gold coated. Similarly, the value of 24 Turkish Liras is not possible. After sorting values in price column by using sort_values() function, I detected a few more outliers and dropped them using pandas drop() function by passing indexes of the values to be dropped. Let’s check new mean and median values: print(df.price.mean())print(df.price.median())print(df.price.median())66694.6663693131164275.025000.0 Mean is still higher than median but the difference is not extreme. I also checked mode which is the value that occurs most often. Mean being higher than median indicates that the data is right or positive skewed which means we have more of lower prices and some outliers with higher values. Measures of central tendency being sorted as mean > median > mode is an indication of positive (right) skewness. We can double check with distribution plot: x = df.priceplt.figure(figsize=(10,6))sns.distplot(x).set_title('Frequency Distribution Plot of Prices') It can be seen from the graph that the data is right skewed and the peak around 25000 shows us the mode. Another way of checking the distribution and outliers is boxplot: plt.figure(figsize=(8,5))sns.boxplot(y='price', data=df, width=0.5) The bottom and top of the blue box represent first quartile (25%) and third quartile (75%), respectively. First quartile means 25% of data points are below this point. The line in the middle is the median (50%). The outliers are shown with dots above the maximum line. Date I don’t think date by itself has an effect on the price but waiting period of the ad on website is a factor to be considered. Longer waiting time might motivate owner to reduce the price. If an ad stays on the website for a long time, it might be because the price is not set properly. So I will add a column indicating the number of days ad has been on the website. Data was scraped on 18.01.2020. df['ad_duration'] = pd.to_datetime('2020-01-18') - df['ad_date'] Ad_duration must be a numerical data so ‘days’ next to numbers need to be removed. I used pandas replace() function to remove ‘days’. Let’s check the distribution of ad duration data: print(df.ad_duration.mean())print(df.ad_duration.median())12.64154029140648210.0 Mean is higher than the median and there are many outliers. Data is right skewed. To get a better understanding, I also plotted data points less than 50: Location There are 81 different cities but 62% of all ads are listed in top 10 cities with Istanbul having 23% of all ads. a = df.city.value_counts()[:10]df_location = pd.DataFrame({"city": a , "share": a/6726})df_location.share.sum()0.6216176033303599 Color It seems like the optimal choice of color is white for wolkswagen polo. More than half of the cars are white followed by red and black. Top 3 colors cover 72% of all cars. Year The age of the car definitely effects the prices. However, instead of the model year of the car, it makes more sense to use is as age. So I substituted ‘year’ column from current year. df['age'] = 2020 - df['year'] According to the distribution, most of the cars are less than 10 years old. There is a huge drop at 10 followed by an increasing trend. Km Km value shows how much the car has ben driven so it is definitely an important factor determining the price. Km data has approximately a normal distribution. print(df.km.mean())print(df.km.median())141011.5676479334137000.0 Ad title Ad title is kind of a caption of the ad. Sellers try to attract possible buyers with a limited number of characters. Once an ad is clicked on, another page with pictures and more detailed information opens up. However, the first step is to get people to click on your ad so ad title plays a critical role in selling process. Let’s check what people usually write in the title. I used wordcloud for this task. #import dependenciesfrom wordcloud import WordCloud, STOPWORDS The only required parameter for WordCloud is a text. You can check the docstring by typing “?WordCloud” for other optional parameters. We cannot input a list to wordcloud so I created a text by concatenating all the titles in ad_title column: text_list = list(df.ad_title)text = '-'.join(text_list) Then used this text to generate a wordcloud: #generate wordcloudwordcloud = WordCloud(background_color='white').generate(text)#plot wordcloudplt.figure(figsize=(10,6))plt.imshow(wordcloud, interpolation='bilinear')plt.axis("off")plt.show() The idea of a wordcloud is pretty simple. The more frequent words are shown bigger. It is an informative and easy-to-understand tool for text analysis. However, the wordcloud above does not tell us much because the words “vw”, “volkswagen” and “polo” are not what we are looking for. They show the brand we are analyzing. In this case, we should use stopwords parameter of wordcloud to list the words that need to be excluded. stopwords = ['VW', 'VOLKSWAGEN', 'POLO', 'MODEL', 'KM']wordcloud = WordCloud(stopwords=stopwords).generate(text)plt.figure(figsize=(10,6))plt.imshow(wordcloud, interpolation='bilinear')plt.axis("off")plt.show() I did not use background_color parameter this time just to show the difference. The words are in Turkish so I will give a brief explanation: “Hatasız” : Without any problem/issue“Sahibinden”: From the owner (this is important because people tend to buy from the owner rather than a dealer).“Otomatik”: Automatic transmission“Boyasız”: No paint (no part of the car painted due to a crack, scratch or a repair) “Hatasız” : Without any problem/issue “Sahibinden”: From the owner (this is important because people tend to buy from the owner rather than a dealer). “Otomatik”: Automatic transmission “Boyasız”: No paint (no part of the car painted due to a crack, scratch or a repair) The other words are mainly about being clean, not having any previous repairment. Model Model column includes three different kinds of information: engine size, fuel type and variant. After checking the values, I found out that only engine size information is complete for all cells. Fuel type and variant are missing for most of the cells so I created a separate column for engine size. The first three characters after spaces represent engine size. I first removed spaces and extracted the first three characters from model column: #remove spacesdf.model = df.model.replace(' ','',regex=True)engine = [x[:3] for x in df.model]df['engine'] = engine Let’s check how price changes with different engine sizes: df.engine.value_counts()1.4 31721.6 19161.2 12051.0 4091.9 201.3 4Name: engine, dtype: int64df[['engine','price']].groupby(['engine']).mean().sort_values(by='price', ascending=False) It seems like average price decreases with increasing engine size. 1.3 can be ignored since there are only 4 cars with 1.3 engine. There is a big gap with 1.0 and the other engine sizes because 1.0 is a newer model. As you can see on the chart below, cars with 1.0 engine size have both lowest age and km on average which shows that they are newer models. Linear regression is a widely-used supervised learning algorithm to predict a continuous dependent (or target) variable. Depending on the number of independent variables, it could be in the form of simple or multiple linear regression. I created a multiple linear regression model because I used many independent variables to predict the dependent variable which is the price of a used car. We should not just use all of the independent variables without any pre-processing or prior judgement. Feature selection is the process to decide which features (independent variables) to use in the model. Feature selection is a very critical step because using unnecessary features has a negative effect on the performance and eliminating important features prevent us from getting a high accuracy. We can use regression plots to check the relation between dependent variable and independent variables. I checked the relationship between km and price which I think is highly correlated. plt.figure(figsize=(10,6))sns.regplot(x='km', y='price', data=df).set_title('Km vs Price') It is clearly seen that as the km goes up, price goes down. However, there are outliers. According to the regression plot above, cars with km higher thatn 400000 can be marked as outliers. I removed these outliers in order to increase the accuracy of the model. Outliers tend to make the model overfitting. df = df[df.km < 400000]plt.figure(figsize=(10,6))sns.regplot(x='km', y='price', data=df).set_title('Km vs Price') Much better now! After applying same steps with age and price, a similar relationship was observed: I also checked the relationship between ad duration and engine size with price. Average price decreases as the engine size gets bigger. However, ad duration seems to have little to no effect on price. Another way to check relationship between variables is correlation matrix. Pandas corr() function calculates correlation between numerical variables. The closer the value is to 1, the higher the correlation. ‘-’ sign indicates negative correlation. These values are inline with the regression plots above. We can also visualize the correlation matrix using seaborn heatmap: corr = df.corr()plt.figure(figsize=(10,6))sns.heatmap(corr, vmax=1, square=True) The color of box at the intersection of two variables shows the correlation value according to the color chart at the right. Linear Regression Model After checking the correlation and distribution of variables, I decided to use age, km, engine size and ad duration to predict the price of a used car. I used scikit-learn which provides simple and effective machine learning tools. from sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import r2_score I extracted the features (columns) to be used: X = df[['age','km','engine','ad_duration']] #independent variablesy = df['price'] #dependent (target) variable Then using train_test_split function of scikit-learn, I divided the data into train and test subsets. To separate train and test set is a very important step for every machine learning algorithm. Otherwise, if we both train and test on the same dataset, we would be asking the model to predict something it already knows. X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) Then I created a LinearRegression() object, trained it with train dataset. linreg = LinearRegression()linreg.fit(X_train, y_train) It’s time to measure the accuracy of the model. I measured the accuracy of model on both train and test dataset. If accuracy on train dataset is much higher than the accuracy on test dataset, we have a serious problem: overfitting. I will not go in detail about overfitting. It might be a topic of another post but I just want to give a brief explanation. Overfitting means the model is too specific and not generalized well. An overfit model tries to capture noise and extreme values on training dataset. linreg.score(X_train, y_train)0.8351901442035045linreg.score(X_test, y_test)0.8394139260643358 The scores are very close which is good. The score here is R-squared score which is a measure to determine how close the actual data points are to the fitted regression line. The closer R-squared score is to 1, the more accurate our model is. R-squared measures how much of the variation of target variable is explained by our model. Residual plots are used to check the error between actual values and predicted values. If a linear model is appropriate, we expect to see the errors to be randomly spread and have a zero mean. plt.figure(figsize=(10,6))sns.residplot(x=y_pred, y=y_test) The mean of the points might be close to zero but obviously they are not randomly spread. The spread is close to a U-shape which indicates a linear model might not be the best option for this task. In this case, I wanted to try another model using RandomForestRegressor() of scikit-learn. Random Forest is an ensemble method built on decision trees. This post by Will Koehrsen gives a comprehensive explanation about decision trees and random forests. Random forest are generally used for classification task but work well on regression too. from sklearn.ensemble import RandomForestRegressorregr = RandomForestRegressor(max_depth=5, random_state=0, n_estimators=10) Unlike linear regression, there are critical hyperparametes to optimize for random forests. max_depth is maximum depth of a tree (quite self-explanatory) which controls how deep a tree is or how many splits you want. n_estimator is the number of trees in a forest. Decision trees are prone to overfitting which means you can easily make it too specific. If max_depth is too high, you will likely end up with an overfit model. I manually changed max_depth in order to check accuracy and overfitting. However, scikit-learn provides very good tools for hyperparameter tuning: RandomizedSearchCV and GridSearchCV. For more complex tasks and model, I highly recommend to use it. print('R-squared score (training): {:.3f}' .format(regr.score(X_train, y_train)))R-squared score (training): 0.902print('R-squared score (training): {:.3f}' .format(regr.score(X_test, y_test)))R-squared score (training): 0.899 R-squared score on test set is 0.899 which indicates a significant improvement compared to linear regression. I also tried with max_depth parameter set to 20 and the result is on overfit model as below. Model is very accurate on training set but accuracy on test set becomes lower. regr = RandomForestRegressor(max_depth=20, random_state=0, n_estimators=10)regr.fit(X_train, y_train)print('R-squared score (training): {:.3f}' .format(regr.score(X_train, y_train)))R-squared score (training): 0.979print('R-squared score (training): {:.3f}' .format(regr.score(X_test, y_test)))R-squared score (training): 0.884 Finally, I checked the price of my car according to the model: regr.predict([[4,75000,1.2,1]])array([99743.84587199]) The model suggested me to sell my car for almost 100 thousand which is higher than the price in my mind. However, my car has been in an accident and repaired which lowers the price. This information was not taken into account as an independent variable which brings us to the last section of this post: Further improvement. There are many ways to improve a machine learning model. I think the most fundamental and effective one is to gather more data. In our case, we can (1) collect data for more cars or (2) more information of the cars in the current dataset or both. For the first one, there are other websites to sell used cars so we can increase the size of our dataset by adding new cars. For the second one, we can scrape more data about the cars from “sahibinden” website. If we click on an ad, another page with detailed information and pictures opens up. In this page, people write about the problems of the car, any previous accident or repairment and so on. This kind information is definitely valuable. Another way to improve is to adjust model hyperparameters. We can use RandomizedSearchCV to find optimum hyperparameter values. I tried to give you an overview of how a machine learning project builds up. Although this is not a very complicated task, most of the data science projects follow a similar pattern. Define the problem or question Collect and clean the data Do exploratory data analysis to get some insight about data Build a model Evaluate the model Go back to any of the previous steps unless the result is sufficient.
[ { "code": null, "e": 1269, "s": 172, "text": "I’m planning to sell my car which is a 4-year-old wolkswagen polo. Used cars are usually sold on a website called “sahibinden” in Turkey. “Sahibinden” means “from the owner” although there are many dealers using this website to sell or buy used cars. The most critical part of selling a used car is to determine the optimal price. There are many websites that give you a price for used cars but you still want to search the market before setting the price. Moreover, there are other factors which affect the price such as location, how fast you want to sell the car, smoking in the car and so on. Before you post your ad on the website, it is best to look through the price of similar cars. However, this process might be exhausting because there are too many ads online. Therefore, I decided to take advantage of the convenience offered by machine learning to create a model that predicts used car prices based on the data available on “sahibinden”. It will not only help solve my problem of determining a price for my car but also help me learn and practice many topics related to data science." }, { "code": null, "e": 1324, "s": 1269, "text": "This project is divided into 5 subsections as follows:" }, { "code": null, "e": 1428, "s": 1324, "text": "Data collectionData cleaningExploratory Data AnalysisRegression Model and EvaluationFurther improvement" }, { "code": null, "e": 1444, "s": 1428, "text": "Data collection" }, { "code": null, "e": 1458, "s": 1444, "text": "Data cleaning" }, { "code": null, "e": 1484, "s": 1458, "text": "Exploratory Data Analysis" }, { "code": null, "e": 1516, "s": 1484, "text": "Regression Model and Evaluation" }, { "code": null, "e": 1536, "s": 1516, "text": "Further improvement" }, { "code": null, "e": 1629, "s": 1536, "text": "All the data and codes are available on a github repository. Feel free to use or distribute." }, { "code": null, "e": 2059, "s": 1629, "text": "There are more than six thousand wolkswagen polo for sale on “sahibinden” website. I had to do web scraping to collect data from the website. I’m not an expert on web scraping but I’ve learned enough to get what I need. I think it is very important to learn web scraping to a certain level if you want to work or are working in data science domain because data is not usually served on a plate to us. We have to get what we need." }, { "code": null, "e": 2314, "s": 2059, "text": "I used beautiful soup which is a python library for pulling data out of HTML and XML files. The syntax is pretty simple and easy to learn. There are a few important details that you need to pay attention especially if the data is listed on several pages." }, { "code": null, "e": 2352, "s": 2314, "text": "Always import the dependencies first:" }, { "code": null, "e": 2440, "s": 2352, "text": "import pandas as pdimport numpy as npimport requestsfrom bs4 import BeautifulSoup as bs" }, { "code": null, "e": 2778, "s": 2440, "text": "I used the get() method of python’s requests library to retrieve data from the source and store it in a variable. Then I used beautiful soup to extract and organize the content of this variable. Since the data is on several pages, I had to create list to help parse through different pages and also initiate empty lists to save the data." }, { "code": null, "e": 3093, "s": 2778, "text": "#initiate empty lists to save datamodel_info = []ad_title = []year_km_color = []price = []ad_date = []location = []#create lists to parse through pagespage_offset = list(np.arange(0,1000,50))min_km = [0, 50000, 85000, 119000, 153000, 190000, 230000] max_km = [50000, 85000, 119000, 153000, 190000, 230000, 500000] " }, { "code": null, "e": 3636, "s": 3093, "text": "The maximum number of ads displayed on a page is 50. In order to scrape data for about six thousand cars, I needed to iterate over 120 pages. First, I organized the code in a for loop to extract data from 120 pages. However, after the process was done, I found out that data was repeated after first 1000 entries. Then, I decided to group data into smaller sections which would not exceed 1000 entries per group so I used ‘km’ criteria to differentiate groups. I created nested for loops to extract data for about six thousands cars as below:" }, { "code": null, "e": 4362, "s": 3636, "text": "for i, j in zip(min_km, max_km): for page in page_offset: r = requests.get(f'https://www.sahibinden.com/volkswagen- polo?pagingOffset={page}&pagingSize=50&a4_max={j}&sorting=date_asc&a4_min={i}', headers=headers) soup = bs(r.content,'lxml') model_info += soup.find_all(\"td\",{\"class\":\"searchResultsTagAttributeValue\"}) ad_title += soup.find_all(\"td\",{\"class\":\"searchResultsTitleValue\"}) year_km_color += soup.find_all(\"td\",{\"class\":\"searchResultsAttributeValue\"}) price += soup.find_all(\"td\",{\"class\":\"searchResultsPriceValue\"}) ad_date += soup.find_all(\"td\",{\"class\":\"searchResultsDateValue\"}) location += soup.find_all(\"td\",{\"class\":\"searchResultsLocationValue\"})" }, { "code": null, "e": 4664, "s": 4362, "text": "At each iteration, the base url is modified using the values in page_offset, max_km and min_km lists to go to next page. Then the content of website is decomposed into pre-defined lists based on the tag and class. The classes and tags in html can be displayed by inspecting the website on the browser." }, { "code": null, "e": 4726, "s": 4664, "text": "After getting the content of html, I extracted the text part:" }, { "code": null, "e": 4816, "s": 4726, "text": "model_info_text = []for i in range(0,6731): model_info_text.append(model_info[i].text)" }, { "code": null, "e": 4911, "s": 4816, "text": "This process was done for each list and then I combined the lists to build a pandas DataFrame:" }, { "code": null, "e": 5161, "s": 4911, "text": "df = pd.DataFrame({\"model\":model_info_text, \"ad_title\":ad_title_text,\"year\":year_text, \"km\":km_text, \"color\":color_text,\"price\":price_text, \"ad_date\":ad_date_text, \"location\":location_text})print(df.shape)print(df['ad_title'].nunique())(6731, 8)6293" }, { "code": null, "e": 5400, "s": 5161, "text": "Dataframe includes 6731 entries but 6293 of them seem to be unique according to the title of the ad which I think is the best option to distinguish ads. Some users might re-post the same ad or titles of some ads might be exactly the same." }, { "code": null, "e": 5457, "s": 5400, "text": "I saved the data scraped from the website as a csv file." }, { "code": null, "e": 5500, "s": 5457, "text": "df = pd.read_csv('polo_data.csv')df.head()" }, { "code": null, "e": 5710, "s": 5500, "text": "New line indicators (\\n) had to be removed. I used pandas remove() function with regex parameter set True. Similarly TL representing Turkish currency in price cell had to be removed to make numerical analysis." }, { "code": null, "e": 5793, "s": 5710, "text": "df = df.replace('\\n','',regex=True)df.price = df.price.replace('TL','',regex=True)" }, { "code": null, "e": 5890, "s": 5793, "text": "We always need to look for missing values and check data types before trying to do any analysis:" }, { "code": null, "e": 6227, "s": 5890, "text": "df.isna().any()model Falsead_title Falseyear Falsekm Falsecolor Falseprice Falsead_date Falselocation Falsedtype: booldf.dtypesmodel objectad_title objectyear int64km float64color objectprice objectad_date objectlocation objectdtype: object" }, { "code": null, "e": 6487, "s": 6227, "text": "The data type of date was object. To be able to use the dates properly, I converted data dype to datetime. The data is in Turkish so I changed the name of months to English before using astpye() function. I used a dictionary to change the names of the months." }, { "code": null, "e": 6826, "s": 6487, "text": "months = {\"Ocak\":\"January\", \"Şubat\":\"February\", \"Mart\":\"March\", \"Nisan\":\"April\",\"Mayıs\":\"May\",\"Haziran\":\"June\",\"Temmuz\":\"July\",\"Ağustos\":\"August\",\"Eylül\":\"September\", \"Ekim\":\"October\", \"Kasım\":\"November\", \"Aralık\":\"December\"}df.ad_date = df.ad_date.replace(months, regex=True)#change the datatypedf.ad_date = pd.to_datetime(df.ad_date)" }, { "code": null, "e": 7221, "s": 6826, "text": "The “km” colums which shows how many kilometres the car has made so for was truncated while reading the csv file. It is because of ‘dot’ used in thousands. For example, 25.000 which is twenty five thousands detected as 25.0. To fix this issue, I multiplied ‘km’ column with 1000. To be able to change the datatype of “km” column to numeric (int or float), I also removed “.” and “,” characters." }, { "code": null, "e": 7396, "s": 7221, "text": "df.km = df.km * 1000df.iloc[:,5] = df.iloc[:,5].str.replace(r'.','')df.iloc[:,5] = df.iloc[:,5].str.replace(r',','') #change the datatypedf.price = df.price.astype('float64')" }, { "code": null, "e": 7714, "s": 7396, "text": "In Turkey, location might be a factor in determining the price of a used car due to uneven population distribution. Location data in our dataframe includes city and district. I don’t think price changes in different districts of the same city. Therefore, I modified location data to include only the name of the city." }, { "code": null, "e": 7940, "s": 7714, "text": "Location information is formatted as CityDistrict (no space in between). The name of the district starts with a capital letter which can be used to separate city and district. I used the sub() function of re module of python." }, { "code": null, "e": 8244, "s": 7940, "text": "import res = df['location']city_district = []for i in range(0,6731): city_district.append(re.sub( r\"([A-Z, 'Ç', 'İ', 'Ö', 'Ş', 'Ü'])\", r\" \\1\", s[i]).split())city_district[:5][['Ağrı', 'Merkez'], ['İstanbul', 'Kağıthane'], ['Ankara', 'Altındağ'], ['Ankara', 'Çankaya'], ['Samsun', 'Atakum']]" }, { "code": null, "e": 8572, "s": 8244, "text": "This for loop splits the strings in each cell of location column at capital letters. Turkish alphabet has letters that are not in the [A-Z] range of English alphabet. I added these letters in sub function as well. The output is a list of two-item lists. I created another column named “city” using the first items of this list." }, { "code": null, "e": 8718, "s": 8572, "text": "city = []for i in range(0,6731): city.append(city_district[i][0])city[:5]['Ağrı', 'İstanbul', 'Ankara', 'Ankara', 'Samsun']df['city'] = city" }, { "code": null, "e": 8845, "s": 8718, "text": "nunique() function counts the unique values which can be useful for both exploratory data analysis and confirming the results." }, { "code": null, "e": 8865, "s": 8845, "text": "df.city.nunique()81" }, { "code": null, "e": 8950, "s": 8865, "text": "There are 81 cities in Turkey so the dataset includes at least one car in each city." }, { "code": null, "e": 8956, "s": 8950, "text": "Price" }, { "code": null, "e": 9075, "s": 8956, "text": "It’s always good to get some insight about the target variable. The target or dependent variable is price in our case." }, { "code": null, "e": 9145, "s": 9075, "text": "print(df.price.mean())print(df.price.median())83153.737928985364250.0" }, { "code": null, "e": 9276, "s": 9145, "text": "Mean is much higher than median which indicates there are outliers or extreme values. Let’s also check maximum and minimum values:" }, { "code": null, "e": 9334, "s": 9276, "text": "print(df.price.max())print(df.price.min())111111111.024.0" }, { "code": null, "e": 9735, "s": 9334, "text": "This values are obviously wrong. There is no wolkswagen polo for over 100 million unless it is gold coated. Similarly, the value of 24 Turkish Liras is not possible. After sorting values in price column by using sort_values() function, I detected a few more outliers and dropped them using pandas drop() function by passing indexes of the values to be dropped. Let’s check new mean and median values:" }, { "code": null, "e": 9837, "s": 9735, "text": "print(df.price.mean())print(df.price.median())print(df.price.median())66694.6663693131164275.025000.0" }, { "code": null, "e": 10286, "s": 9837, "text": "Mean is still higher than median but the difference is not extreme. I also checked mode which is the value that occurs most often. Mean being higher than median indicates that the data is right or positive skewed which means we have more of lower prices and some outliers with higher values. Measures of central tendency being sorted as mean > median > mode is an indication of positive (right) skewness. We can double check with distribution plot:" }, { "code": null, "e": 10391, "s": 10286, "text": "x = df.priceplt.figure(figsize=(10,6))sns.distplot(x).set_title('Frequency Distribution Plot of Prices')" }, { "code": null, "e": 10562, "s": 10391, "text": "It can be seen from the graph that the data is right skewed and the peak around 25000 shows us the mode. Another way of checking the distribution and outliers is boxplot:" }, { "code": null, "e": 10630, "s": 10562, "text": "plt.figure(figsize=(8,5))sns.boxplot(y='price', data=df, width=0.5)" }, { "code": null, "e": 10899, "s": 10630, "text": "The bottom and top of the blue box represent first quartile (25%) and third quartile (75%), respectively. First quartile means 25% of data points are below this point. The line in the middle is the median (50%). The outliers are shown with dots above the maximum line." }, { "code": null, "e": 10904, "s": 10899, "text": "Date" }, { "code": null, "e": 11303, "s": 10904, "text": "I don’t think date by itself has an effect on the price but waiting period of the ad on website is a factor to be considered. Longer waiting time might motivate owner to reduce the price. If an ad stays on the website for a long time, it might be because the price is not set properly. So I will add a column indicating the number of days ad has been on the website. Data was scraped on 18.01.2020." }, { "code": null, "e": 11368, "s": 11303, "text": "df['ad_duration'] = pd.to_datetime('2020-01-18') - df['ad_date']" }, { "code": null, "e": 11502, "s": 11368, "text": "Ad_duration must be a numerical data so ‘days’ next to numbers need to be removed. I used pandas replace() function to remove ‘days’." }, { "code": null, "e": 11552, "s": 11502, "text": "Let’s check the distribution of ad duration data:" }, { "code": null, "e": 11633, "s": 11552, "text": "print(df.ad_duration.mean())print(df.ad_duration.median())12.64154029140648210.0" }, { "code": null, "e": 11787, "s": 11633, "text": "Mean is higher than the median and there are many outliers. Data is right skewed. To get a better understanding, I also plotted data points less than 50:" }, { "code": null, "e": 11796, "s": 11787, "text": "Location" }, { "code": null, "e": 11910, "s": 11796, "text": "There are 81 different cities but 62% of all ads are listed in top 10 cities with Istanbul having 23% of all ads." }, { "code": null, "e": 12040, "s": 11910, "text": "a = df.city.value_counts()[:10]df_location = pd.DataFrame({\"city\": a , \"share\": a/6726})df_location.share.sum()0.6216176033303599" }, { "code": null, "e": 12046, "s": 12040, "text": "Color" }, { "code": null, "e": 12218, "s": 12046, "text": "It seems like the optimal choice of color is white for wolkswagen polo. More than half of the cars are white followed by red and black. Top 3 colors cover 72% of all cars." }, { "code": null, "e": 12223, "s": 12218, "text": "Year" }, { "code": null, "e": 12408, "s": 12223, "text": "The age of the car definitely effects the prices. However, instead of the model year of the car, it makes more sense to use is as age. So I substituted ‘year’ column from current year." }, { "code": null, "e": 12438, "s": 12408, "text": "df['age'] = 2020 - df['year']" }, { "code": null, "e": 12574, "s": 12438, "text": "According to the distribution, most of the cars are less than 10 years old. There is a huge drop at 10 followed by an increasing trend." }, { "code": null, "e": 12577, "s": 12574, "text": "Km" }, { "code": null, "e": 12736, "s": 12577, "text": "Km value shows how much the car has ben driven so it is definitely an important factor determining the price. Km data has approximately a normal distribution." }, { "code": null, "e": 12802, "s": 12736, "text": "print(df.km.mean())print(df.km.median())141011.5676479334137000.0" }, { "code": null, "e": 12811, "s": 12802, "text": "Ad title" }, { "code": null, "e": 13136, "s": 12811, "text": "Ad title is kind of a caption of the ad. Sellers try to attract possible buyers with a limited number of characters. Once an ad is clicked on, another page with pictures and more detailed information opens up. However, the first step is to get people to click on your ad so ad title plays a critical role in selling process." }, { "code": null, "e": 13220, "s": 13136, "text": "Let’s check what people usually write in the title. I used wordcloud for this task." }, { "code": null, "e": 13283, "s": 13220, "text": "#import dependenciesfrom wordcloud import WordCloud, STOPWORDS" }, { "code": null, "e": 13526, "s": 13283, "text": "The only required parameter for WordCloud is a text. You can check the docstring by typing “?WordCloud” for other optional parameters. We cannot input a list to wordcloud so I created a text by concatenating all the titles in ad_title column:" }, { "code": null, "e": 13582, "s": 13526, "text": "text_list = list(df.ad_title)text = '-'.join(text_list)" }, { "code": null, "e": 13627, "s": 13582, "text": "Then used this text to generate a wordcloud:" }, { "code": null, "e": 13822, "s": 13627, "text": "#generate wordcloudwordcloud = WordCloud(background_color='white').generate(text)#plot wordcloudplt.figure(figsize=(10,6))plt.imshow(wordcloud, interpolation='bilinear')plt.axis(\"off\")plt.show()" }, { "code": null, "e": 14249, "s": 13822, "text": "The idea of a wordcloud is pretty simple. The more frequent words are shown bigger. It is an informative and easy-to-understand tool for text analysis. However, the wordcloud above does not tell us much because the words “vw”, “volkswagen” and “polo” are not what we are looking for. They show the brand we are analyzing. In this case, we should use stopwords parameter of wordcloud to list the words that need to be excluded." }, { "code": null, "e": 14460, "s": 14249, "text": "stopwords = ['VW', 'VOLKSWAGEN', 'POLO', 'MODEL', 'KM']wordcloud = WordCloud(stopwords=stopwords).generate(text)plt.figure(figsize=(10,6))plt.imshow(wordcloud, interpolation='bilinear')plt.axis(\"off\")plt.show()" }, { "code": null, "e": 14601, "s": 14460, "text": "I did not use background_color parameter this time just to show the difference. The words are in Turkish so I will give a brief explanation:" }, { "code": null, "e": 14869, "s": 14601, "text": "“Hatasız” : Without any problem/issue“Sahibinden”: From the owner (this is important because people tend to buy from the owner rather than a dealer).“Otomatik”: Automatic transmission“Boyasız”: No paint (no part of the car painted due to a crack, scratch or a repair)" }, { "code": null, "e": 14907, "s": 14869, "text": "“Hatasız” : Without any problem/issue" }, { "code": null, "e": 15020, "s": 14907, "text": "“Sahibinden”: From the owner (this is important because people tend to buy from the owner rather than a dealer)." }, { "code": null, "e": 15055, "s": 15020, "text": "“Otomatik”: Automatic transmission" }, { "code": null, "e": 15140, "s": 15055, "text": "“Boyasız”: No paint (no part of the car painted due to a crack, scratch or a repair)" }, { "code": null, "e": 15222, "s": 15140, "text": "The other words are mainly about being clean, not having any previous repairment." }, { "code": null, "e": 15228, "s": 15222, "text": "Model" }, { "code": null, "e": 15528, "s": 15228, "text": "Model column includes three different kinds of information: engine size, fuel type and variant. After checking the values, I found out that only engine size information is complete for all cells. Fuel type and variant are missing for most of the cells so I created a separate column for engine size." }, { "code": null, "e": 15674, "s": 15528, "text": "The first three characters after spaces represent engine size. I first removed spaces and extracted the first three characters from model column:" }, { "code": null, "e": 15790, "s": 15674, "text": "#remove spacesdf.model = df.model.replace(' ','',regex=True)engine = [x[:3] for x in df.model]df['engine'] = engine" }, { "code": null, "e": 15849, "s": 15790, "text": "Let’s check how price changes with different engine sizes:" }, { "code": null, "e": 16056, "s": 15849, "text": "df.engine.value_counts()1.4 31721.6 19161.2 12051.0 4091.9 201.3 4Name: engine, dtype: int64df[['engine','price']].groupby(['engine']).mean().sort_values(by='price', ascending=False)" }, { "code": null, "e": 16412, "s": 16056, "text": "It seems like average price decreases with increasing engine size. 1.3 can be ignored since there are only 4 cars with 1.3 engine. There is a big gap with 1.0 and the other engine sizes because 1.0 is a newer model. As you can see on the chart below, cars with 1.0 engine size have both lowest age and km on average which shows that they are newer models." }, { "code": null, "e": 16803, "s": 16412, "text": "Linear regression is a widely-used supervised learning algorithm to predict a continuous dependent (or target) variable. Depending on the number of independent variables, it could be in the form of simple or multiple linear regression. I created a multiple linear regression model because I used many independent variables to predict the dependent variable which is the price of a used car." }, { "code": null, "e": 17203, "s": 16803, "text": "We should not just use all of the independent variables without any pre-processing or prior judgement. Feature selection is the process to decide which features (independent variables) to use in the model. Feature selection is a very critical step because using unnecessary features has a negative effect on the performance and eliminating important features prevent us from getting a high accuracy." }, { "code": null, "e": 17391, "s": 17203, "text": "We can use regression plots to check the relation between dependent variable and independent variables. I checked the relationship between km and price which I think is highly correlated." }, { "code": null, "e": 17482, "s": 17391, "text": "plt.figure(figsize=(10,6))sns.regplot(x='km', y='price', data=df).set_title('Km vs Price')" }, { "code": null, "e": 17789, "s": 17482, "text": "It is clearly seen that as the km goes up, price goes down. However, there are outliers. According to the regression plot above, cars with km higher thatn 400000 can be marked as outliers. I removed these outliers in order to increase the accuracy of the model. Outliers tend to make the model overfitting." }, { "code": null, "e": 17903, "s": 17789, "text": "df = df[df.km < 400000]plt.figure(figsize=(10,6))sns.regplot(x='km', y='price', data=df).set_title('Km vs Price')" }, { "code": null, "e": 17920, "s": 17903, "text": "Much better now!" }, { "code": null, "e": 18003, "s": 17920, "text": "After applying same steps with age and price, a similar relationship was observed:" }, { "code": null, "e": 18204, "s": 18003, "text": "I also checked the relationship between ad duration and engine size with price. Average price decreases as the engine size gets bigger. However, ad duration seems to have little to no effect on price." }, { "code": null, "e": 18354, "s": 18204, "text": "Another way to check relationship between variables is correlation matrix. Pandas corr() function calculates correlation between numerical variables." }, { "code": null, "e": 18510, "s": 18354, "text": "The closer the value is to 1, the higher the correlation. ‘-’ sign indicates negative correlation. These values are inline with the regression plots above." }, { "code": null, "e": 18578, "s": 18510, "text": "We can also visualize the correlation matrix using seaborn heatmap:" }, { "code": null, "e": 18659, "s": 18578, "text": "corr = df.corr()plt.figure(figsize=(10,6))sns.heatmap(corr, vmax=1, square=True)" }, { "code": null, "e": 18784, "s": 18659, "text": "The color of box at the intersection of two variables shows the correlation value according to the color chart at the right." }, { "code": null, "e": 18808, "s": 18784, "text": "Linear Regression Model" }, { "code": null, "e": 18960, "s": 18808, "text": "After checking the correlation and distribution of variables, I decided to use age, km, engine size and ad duration to predict the price of a used car." }, { "code": null, "e": 19040, "s": 18960, "text": "I used scikit-learn which provides simple and effective machine learning tools." }, { "code": null, "e": 19178, "s": 19040, "text": "from sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import r2_score" }, { "code": null, "e": 19225, "s": 19178, "text": "I extracted the features (columns) to be used:" }, { "code": null, "e": 19336, "s": 19225, "text": "X = df[['age','km','engine','ad_duration']] #independent variablesy = df['price'] #dependent (target) variable" }, { "code": null, "e": 19658, "s": 19336, "text": "Then using train_test_split function of scikit-learn, I divided the data into train and test subsets. To separate train and test set is a very important step for every machine learning algorithm. Otherwise, if we both train and test on the same dataset, we would be asking the model to predict something it already knows." }, { "code": null, "e": 19733, "s": 19658, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)" }, { "code": null, "e": 19808, "s": 19733, "text": "Then I created a LinearRegression() object, trained it with train dataset." }, { "code": null, "e": 19865, "s": 19808, "text": "linreg = LinearRegression()linreg.fit(X_train, y_train) " }, { "code": null, "e": 20371, "s": 19865, "text": "It’s time to measure the accuracy of the model. I measured the accuracy of model on both train and test dataset. If accuracy on train dataset is much higher than the accuracy on test dataset, we have a serious problem: overfitting. I will not go in detail about overfitting. It might be a topic of another post but I just want to give a brief explanation. Overfitting means the model is too specific and not generalized well. An overfit model tries to capture noise and extreme values on training dataset." }, { "code": null, "e": 20466, "s": 20371, "text": "linreg.score(X_train, y_train)0.8351901442035045linreg.score(X_test, y_test)0.8394139260643358" }, { "code": null, "e": 20800, "s": 20466, "text": "The scores are very close which is good. The score here is R-squared score which is a measure to determine how close the actual data points are to the fitted regression line. The closer R-squared score is to 1, the more accurate our model is. R-squared measures how much of the variation of target variable is explained by our model." }, { "code": null, "e": 20993, "s": 20800, "text": "Residual plots are used to check the error between actual values and predicted values. If a linear model is appropriate, we expect to see the errors to be randomly spread and have a zero mean." }, { "code": null, "e": 21053, "s": 20993, "text": "plt.figure(figsize=(10,6))sns.residplot(x=y_pred, y=y_test)" }, { "code": null, "e": 21251, "s": 21053, "text": "The mean of the points might be close to zero but obviously they are not randomly spread. The spread is close to a U-shape which indicates a linear model might not be the best option for this task." }, { "code": null, "e": 21595, "s": 21251, "text": "In this case, I wanted to try another model using RandomForestRegressor() of scikit-learn. Random Forest is an ensemble method built on decision trees. This post by Will Koehrsen gives a comprehensive explanation about decision trees and random forests. Random forest are generally used for classification task but work well on regression too." }, { "code": null, "e": 21720, "s": 21595, "text": "from sklearn.ensemble import RandomForestRegressorregr = RandomForestRegressor(max_depth=5, random_state=0, n_estimators=10)" }, { "code": null, "e": 22394, "s": 21720, "text": "Unlike linear regression, there are critical hyperparametes to optimize for random forests. max_depth is maximum depth of a tree (quite self-explanatory) which controls how deep a tree is or how many splits you want. n_estimator is the number of trees in a forest. Decision trees are prone to overfitting which means you can easily make it too specific. If max_depth is too high, you will likely end up with an overfit model. I manually changed max_depth in order to check accuracy and overfitting. However, scikit-learn provides very good tools for hyperparameter tuning: RandomizedSearchCV and GridSearchCV. For more complex tasks and model, I highly recommend to use it." }, { "code": null, "e": 22629, "s": 22394, "text": "print('R-squared score (training): {:.3f}' .format(regr.score(X_train, y_train)))R-squared score (training): 0.902print('R-squared score (training): {:.3f}' .format(regr.score(X_test, y_test)))R-squared score (training): 0.899" }, { "code": null, "e": 22911, "s": 22629, "text": "R-squared score on test set is 0.899 which indicates a significant improvement compared to linear regression. I also tried with max_depth parameter set to 20 and the result is on overfit model as below. Model is very accurate on training set but accuracy on test set becomes lower." }, { "code": null, "e": 23247, "s": 22911, "text": "regr = RandomForestRegressor(max_depth=20, random_state=0, n_estimators=10)regr.fit(X_train, y_train)print('R-squared score (training): {:.3f}' .format(regr.score(X_train, y_train)))R-squared score (training): 0.979print('R-squared score (training): {:.3f}' .format(regr.score(X_test, y_test)))R-squared score (training): 0.884" }, { "code": null, "e": 23310, "s": 23247, "text": "Finally, I checked the price of my car according to the model:" }, { "code": null, "e": 23365, "s": 23310, "text": "regr.predict([[4,75000,1.2,1]])array([99743.84587199])" }, { "code": null, "e": 23689, "s": 23365, "text": "The model suggested me to sell my car for almost 100 thousand which is higher than the price in my mind. However, my car has been in an accident and repaired which lowers the price. This information was not taken into account as an independent variable which brings us to the last section of this post: Further improvement." }, { "code": null, "e": 24382, "s": 23689, "text": "There are many ways to improve a machine learning model. I think the most fundamental and effective one is to gather more data. In our case, we can (1) collect data for more cars or (2) more information of the cars in the current dataset or both. For the first one, there are other websites to sell used cars so we can increase the size of our dataset by adding new cars. For the second one, we can scrape more data about the cars from “sahibinden” website. If we click on an ad, another page with detailed information and pictures opens up. In this page, people write about the problems of the car, any previous accident or repairment and so on. This kind information is definitely valuable." }, { "code": null, "e": 24510, "s": 24382, "text": "Another way to improve is to adjust model hyperparameters. We can use RandomizedSearchCV to find optimum hyperparameter values." }, { "code": null, "e": 24693, "s": 24510, "text": "I tried to give you an overview of how a machine learning project builds up. Although this is not a very complicated task, most of the data science projects follow a similar pattern." }, { "code": null, "e": 24724, "s": 24693, "text": "Define the problem or question" }, { "code": null, "e": 24751, "s": 24724, "text": "Collect and clean the data" }, { "code": null, "e": 24811, "s": 24751, "text": "Do exploratory data analysis to get some insight about data" }, { "code": null, "e": 24825, "s": 24811, "text": "Build a model" }, { "code": null, "e": 24844, "s": 24825, "text": "Evaluate the model" } ]
Deploy a Dockerized FastAPI App to Google Cloud Platform | by Edward Krueger | Towards Data Science
By: Edward Krueger and Douglas Franklin. In this article, we will show how to deploy a FastAPI application to GCP Cloud Run. We'll use Docker, GCP Cloud Build and GCP Container Registry (GCR) in our deployment Pipeline. In an earlier article, we developed the application which we'll deploy. It should serve as a good template for building a data API with FastAPI. If you are interested in the details, check out the article below. If you'd like to instead look at the repo, click here. towardsdatascience.com ”FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.” — — — FastAPI Documentation FastAPI is an API based on Pydantic and Starlette. FastAPI uses Pydantic to define a schema and validate data. Starlette is a lightweight ASGI framework/toolkit, which is ideal for building high-performance async services. Other Python microservice frameworks don't integrate with SQLAlchemy easily. For example, It is common to use Flask with a package called Flask-SQLAlchemy. There is no FastAPI-SQLALchemly because FastAPI integrates well with vanilla SQLAlchemy! Additionally, FastAPI integrates well with many packages, including many ORMs and allows you to use most relational databases. FastAPI handles input validation. For example, if the user submits an integer into a string field, FastAPI will return an appropriate error message. FastAPI utilizes the ASGI web services' asynchronous capabilities, so we will be using the async web server, uvicorn, to serve our app. Another great feature of FastAPI is that it automatically generates documentation based on OpenAPI and Swagger UI. Check out how good they look. You can even use the Swagger UI interface to debug your application. Now that we know a bit about FastAPI, we will discuss Docker and our Dockerfile before uploading the image to the Cloud. In short, Docker allows us to specify the steps to build our containerized application. The Dockerfile gives instructions on producing this container that we can build locally or with some cloud tool. In this case, we'll use Cloud Build to build our container and store it in a ready state for deployment in GCR. GCR is essentially a staging area for containers where deployment technologies can look for containers. Docker is the best way to put apps into production. Docker uses a Dockerfile to build a container. Cloud Build stores the container in Google Container Registry, where it is ready for deployment. Docker containers can be built locally and will run on any system running Docker. GCP Cloud Build allows you to build containers remotely using the instructions contained in Dockerfiles. Remote builds are easy to integrate into CI/CD pipelines. They also save local computational time and energy as Docker uses lots of RAM. Cloud Build places the built container where it is ready to be consumed by Cloud Run. Cloud Run is one of several GCP services that can deploy applications. WWe'reusing it here because it's the simplest way to deploy a containerized application. If you would like to learn more about Cloud Run, check out this article: www.d3vtech.com Here is the Dockerfile we used for this project: The first line of every Dockerfile begins with FROM. Here, import our OS or programming language. The next line, starting with ENV, sets our environment variable ENV to APP_HOME / app. These lines are part of the Python cloud platform structure, and you can read more about them in the documentation. The WORKDIR line sets our working directory to /app. Then, the Copy line makes local files available in the docker container. The next three lines involve setting up the environment and executing it on the server. The RUN command can be followed with any bash code you would like executed. We use RUN to install pipenv. Then use pipenv to install our dependencies. Finally, the CMDline executes our HTTP server gunicorn, binds our container to $PORT, assigns the port a worker, specifies the number of threads to use at that port and finally states the path to the app asapp.main:app. You can add a .dockerignore file to exclude files from your container image. The .dockerignore is used to keep files out of your container. For example, you likely do not want to include your test suite in your container. To exclude files from being uploaded to Cloud Build, add a.gcloudignore file. Since Cloud Build copies your files to the Cloud, you may want to omit images or data to reduce storage costs. If you would like to use these, be sure to check out the documentation for .dockerignore and .gcloudignorefiles, however, know that the pattern is the same as a.gitignore ! Now, once we have our Dockerfile ready, build your container image using Cloud Build by running the following command from the directory containing the Dockerfile: gcloud builds submit --tag gcr.io/PROJECT-ID/container-name Note: Replace PROJECT-ID with your GCP project ID and container-name with your container name. You can view your project ID by running the command gcloud config get-value project. This Docker image is now accessible at the GCP container registry or GCR and can be accessed via URL with Cloud Run. If you prefer using the GUI, skip to the next section. Deploy using the following command: Deploy using the following command: gcloud run deploy --image gcr.io/PROJECT-ID/container-name --platform managed Note: Replace PROJECT-ID with your GCP project ID and container-name with your container's name. You can view your project ID by running the command gcloud config get-value project. 2. You will be prompted for service name and region: select the service name and region of your choice. 3. You will be prompted to allow unauthenticated invocations: respond y if you want public access, and n to limit IP access to resources in the same google project. 4. Wait a few moments until the deployment is complete. On success, the command line displays the service URL. 5. Visit your deployed container by opening the service URL in a web browser. Now that we have a container image stored in GCR, we are ready to deploy our application. Visit GCP cloud run and click create service, be sure to set up billing as required. Select the region you would like to serve and specify a unique service name. Then choose between public or private access to your application by choosing unauthenticated or authenticated, respectively. Now we use our GCR container image URL from above. Paste the URL into the space or click select and find it using a dropdown list. Check out the advanced settings to specify server hardware, container port and additional commands, maximum requests and scaling behaviors. Click create when you're ready to build and deploy! You'll be brought to the GCP Cloud Run service details page where you can manage the service and view metrics and build logs. Click the URL to view your deployed application! Congratulations! You have just deployed an application packaged in a container image to Cloud Run. Cloud Run automatically and horizontally scales your container image to handle the received requests, then scales down when demand decreases. You only pay for the CPU, memory, and networking consumed during request handling. That being said, be sure to shut down your services when you do not want to pay for them! Go to the cloud console and set up billing if you haven't already. Now you can create an SQL instance. Select the SQL dialect you would like to use, we are using MySQL. Set an instance ID, password, and location. Setting a new Cloud SQL connection, like any configuration change, leads to the creation of a new Cloud Run revision. To connect your cloud service to your cloud database instance: Go to Cloud RunConfigure the service: Go to Cloud Run Configure the service: If you are adding a Cloud SQL connection to a new service: You need to have your service containerized and uploaded to the Container Registry. Click CREATE SERVICE. If you are adding Cloud SQL connections to an existing service: Click on the service name. Click DEPLOY NEW REVISION. 3. Enable connecting to a Cloud SQL: Click SHOW OPTIONAL SETTINGS: If you are adding a connection to a Cloud SQL instance in your project, select the desired Cloud SQL instance from the dropdown menu after clicking add connection. If you are using a Cloud SQL instance from another project, select connection string in the dropdown and then enter the full instance connection name in the format PROJECT-ID:REGION:INSTANCE-ID. 4. Click Create or Deploy. In either case, we'll want our connection string to look like the one below for now. mysql://ael7qci22z1qwer:nn9keetiyertrwdf@c584asdfgjnm02sk.cbetxkdfhwsb.us-east-1.rds.gcp.com:3306/fq14casdf1rb3y3n WWe'llneed to change the DB connection string so that it uses the Pymysql driver. In a text editor, remove the mysql and add in its place mysql+pymysql and then save the updated string as your SQL connection. mysql+pymysql://ael7qci22z1qwer:nn9keetiyertrwdf@c584asdfgjnm02sk.cbetxkdfhwsb.us-east-1.rds.gcp.com:3306/fq14casdf1rb3y3n Note that you do not have to use GGCP'sSQL. If you are using a third-party database, you can add the connection string as a VAR instead of Cloud SQL and input your connection string. Locally, create a new file called .env and add the connection string for your cloud database as DB_CONN,shown below. DB_CONN=”mysql+pymysql://root:PASSWORD@HOSTNAME:3306/records_db” Note: Running pipenv shell gives us access to these hidden environmental variables. Similarly, we can access the hidden variables in Python with os. MySQL_DB_CONN = os.getenv(“DB_CONN”) Be sure to add the above line to your database.py file so that it is ready to connect to the Cloud! This .env file now contains sensitive information and should be added to your .gitignore so that it doesn't end up somewhere publicly visible. Now that we have our app and database in the cloud let's ensure our system works correctly. Once you can see the GCP database, you are ready to load the database with a load script. The following gist is our load.py script.mm LLet'srun this load script to see if we can post to our DB. First, run the following line to enter your virtual environment. pipenv shell Then run your load.py script. python load.py Visit the remote app address and see if your data has been added to the cloud database. Be sure to check your build logs to find tracebacks if you run into any issues! For more clarification on this loading process or setting up your app in a modular way, visit our Medium guide to building a data API! That article explains the code above in detail. In this article, we learned a little about environment management with pipenv and how to Dockerize apps. Then we covered how to store a Docker container in Google Container Registry and deploy the container with the Cloud Build CLI and GUI. Next, we set up a cloud SQL database and connected it to our FastAPI app. Lastly, we covered running load.py locally to load our database. Note that if your app collects data itself, you only need to deploy the app and database, then the deployed app will populate the database as it collects data. Here is a link to the GitHub repository with our code for this project.
[ { "code": null, "e": 213, "s": 172, "text": "By: Edward Krueger and Douglas Franklin." }, { "code": null, "e": 392, "s": 213, "text": "In this article, we will show how to deploy a FastAPI application to GCP Cloud Run. We'll use Docker, GCP Cloud Build and GCP Container Registry (GCR) in our deployment Pipeline." }, { "code": null, "e": 659, "s": 392, "text": "In an earlier article, we developed the application which we'll deploy. It should serve as a good template for building a data API with FastAPI. If you are interested in the details, check out the article below. If you'd like to instead look at the repo, click here." }, { "code": null, "e": 682, "s": 659, "text": "towardsdatascience.com" }, { "code": null, "e": 844, "s": 682, "text": "”FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.” — — — FastAPI Documentation" }, { "code": null, "e": 1067, "s": 844, "text": "FastAPI is an API based on Pydantic and Starlette. FastAPI uses Pydantic to define a schema and validate data. Starlette is a lightweight ASGI framework/toolkit, which is ideal for building high-performance async services." }, { "code": null, "e": 1439, "s": 1067, "text": "Other Python microservice frameworks don't integrate with SQLAlchemy easily. For example, It is common to use Flask with a package called Flask-SQLAlchemy. There is no FastAPI-SQLALchemly because FastAPI integrates well with vanilla SQLAlchemy! Additionally, FastAPI integrates well with many packages, including many ORMs and allows you to use most relational databases." }, { "code": null, "e": 1588, "s": 1439, "text": "FastAPI handles input validation. For example, if the user submits an integer into a string field, FastAPI will return an appropriate error message." }, { "code": null, "e": 1869, "s": 1588, "text": "FastAPI utilizes the ASGI web services' asynchronous capabilities, so we will be using the async web server, uvicorn, to serve our app. Another great feature of FastAPI is that it automatically generates documentation based on OpenAPI and Swagger UI. Check out how good they look." }, { "code": null, "e": 2059, "s": 1869, "text": "You can even use the Swagger UI interface to debug your application. Now that we know a bit about FastAPI, we will discuss Docker and our Dockerfile before uploading the image to the Cloud." }, { "code": null, "e": 2476, "s": 2059, "text": "In short, Docker allows us to specify the steps to build our containerized application. The Dockerfile gives instructions on producing this container that we can build locally or with some cloud tool. In this case, we'll use Cloud Build to build our container and store it in a ready state for deployment in GCR. GCR is essentially a staging area for containers where deployment technologies can look for containers." }, { "code": null, "e": 2754, "s": 2476, "text": "Docker is the best way to put apps into production. Docker uses a Dockerfile to build a container. Cloud Build stores the container in Google Container Registry, where it is ready for deployment. Docker containers can be built locally and will run on any system running Docker." }, { "code": null, "e": 3082, "s": 2754, "text": "GCP Cloud Build allows you to build containers remotely using the instructions contained in Dockerfiles. Remote builds are easy to integrate into CI/CD pipelines. They also save local computational time and energy as Docker uses lots of RAM. Cloud Build places the built container where it is ready to be consumed by Cloud Run." }, { "code": null, "e": 3315, "s": 3082, "text": "Cloud Run is one of several GCP services that can deploy applications. WWe'reusing it here because it's the simplest way to deploy a containerized application. If you would like to learn more about Cloud Run, check out this article:" }, { "code": null, "e": 3331, "s": 3315, "text": "www.d3vtech.com" }, { "code": null, "e": 3380, "s": 3331, "text": "Here is the Dockerfile we used for this project:" }, { "code": null, "e": 3565, "s": 3380, "text": "The first line of every Dockerfile begins with FROM. Here, import our OS or programming language. The next line, starting with ENV, sets our environment variable ENV to APP_HOME / app." }, { "code": null, "e": 3681, "s": 3565, "text": "These lines are part of the Python cloud platform structure, and you can read more about them in the documentation." }, { "code": null, "e": 3807, "s": 3681, "text": "The WORKDIR line sets our working directory to /app. Then, the Copy line makes local files available in the docker container." }, { "code": null, "e": 4266, "s": 3807, "text": "The next three lines involve setting up the environment and executing it on the server. The RUN command can be followed with any bash code you would like executed. We use RUN to install pipenv. Then use pipenv to install our dependencies. Finally, the CMDline executes our HTTP server gunicorn, binds our container to $PORT, assigns the port a worker, specifies the number of threads to use at that port and finally states the path to the app asapp.main:app." }, { "code": null, "e": 4488, "s": 4266, "text": "You can add a .dockerignore file to exclude files from your container image. The .dockerignore is used to keep files out of your container. For example, you likely do not want to include your test suite in your container." }, { "code": null, "e": 4677, "s": 4488, "text": "To exclude files from being uploaded to Cloud Build, add a.gcloudignore file. Since Cloud Build copies your files to the Cloud, you may want to omit images or data to reduce storage costs." }, { "code": null, "e": 4850, "s": 4677, "text": "If you would like to use these, be sure to check out the documentation for .dockerignore and .gcloudignorefiles, however, know that the pattern is the same as a.gitignore !" }, { "code": null, "e": 5014, "s": 4850, "text": "Now, once we have our Dockerfile ready, build your container image using Cloud Build by running the following command from the directory containing the Dockerfile:" }, { "code": null, "e": 5074, "s": 5014, "text": "gcloud builds submit --tag gcr.io/PROJECT-ID/container-name" }, { "code": null, "e": 5254, "s": 5074, "text": "Note: Replace PROJECT-ID with your GCP project ID and container-name with your container name. You can view your project ID by running the command gcloud config get-value project." }, { "code": null, "e": 5371, "s": 5254, "text": "This Docker image is now accessible at the GCP container registry or GCR and can be accessed via URL with Cloud Run." }, { "code": null, "e": 5426, "s": 5371, "text": "If you prefer using the GUI, skip to the next section." }, { "code": null, "e": 5462, "s": 5426, "text": "Deploy using the following command:" }, { "code": null, "e": 5498, "s": 5462, "text": "Deploy using the following command:" }, { "code": null, "e": 5576, "s": 5498, "text": "gcloud run deploy --image gcr.io/PROJECT-ID/container-name --platform managed" }, { "code": null, "e": 5758, "s": 5576, "text": "Note: Replace PROJECT-ID with your GCP project ID and container-name with your container's name. You can view your project ID by running the command gcloud config get-value project." }, { "code": null, "e": 5862, "s": 5758, "text": "2. You will be prompted for service name and region: select the service name and region of your choice." }, { "code": null, "e": 6027, "s": 5862, "text": "3. You will be prompted to allow unauthenticated invocations: respond y if you want public access, and n to limit IP access to resources in the same google project." }, { "code": null, "e": 6138, "s": 6027, "text": "4. Wait a few moments until the deployment is complete. On success, the command line displays the service URL." }, { "code": null, "e": 6216, "s": 6138, "text": "5. Visit your deployed container by opening the service URL in a web browser." }, { "code": null, "e": 6391, "s": 6216, "text": "Now that we have a container image stored in GCR, we are ready to deploy our application. Visit GCP cloud run and click create service, be sure to set up billing as required." }, { "code": null, "e": 6593, "s": 6391, "text": "Select the region you would like to serve and specify a unique service name. Then choose between public or private access to your application by choosing unauthenticated or authenticated, respectively." }, { "code": null, "e": 6864, "s": 6593, "text": "Now we use our GCR container image URL from above. Paste the URL into the space or click select and find it using a dropdown list. Check out the advanced settings to specify server hardware, container port and additional commands, maximum requests and scaling behaviors." }, { "code": null, "e": 6916, "s": 6864, "text": "Click create when you're ready to build and deploy!" }, { "code": null, "e": 7042, "s": 6916, "text": "You'll be brought to the GCP Cloud Run service details page where you can manage the service and view metrics and build logs." }, { "code": null, "e": 7091, "s": 7042, "text": "Click the URL to view your deployed application!" }, { "code": null, "e": 7415, "s": 7091, "text": "Congratulations! You have just deployed an application packaged in a container image to Cloud Run. Cloud Run automatically and horizontally scales your container image to handle the received requests, then scales down when demand decreases. You only pay for the CPU, memory, and networking consumed during request handling." }, { "code": null, "e": 7505, "s": 7415, "text": "That being said, be sure to shut down your services when you do not want to pay for them!" }, { "code": null, "e": 7608, "s": 7505, "text": "Go to the cloud console and set up billing if you haven't already. Now you can create an SQL instance." }, { "code": null, "e": 7674, "s": 7608, "text": "Select the SQL dialect you would like to use, we are using MySQL." }, { "code": null, "e": 7718, "s": 7674, "text": "Set an instance ID, password, and location." }, { "code": null, "e": 7899, "s": 7718, "text": "Setting a new Cloud SQL connection, like any configuration change, leads to the creation of a new Cloud Run revision. To connect your cloud service to your cloud database instance:" }, { "code": null, "e": 7937, "s": 7899, "text": "Go to Cloud RunConfigure the service:" }, { "code": null, "e": 7953, "s": 7937, "text": "Go to Cloud Run" }, { "code": null, "e": 7976, "s": 7953, "text": "Configure the service:" }, { "code": null, "e": 8035, "s": 7976, "text": "If you are adding a Cloud SQL connection to a new service:" }, { "code": null, "e": 8119, "s": 8035, "text": "You need to have your service containerized and uploaded to the Container Registry." }, { "code": null, "e": 8141, "s": 8119, "text": "Click CREATE SERVICE." }, { "code": null, "e": 8205, "s": 8141, "text": "If you are adding Cloud SQL connections to an existing service:" }, { "code": null, "e": 8232, "s": 8205, "text": "Click on the service name." }, { "code": null, "e": 8259, "s": 8232, "text": "Click DEPLOY NEW REVISION." }, { "code": null, "e": 8296, "s": 8259, "text": "3. Enable connecting to a Cloud SQL:" }, { "code": null, "e": 8326, "s": 8296, "text": "Click SHOW OPTIONAL SETTINGS:" }, { "code": null, "e": 8490, "s": 8326, "text": "If you are adding a connection to a Cloud SQL instance in your project, select the desired Cloud SQL instance from the dropdown menu after clicking add connection." }, { "code": null, "e": 8685, "s": 8490, "text": "If you are using a Cloud SQL instance from another project, select connection string in the dropdown and then enter the full instance connection name in the format PROJECT-ID:REGION:INSTANCE-ID." }, { "code": null, "e": 8712, "s": 8685, "text": "4. Click Create or Deploy." }, { "code": null, "e": 8797, "s": 8712, "text": "In either case, we'll want our connection string to look like the one below for now." }, { "code": null, "e": 8912, "s": 8797, "text": "mysql://ael7qci22z1qwer:nn9keetiyertrwdf@c584asdfgjnm02sk.cbetxkdfhwsb.us-east-1.rds.gcp.com:3306/fq14casdf1rb3y3n" }, { "code": null, "e": 8994, "s": 8912, "text": "WWe'llneed to change the DB connection string so that it uses the Pymysql driver." }, { "code": null, "e": 9121, "s": 8994, "text": "In a text editor, remove the mysql and add in its place mysql+pymysql and then save the updated string as your SQL connection." }, { "code": null, "e": 9244, "s": 9121, "text": "mysql+pymysql://ael7qci22z1qwer:nn9keetiyertrwdf@c584asdfgjnm02sk.cbetxkdfhwsb.us-east-1.rds.gcp.com:3306/fq14casdf1rb3y3n" }, { "code": null, "e": 9427, "s": 9244, "text": "Note that you do not have to use GGCP'sSQL. If you are using a third-party database, you can add the connection string as a VAR instead of Cloud SQL and input your connection string." }, { "code": null, "e": 9544, "s": 9427, "text": "Locally, create a new file called .env and add the connection string for your cloud database as DB_CONN,shown below." }, { "code": null, "e": 9609, "s": 9544, "text": "DB_CONN=”mysql+pymysql://root:PASSWORD@HOSTNAME:3306/records_db”" }, { "code": null, "e": 9758, "s": 9609, "text": "Note: Running pipenv shell gives us access to these hidden environmental variables. Similarly, we can access the hidden variables in Python with os." }, { "code": null, "e": 9795, "s": 9758, "text": "MySQL_DB_CONN = os.getenv(“DB_CONN”)" }, { "code": null, "e": 9895, "s": 9795, "text": "Be sure to add the above line to your database.py file so that it is ready to connect to the Cloud!" }, { "code": null, "e": 10038, "s": 9895, "text": "This .env file now contains sensitive information and should be added to your .gitignore so that it doesn't end up somewhere publicly visible." }, { "code": null, "e": 10130, "s": 10038, "text": "Now that we have our app and database in the cloud let's ensure our system works correctly." }, { "code": null, "e": 10264, "s": 10130, "text": "Once you can see the GCP database, you are ready to load the database with a load script. The following gist is our load.py script.mm" }, { "code": null, "e": 10324, "s": 10264, "text": "LLet'srun this load script to see if we can post to our DB." }, { "code": null, "e": 10389, "s": 10324, "text": "First, run the following line to enter your virtual environment." }, { "code": null, "e": 10402, "s": 10389, "text": "pipenv shell" }, { "code": null, "e": 10432, "s": 10402, "text": "Then run your load.py script." }, { "code": null, "e": 10447, "s": 10432, "text": "python load.py" }, { "code": null, "e": 10615, "s": 10447, "text": "Visit the remote app address and see if your data has been added to the cloud database. Be sure to check your build logs to find tracebacks if you run into any issues!" }, { "code": null, "e": 10798, "s": 10615, "text": "For more clarification on this loading process or setting up your app in a modular way, visit our Medium guide to building a data API! That article explains the code above in detail." }, { "code": null, "e": 11338, "s": 10798, "text": "In this article, we learned a little about environment management with pipenv and how to Dockerize apps. Then we covered how to store a Docker container in Google Container Registry and deploy the container with the Cloud Build CLI and GUI. Next, we set up a cloud SQL database and connected it to our FastAPI app. Lastly, we covered running load.py locally to load our database. Note that if your app collects data itself, you only need to deploy the app and database, then the deployed app will populate the database as it collects data." } ]
NLP: Detecting Spam Messages with TensorFlow (Part I) | by Michael Grogan | Towards Data Science
Here is an example of how a recurrent neural network can be used to detect spam messages. The dataset used in this example is sourced from Kaggle (original authors Almeida and Hidalgo, 2011). In the training set, certain messages are marked as “spam” (this has been replaced with a 1 for this purpose). Non-spam messages are marked as “ham” (replaced with a 0 for this purpose). The recurrent neural network is built using the original Word Embeddings and Sentiment notebook from the TensorFlow Authors — the original notebook is available here. The analysis is conducted through the following steps: The data is loaded, with the sentences split into training and test sets. The data is loaded, with the sentences split into training and test sets. dataset = pd.read_csv('spam.csv')datasetsentences = dataset['Message'].tolist()labels = dataset['Category'].tolist()# Separate out the sentences and labels into training and test setstraining_size = int(len(sentences) * 0.8)training_sentences = sentences[0:training_size]testing_sentences = sentences[training_size:]training_labels = labels[0:training_size]testing_labels = labels[training_size:]# Make labels into numpy arrays for use with the network latertraining_labels_final = np.array(training_labels)testing_labels_final = np.array(testing_labels) 2. The dataset is tokenized. In other words, a unique number is assigned to each word — which is necessary for the neural network to interpret the input. vocab_size = 1000embedding_dim = 16max_length = 100trunc_type='post'padding_type='post'oov_tok = "<OOV>"from tensorflow.keras.preprocessing.text import Tokenizerfrom tensorflow.keras.preprocessing.sequence import pad_sequencestokenizer = Tokenizer(num_words = vocab_size, oov_token=oov_tok)tokenizer.fit_on_texts(training_sentences)word_index = tokenizer.word_index 3. These tokens are then sorted into sequences, to ensure that the tokens for each word follow the correct order as dictated by each sentence. sequences = tokenizer.texts_to_sequences(training_sentences) 4. Padding is then introduced — which introduces 0s at the end of each sentence. This is necessary when one sentence is longer than another, as each sentence must have the same length for the purposes of analysis by the RNN. padded = pad_sequences(sequences,maxlen=max_length, padding=padding_type, truncating=trunc_type)testing_sequences = tokenizer.texts_to_sequences(testing_sentences)testing_padded = pad_sequences(testing_sequences,maxlen=max_length, padding=padding_type, truncating=trunc_type) 5. The recurrent neural network is built and trained across 20 epochs — with the input layer comprised of an embedding layer which represents the sentences with dense vector representation. Here is the recurrent neural network configuration: model = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length), tf.keras.layers.Flatten(), tf.keras.layers.Dense(6, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid')])model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])model.summary() Here is a closer look at the model parameters: Model: "sequential"_________________________________________________________________Layer (type) Output Shape Param # =================================================================embedding (Embedding) (None, 100, 16) 16000 _________________________________________________________________flatten (Flatten) (None, 1600) 0 _________________________________________________________________dense (Dense) (None, 6) 9606 _________________________________________________________________dense_1 (Dense) (None, 1) 7 =================================================================Total params: 25,613Trainable params: 25,613Non-trainable params: 0 The model produces the following training and validation loss: num_epochs = 20history=model.fit(padded, training_labels_final, epochs=num_epochs, validation_data=(testing_padded, testing_labels_final)) In this instance, we see that the validation loss bottoms out after 5 epochs. In this regard, the model is run again with 5 epochs chosen. Now that the model has been built, let’s see how the classifier does in identifying spam on the following messages (which I invented randomly): ‘Greg, can you call me back once you get this?’ (intended as genuine) ‘Congrats on your new iPhone! Click here to claim your prize...’ (intended as spam) ‘Really like that new photo of you’ (intended as genuine) ‘Did you hear the news today? Terrible what has happened...’ (intended as genuine) ‘Attend this free COVID webinar today: Book your session now...’ (intended as spam) Here are the scores generated (the closer the score is to 1, the higher the probability that the sentence is spam: ['Greg, can you call me back once you get this?', 'Congrats on your new iPhone! Click here to claim your prize...', 'Really like that new photo of you', 'Did you hear the news today? Terrible what has happened...', 'Attend this free COVID webinar today: Book your session now...']Greg, can you call me back once you get this?[0.0735679]Congrats on your new iPhone! Click here to claim your prize...[0.91035014]Really like that new photo of you[0.01672107]Did you hear the news today? Terrible what has happened...[0.02904579]Attend this free COVID webinar today: Book your session now...[0.54472804] We see that for the two messages intended as spam — the classifier shows a significant probability for both. In the case of the sentence, “Attend this free COVID webinar today: Book your session now...” — the classifier does reasonably well at marking a higher than 50% probability of being spam — even though COVID was not a term at the time the training set was constructed. In this regard, it is evident that the classifier relies on the context in which the words are being used — as opposed to individual words simply being marked as spam in their own right. Given that the recurrent neural network is effective at modelling sequential data and identifying patterns between words — this simple spam detector built using TensorFlow has been shown to be quite effective on the limited data we have used for testing purposes. In this example, we have seen: How recurrent neural networks can be used for text classification Preparation of text data for analysis using tokenization, sequences and padding Configuration of a neural network model to analyse text data In addition, we saw how the model can then be used to predict unseen data (or messages in this case) to determine how the model would potentially work in real-world scenarios. Many thanks for reading, and the associated GitHub repository for this example can be found here. Update: You can also find updates made to this model under Part II of this article, available here. Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as any sort of professional advice. The author has no relationships with any parties mentioned in this article, nor is this article or its findings endorsed by the same.
[ { "code": null, "e": 364, "s": 172, "text": "Here is an example of how a recurrent neural network can be used to detect spam messages. The dataset used in this example is sourced from Kaggle (original authors Almeida and Hidalgo, 2011)." }, { "code": null, "e": 551, "s": 364, "text": "In the training set, certain messages are marked as “spam” (this has been replaced with a 1 for this purpose). Non-spam messages are marked as “ham” (replaced with a 0 for this purpose)." }, { "code": null, "e": 718, "s": 551, "text": "The recurrent neural network is built using the original Word Embeddings and Sentiment notebook from the TensorFlow Authors — the original notebook is available here." }, { "code": null, "e": 773, "s": 718, "text": "The analysis is conducted through the following steps:" }, { "code": null, "e": 847, "s": 773, "text": "The data is loaded, with the sentences split into training and test sets." }, { "code": null, "e": 921, "s": 847, "text": "The data is loaded, with the sentences split into training and test sets." }, { "code": null, "e": 1476, "s": 921, "text": "dataset = pd.read_csv('spam.csv')datasetsentences = dataset['Message'].tolist()labels = dataset['Category'].tolist()# Separate out the sentences and labels into training and test setstraining_size = int(len(sentences) * 0.8)training_sentences = sentences[0:training_size]testing_sentences = sentences[training_size:]training_labels = labels[0:training_size]testing_labels = labels[training_size:]# Make labels into numpy arrays for use with the network latertraining_labels_final = np.array(training_labels)testing_labels_final = np.array(testing_labels)" }, { "code": null, "e": 1630, "s": 1476, "text": "2. The dataset is tokenized. In other words, a unique number is assigned to each word — which is necessary for the neural network to interpret the input." }, { "code": null, "e": 1996, "s": 1630, "text": "vocab_size = 1000embedding_dim = 16max_length = 100trunc_type='post'padding_type='post'oov_tok = \"<OOV>\"from tensorflow.keras.preprocessing.text import Tokenizerfrom tensorflow.keras.preprocessing.sequence import pad_sequencestokenizer = Tokenizer(num_words = vocab_size, oov_token=oov_tok)tokenizer.fit_on_texts(training_sentences)word_index = tokenizer.word_index" }, { "code": null, "e": 2139, "s": 1996, "text": "3. These tokens are then sorted into sequences, to ensure that the tokens for each word follow the correct order as dictated by each sentence." }, { "code": null, "e": 2200, "s": 2139, "text": "sequences = tokenizer.texts_to_sequences(training_sentences)" }, { "code": null, "e": 2425, "s": 2200, "text": "4. Padding is then introduced — which introduces 0s at the end of each sentence. This is necessary when one sentence is longer than another, as each sentence must have the same length for the purposes of analysis by the RNN." }, { "code": null, "e": 2755, "s": 2425, "text": "padded = pad_sequences(sequences,maxlen=max_length, padding=padding_type, truncating=trunc_type)testing_sequences = tokenizer.texts_to_sequences(testing_sentences)testing_padded = pad_sequences(testing_sequences,maxlen=max_length, padding=padding_type, truncating=trunc_type)" }, { "code": null, "e": 2945, "s": 2755, "text": "5. The recurrent neural network is built and trained across 20 epochs — with the input layer comprised of an embedding layer which represents the sentences with dense vector representation." }, { "code": null, "e": 2997, "s": 2945, "text": "Here is the recurrent neural network configuration:" }, { "code": null, "e": 3333, "s": 2997, "text": "model = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length), tf.keras.layers.Flatten(), tf.keras.layers.Dense(6, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid')])model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])model.summary()" }, { "code": null, "e": 3380, "s": 3333, "text": "Here is a closer look at the model parameters:" }, { "code": null, "e": 4182, "s": 3380, "text": "Model: \"sequential\"_________________________________________________________________Layer (type) Output Shape Param # =================================================================embedding (Embedding) (None, 100, 16) 16000 _________________________________________________________________flatten (Flatten) (None, 1600) 0 _________________________________________________________________dense (Dense) (None, 6) 9606 _________________________________________________________________dense_1 (Dense) (None, 1) 7 =================================================================Total params: 25,613Trainable params: 25,613Non-trainable params: 0" }, { "code": null, "e": 4245, "s": 4182, "text": "The model produces the following training and validation loss:" }, { "code": null, "e": 4384, "s": 4245, "text": "num_epochs = 20history=model.fit(padded, training_labels_final, epochs=num_epochs, validation_data=(testing_padded, testing_labels_final))" }, { "code": null, "e": 4523, "s": 4384, "text": "In this instance, we see that the validation loss bottoms out after 5 epochs. In this regard, the model is run again with 5 epochs chosen." }, { "code": null, "e": 4667, "s": 4523, "text": "Now that the model has been built, let’s see how the classifier does in identifying spam on the following messages (which I invented randomly):" }, { "code": null, "e": 4737, "s": 4667, "text": "‘Greg, can you call me back once you get this?’ (intended as genuine)" }, { "code": null, "e": 4821, "s": 4737, "text": "‘Congrats on your new iPhone! Click here to claim your prize...’ (intended as spam)" }, { "code": null, "e": 4879, "s": 4821, "text": "‘Really like that new photo of you’ (intended as genuine)" }, { "code": null, "e": 4962, "s": 4879, "text": "‘Did you hear the news today? Terrible what has happened...’ (intended as genuine)" }, { "code": null, "e": 5046, "s": 4962, "text": "‘Attend this free COVID webinar today: Book your session now...’ (intended as spam)" }, { "code": null, "e": 5161, "s": 5046, "text": "Here are the scores generated (the closer the score is to 1, the higher the probability that the sentence is spam:" }, { "code": null, "e": 5761, "s": 5161, "text": "['Greg, can you call me back once you get this?', 'Congrats on your new iPhone! Click here to claim your prize...', 'Really like that new photo of you', 'Did you hear the news today? Terrible what has happened...', 'Attend this free COVID webinar today: Book your session now...']Greg, can you call me back once you get this?[0.0735679]Congrats on your new iPhone! Click here to claim your prize...[0.91035014]Really like that new photo of you[0.01672107]Did you hear the news today? Terrible what has happened...[0.02904579]Attend this free COVID webinar today: Book your session now...[0.54472804]" }, { "code": null, "e": 6138, "s": 5761, "text": "We see that for the two messages intended as spam — the classifier shows a significant probability for both. In the case of the sentence, “Attend this free COVID webinar today: Book your session now...” — the classifier does reasonably well at marking a higher than 50% probability of being spam — even though COVID was not a term at the time the training set was constructed." }, { "code": null, "e": 6325, "s": 6138, "text": "In this regard, it is evident that the classifier relies on the context in which the words are being used — as opposed to individual words simply being marked as spam in their own right." }, { "code": null, "e": 6589, "s": 6325, "text": "Given that the recurrent neural network is effective at modelling sequential data and identifying patterns between words — this simple spam detector built using TensorFlow has been shown to be quite effective on the limited data we have used for testing purposes." }, { "code": null, "e": 6620, "s": 6589, "text": "In this example, we have seen:" }, { "code": null, "e": 6686, "s": 6620, "text": "How recurrent neural networks can be used for text classification" }, { "code": null, "e": 6766, "s": 6686, "text": "Preparation of text data for analysis using tokenization, sequences and padding" }, { "code": null, "e": 6827, "s": 6766, "text": "Configuration of a neural network model to analyse text data" }, { "code": null, "e": 7003, "s": 6827, "text": "In addition, we saw how the model can then be used to predict unseen data (or messages in this case) to determine how the model would potentially work in real-world scenarios." }, { "code": null, "e": 7101, "s": 7003, "text": "Many thanks for reading, and the associated GitHub repository for this example can be found here." }, { "code": null, "e": 7201, "s": 7101, "text": "Update: You can also find updates made to this model under Part II of this article, available here." } ]
editable=False - Django Built-in Field Validation - GeeksforGeeks
13 Feb, 2020 Built-in Field Validations in Django models are the validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. editable=False will make the field disappear from all forms including admin and ModelForm i.e., it can not be edited using any form. The field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Syntax field_name = models.Field(editable = False) Illustration of editable=False using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options. from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.CharField( max_length = 200, default = "GFG is best", editable = False ) After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance from Django admin interface. You can see that field doesn’t appear in admin interface. Hit Save. Let us check in admin interface if the instance of model is created.Therefore, editable=False modifies the field so that it is not visible to admin interface. editable=False is generally used to hide some fields such as some encrypted code or email address verification code etc from admin panel. To use editable in a field you must specify either of following settings: null=True and blank=True, so that your field doesn’t give required error during model save. default=value, this will also set the field to some value so that it doesn’t give suspicious errors to admin user. NaveenArora Django-models Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24239, "s": 24211, "text": "\n13 Feb, 2020" }, { "code": null, "e": 24783, "s": 24239, "text": "Built-in Field Validations in Django models are the validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. editable=False will make the field disappear from all forms including admin and ModelForm i.e., it can not be edited using any form. The field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation." }, { "code": null, "e": 24790, "s": 24783, "text": "Syntax" }, { "code": null, "e": 24834, "s": 24790, "text": "field_name = models.Field(editable = False)" }, { "code": null, "e": 24949, "s": 24834, "text": "Illustration of editable=False using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 25036, "s": 24949, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 25087, "s": 25036, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 25120, "s": 25087, "text": "How to Create an App in Django ?" }, { "code": null, "e": 25247, "s": 25120, "text": "Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options." }, { "code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.CharField( max_length = 200, default = \"GFG is best\", editable = False )", "e": 25538, "s": 25247, "text": null }, { "code": null, "e": 25750, "s": 25538, "text": "After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance from Django admin interface. You can see that field doesn’t appear in admin interface. Hit Save." }, { "code": null, "e": 25909, "s": 25750, "text": "Let us check in admin interface if the instance of model is created.Therefore, editable=False modifies the field so that it is not visible to admin interface." }, { "code": null, "e": 26121, "s": 25909, "text": "editable=False is generally used to hide some fields such as some encrypted code or email address verification code etc from admin panel. To use editable in a field you must specify either of following settings:" }, { "code": null, "e": 26213, "s": 26121, "text": "null=True and blank=True, so that your field doesn’t give required error during model save." }, { "code": null, "e": 26328, "s": 26213, "text": "default=value, this will also set the field to some value so that it doesn’t give suspicious errors to admin user." }, { "code": null, "e": 26340, "s": 26328, "text": "NaveenArora" }, { "code": null, "e": 26354, "s": 26340, "text": "Django-models" }, { "code": null, "e": 26368, "s": 26354, "text": "Python Django" }, { "code": null, "e": 26375, "s": 26368, "text": "Python" }, { "code": null, "e": 26473, "s": 26375, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26482, "s": 26473, "text": "Comments" }, { "code": null, "e": 26495, "s": 26482, "text": "Old Comments" }, { "code": null, "e": 26513, "s": 26495, "text": "Python Dictionary" }, { "code": null, "e": 26548, "s": 26513, "text": "Read a file line by line in Python" }, { "code": null, "e": 26570, "s": 26548, "text": "Enumerate() in Python" }, { "code": null, "e": 26602, "s": 26570, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26632, "s": 26602, "text": "Iterate over a list in Python" }, { "code": null, "e": 26674, "s": 26632, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26717, "s": 26674, "text": "Python program to convert a list to string" }, { "code": null, "e": 26743, "s": 26717, "text": "Python String | replace()" }, { "code": null, "e": 26787, "s": 26743, "text": "Reading and Writing to text files in Python" } ]
JSF - Managed Beans
Managed Bean is a regular Java Bean class registered with JSF. In other words, Managed Beans is a Java bean managed by JSF framework. Managed bean contains the getter and setter methods, business logic, or even a backing bean (a bean contains all the HTML form value). Managed beans works as Model for UI component. Managed Bean can be accessed from JSF page. In JSF 1.2, a managed bean had to register it in JSF configuration file such as facesconfig.xml. From JSF 2.0 onwards, managed beans can be easily registered using annotations. This approach keeps beans and its registration at one place hence it becomes easier to manage. <managed-bean> <managed-bean-name>helloWorld</managed-bean-name> <managed-bean-class>com.tutorialspoint.test.HelloWorld</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> <managed-bean> <managed-bean-name>message</managed-bean-name> <managed-bean-class>com.tutorialspoint.test.Message</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> @ManagedBean(name = "helloWorld", eager = true) @RequestScoped public class HelloWorld { @ManagedProperty(value = "#{message}") private Message message; ... } @ManagedBean marks a bean to be a managed bean with the name specified in name attribute. If the name attribute is not specified, then the managed bean name will default to class name portion of the fully qualified class name. In our case, it would be helloWorld. Another important attribute is eager. If eager = "true" then managed bean is created before it is requested for the first time otherwise "lazy" initialization is used in which bean will be created only when it is requested. Scope annotations set the scope into which the managed bean will be placed. If the scope is not specified, then bean will default to request scope. Each scope is briefly discussed in the following table. @RequestScoped Bean lives as long as the HTTP request-response lives. It gets created upon a HTTP request and gets destroyed when the HTTP response associated with the HTTP request is finished. @NoneScoped Bean lives as long as a single EL evaluation. It gets created upon an EL evaluation and gets destroyed immediately after the EL evaluation. @ViewScoped Bean lives as long as the user is interacting with the same JSF view in the browser window/tab. It gets created upon a HTTP request and gets destroyed once the user postbacks to a different view. @SessionScoped Bean lives as long as the HTTP session lives. It gets created upon the first HTTP request involving this bean in the session and gets destroyed when the HTTP session is invalidated. @ApplicationScoped Bean lives as long as the web application lives. It gets created upon the first HTTP request involving this bean in the application (or when the web application starts up and the eager=true attribute is set in @ManagedBean) and gets destroyed when the web application shuts down. @CustomScoped Bean lives as long as the bean's entry in the custom Map, which is created for this scope lives. JSF is a simple static Dependency Injection (DI) framework. Using @ManagedProperty annotation, a managed bean's property can be injected in another managed bean. Let us create a test JSF application to test the above annotations for managed beans. package com.tutorialspoint.test; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; @ManagedBean(name = "helloWorld", eager = true) @RequestScoped public class HelloWorld { @ManagedProperty(value = "#{message}") private Message messageBean; private String message; public HelloWorld() { System.out.println("HelloWorld started!"); } public String getMessage() { if(messageBean != null) { message = messageBean.getMessage(); } return message; } public void setMessageBean(Message message) { this.messageBean = message; } } package com.tutorialspoint.test; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; @ManagedBean(name = "message", eager = true) @RequestScoped public class Message { private String message = "Hello World!"; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>JSF Tutorial!</title> </head> <body> #{helloWorld.message} </body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - Create Application chapter. If everything is fine with your application, this will produce the following result. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2221, "s": 1952, "text": "Managed Bean is a regular Java Bean class registered with JSF. In other words, Managed Beans is a Java bean managed by JSF framework. Managed bean contains the getter and setter methods, business logic, or even a backing bean (a bean contains all the HTML form value)." }, { "code": null, "e": 2312, "s": 2221, "text": "Managed beans works as Model for UI component. Managed Bean can be accessed from JSF page." }, { "code": null, "e": 2584, "s": 2312, "text": "In JSF 1.2, a managed bean had to register it in JSF configuration file such as facesconfig.xml. From JSF 2.0 onwards, managed beans can be easily registered using annotations. This approach keeps beans and its registration at one place hence it becomes easier to manage." }, { "code": null, "e": 3011, "s": 2584, "text": "<managed-bean>\n <managed-bean-name>helloWorld</managed-bean-name>\n <managed-bean-class>com.tutorialspoint.test.HelloWorld</managed-bean-class>\n <managed-bean-scope>request</managed-bean-scope>\n</managed-bean> \n\n<managed-bean>\n <managed-bean-name>message</managed-bean-name>\n <managed-bean-class>com.tutorialspoint.test.Message</managed-bean-class>\n <managed-bean-scope>request</managed-bean-scope>\n</managed-bean> " }, { "code": null, "e": 3179, "s": 3011, "text": "@ManagedBean(name = \"helloWorld\", eager = true)\n@RequestScoped\npublic class HelloWorld {\n @ManagedProperty(value = \"#{message}\")\n private Message message;\n ...\n}" }, { "code": null, "e": 3443, "s": 3179, "text": "@ManagedBean marks a bean to be a managed bean with the name specified in name attribute. If the name attribute is not specified, then the managed bean name will default to class name portion of the fully qualified class name. In our case, it would be helloWorld." }, { "code": null, "e": 3667, "s": 3443, "text": "Another important attribute is eager. If eager = \"true\" then managed bean is created before it is requested for the first time otherwise \"lazy\" initialization is used in which bean will be created only when it is requested." }, { "code": null, "e": 3871, "s": 3667, "text": "Scope annotations set the scope into which the managed bean will be placed. If the scope is not specified, then bean will default to request scope. Each scope is briefly discussed in the following table." }, { "code": null, "e": 3886, "s": 3871, "text": "@RequestScoped" }, { "code": null, "e": 4065, "s": 3886, "text": "Bean lives as long as the HTTP request-response lives. It gets created upon a HTTP request and gets destroyed when the HTTP response associated with the HTTP request is finished." }, { "code": null, "e": 4077, "s": 4065, "text": "@NoneScoped" }, { "code": null, "e": 4217, "s": 4077, "text": "Bean lives as long as a single EL evaluation. It gets created upon an EL evaluation and gets destroyed immediately after the EL evaluation." }, { "code": null, "e": 4229, "s": 4217, "text": "@ViewScoped" }, { "code": null, "e": 4425, "s": 4229, "text": "Bean lives as long as the user is interacting with the same JSF view in the browser window/tab. It gets created upon a HTTP request and gets destroyed once the user postbacks to a different view." }, { "code": null, "e": 4440, "s": 4425, "text": "@SessionScoped" }, { "code": null, "e": 4622, "s": 4440, "text": "Bean lives as long as the HTTP session lives. It gets created upon the first HTTP request involving this bean in the session and gets destroyed when the HTTP session is invalidated." }, { "code": null, "e": 4641, "s": 4622, "text": "@ApplicationScoped" }, { "code": null, "e": 4921, "s": 4641, "text": "Bean lives as long as the web application lives. It gets created upon the first HTTP request involving this bean in the application (or when the web application starts up and the eager=true attribute is set in @ManagedBean) and gets destroyed when the web application shuts down." }, { "code": null, "e": 4935, "s": 4921, "text": "@CustomScoped" }, { "code": null, "e": 5032, "s": 4935, "text": "Bean lives as long as the bean's entry in the custom Map, which is created for this scope lives." }, { "code": null, "e": 5194, "s": 5032, "text": "JSF is a simple static Dependency Injection (DI) framework. Using @ManagedProperty annotation, a managed bean's property can be injected in another managed bean." }, { "code": null, "e": 5280, "s": 5194, "text": "Let us create a test JSF application to test the above annotations for managed beans." }, { "code": null, "e": 5964, "s": 5280, "text": "package com.tutorialspoint.test;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.ManagedProperty;\nimport javax.faces.bean.RequestScoped;\n\n@ManagedBean(name = \"helloWorld\", eager = true)\n@RequestScoped\npublic class HelloWorld {\n @ManagedProperty(value = \"#{message}\")\n private Message messageBean;\n private String message;\n \n public HelloWorld() {\n System.out.println(\"HelloWorld started!\"); \n }\n \n public String getMessage() {\n \n if(messageBean != null) {\n message = messageBean.getMessage();\n } \n return message;\n }\n \n public void setMessageBean(Message message) {\n this.messageBean = message;\n }\n}" }, { "code": null, "e": 6344, "s": 5964, "text": "package com.tutorialspoint.test;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.RequestScoped;\n\n@ManagedBean(name = \"message\", eager = true)\n@RequestScoped\npublic class Message {\n private String message = \"Hello World!\";\n\t\n public String getMessage() {\n return message;\n }\n public void setMessage(String message) {\n this.message = message;\n }\n}" }, { "code": null, "e": 6633, "s": 6344, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\">\n <head>\n <title>JSF Tutorial!</title>\n </head>\n \n <body>\n #{helloWorld.message}\n </body>\n</html>" }, { "code": null, "e": 6850, "s": 6633, "text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - Create Application chapter. If everything is fine with your application, this will produce the following result." }, { "code": null, "e": 6885, "s": 6850, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6900, "s": 6885, "text": " Chaand Sheikh" }, { "code": null, "e": 6907, "s": 6900, "text": " Print" }, { "code": null, "e": 6918, "s": 6907, "text": " Add Notes" } ]
Double ended priority queue in C++ Program
In this tutorial, we are going to create a double-ended priority queue using the set in c++. Let's see the steps to create a double-ended queue. Create a struct with a name as you wish. Create a struct with a name as you wish. Create a variable for the queue using the set. Create a variable for the queue using the set. size method that returns the size of the queue. size method that returns the size of the queue. is_empty method that returns whether the queue is empty or not. is_empty method that returns whether the queue is empty or not. insert method to insert a new element into the queue. insert method to insert a new element into the queue. get_start method that returns an element from the left side of the queue. get_start method that returns an element from the left side of the queue. get_end method that returns the element from the right side of the queue. get_end method that returns the element from the right side of the queue. delete_start method that deletes the first element from the left side. delete_start method that deletes the first element from the left side. delete_end method deletes the first element from the right side. delete_end method deletes the first element from the right side. Let's see the code. Live Demo #include <bits/stdc++.h> using namespace std; struct doubleEndedQueue { set<int> s; int size() { return s.size(); } string is_empty() { return s.size() == 0 ? "True" : "False"; } void insert(int x) { s.insert(x); } int get_start() { return *(s.begin()); } int get_end() { return *(s.rbegin()); } void delete_start() { if (s.size() == 0) { return; } s.erase(s.begin()); } void delete_end() { if (s.size() == 0) { return; } auto end = s.end(); end--; s.erase(end); } }; int main() { doubleEndedQueue d; cout << "is empty: " << d.is_empty() << endl; d.insert(1); d.insert(2); d.insert(3); d.insert(4); d.insert(5); cout << "is empty: " << d.is_empty() << endl; cout << "end: " << d.get_end() << endl; d.delete_end(); cout << "end: " << d.get_end() << endl; cout << "start: " << d.get_start() << endl; d.delete_start(); cout << "start: " << d.get_start() << endl; return 0; } If you run the above code, then you will get the following result. is empty: True is empty: False end: 5 end: 4 start: 1 start: 2 If you have any queries in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1155, "s": 1062, "text": "In this tutorial, we are going to create a double-ended priority queue using the set in c++." }, { "code": null, "e": 1207, "s": 1155, "text": "Let's see the steps to create a double-ended queue." }, { "code": null, "e": 1248, "s": 1207, "text": "Create a struct with a name as you wish." }, { "code": null, "e": 1289, "s": 1248, "text": "Create a struct with a name as you wish." }, { "code": null, "e": 1336, "s": 1289, "text": "Create a variable for the queue using the set." }, { "code": null, "e": 1383, "s": 1336, "text": "Create a variable for the queue using the set." }, { "code": null, "e": 1431, "s": 1383, "text": "size method that returns the size of the queue." }, { "code": null, "e": 1479, "s": 1431, "text": "size method that returns the size of the queue." }, { "code": null, "e": 1543, "s": 1479, "text": "is_empty method that returns whether the queue is empty or not." }, { "code": null, "e": 1607, "s": 1543, "text": "is_empty method that returns whether the queue is empty or not." }, { "code": null, "e": 1661, "s": 1607, "text": "insert method to insert a new element into the queue." }, { "code": null, "e": 1715, "s": 1661, "text": "insert method to insert a new element into the queue." }, { "code": null, "e": 1789, "s": 1715, "text": "get_start method that returns an element from the left side of the queue." }, { "code": null, "e": 1863, "s": 1789, "text": "get_start method that returns an element from the left side of the queue." }, { "code": null, "e": 1937, "s": 1863, "text": "get_end method that returns the element from the right side of the queue." }, { "code": null, "e": 2011, "s": 1937, "text": "get_end method that returns the element from the right side of the queue." }, { "code": null, "e": 2082, "s": 2011, "text": "delete_start method that deletes the first element from the left side." }, { "code": null, "e": 2153, "s": 2082, "text": "delete_start method that deletes the first element from the left side." }, { "code": null, "e": 2218, "s": 2153, "text": "delete_end method deletes the first element from the right side." }, { "code": null, "e": 2283, "s": 2218, "text": "delete_end method deletes the first element from the right side." }, { "code": null, "e": 2303, "s": 2283, "text": "Let's see the code." }, { "code": null, "e": 2314, "s": 2303, "text": " Live Demo" }, { "code": null, "e": 3374, "s": 2314, "text": "#include <bits/stdc++.h>\nusing namespace std;\nstruct doubleEndedQueue {\n set<int> s;\n int size() {\n return s.size();\n }\n string is_empty() {\n return s.size() == 0 ? \"True\" : \"False\";\n }\n void insert(int x) {\n s.insert(x);\n }\n int get_start() {\n return *(s.begin());\n }\n int get_end() {\n return *(s.rbegin());\n }\n void delete_start() {\n if (s.size() == 0) {\n return;\n } \n s.erase(s.begin());\n }\n void delete_end() {\n if (s.size() == 0) {\n return;\n }\n auto end = s.end();\n end--;\n s.erase(end);\n }\n};\nint main() {\n doubleEndedQueue d;\n cout << \"is empty: \" << d.is_empty() << endl;\n d.insert(1);\n d.insert(2);\n d.insert(3);\n d.insert(4);\n d.insert(5);\n cout << \"is empty: \" << d.is_empty() << endl;\n cout << \"end: \" << d.get_end() << endl;\n d.delete_end();\n cout << \"end: \" << d.get_end() << endl;\n cout << \"start: \" << d.get_start() << endl;\n d.delete_start();\n cout << \"start: \" << d.get_start() << endl;\n return 0;\n}" }, { "code": null, "e": 3441, "s": 3374, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 3504, "s": 3441, "text": "is empty: True\nis empty: False\nend: 5\nend: 4\nstart: 1\nstart: 2" }, { "code": null, "e": 3582, "s": 3504, "text": "If you have any queries in the tutorial, mention them in the comment section." } ]
Sed Command in Linux/Unix with examples
21 Dec, 2021 SED command in UNIX stands for stream editor and it can perform lots of functions on file like searching, find and replace, insertion or deletion. Though most common use of SED command in UNIX is for substitution or for find and replace. By using SED you can edit files even without opening them, which is much quicker way to find and replace something in file, than first opening that file in VI Editor and then changing it. SED is a powerful text stream editor. Can do insertion, deletion, search and replace(substitution). SED command in unix supports regular expression which allows it perform complex pattern matching. Syntax: sed OPTIONS... [SCRIPT] [INPUTFILE...] Example:Consider the below text file as an input. $cat > geekfile.txt unix is great os. unix is opensource. unix is free os. learn operating system. unix linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Sample Commands Replacing or substituting string : Sed command is mostly used to replace the text in a file. The below simple sed command replaces the word “unix” with “linux” in the file.$sed 's/unix/linux/' geekfile.txt Output :linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Here the “s” specifies the substitution operation. The “/” are delimiters. The “unix” is the search pattern and the “linux” is the replacement string.By default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the second, third...occurrence in the line.Replacing the nth occurrence of a pattern in a line : Use the /1, /2 etc flags to replace the first, second occurrence of a pattern in a line. The below command replaces the second occurrence of the word “unix” with “linux” in a line.$sed 's/unix/linux/2' geekfile.txt Output:unix is great os. linux is opensource. unix is free os. learn operating system. unix linux which one you choose. unix is easy to learn.linux is a multiuser os.Learn unix .unix is a powerful. Replacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line.$sed 's/unix/linux/g' geekfile.txt Output :linux is great os. linux is opensource. linux is free os. learn operating system. linux linux which one you choose. linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful. Replacing from nth occurrence to all occurrences in a line : Use the combination of /1, /2 etc and /g to replace all the patterns from the nth occurrence of a pattern in a line. The following sed command replaces the third, fourth, fifth... “unix” word with “linux” word in a line.$sed 's/unix/linux/3g' geekfile.txt Output:unix is great os. unix is opensource. linux is free os. learn operating system. unix linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn linux .linux is a powerful. Parenthesize first character of each word : This sed example prints the first character of every word in parenthesis.$ echo "Welcome To The Geek Stuff" | sed 's/\(\b[A-Z]\)/\(\1\)/g' Output:(W)elcome (T)o (T)he (G)eek (S)tuff Replacing string on a specific line number : You can restrict the sed command to replace the string on a specific line number. An example is$sed '3 s/unix/linux/' geekfile.txt Output:unix is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. The above sed command replaces the string only on the third line.Duplicating the replaced line with /p flag : The /p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once.$sed 's/unix/linux/p' geekfile.txt Output:linux is great os. unix is opensource. unix is free os. linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Printing only the replaced lines : Use the -n option along with the /p print flag to display only the replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time.$sed -n 's/unix/linux/p' geekfile.txt Output:linux is great os. unix is opensource. unix is free os. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. If you use -n alone without /p, then the sed does not print anything.Replacing string on a range of lines : You can specify a range of line numbers to the sed command for replacing a string.$sed '1,3 s/unix/linux/' geekfile.txt Output:linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Here the sed command replaces the lines with range from 1 to 3. Another example is$sed '2,$ s/unix/linux/' geekfile.txt Output:unix is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful Here $ indicates the last line in the file. So the sed command replaces the text from second line to last line in the file.Deleting lines from a particular file : SED command can also be used for deleting lines from a particular file. SED command is used for performing deletion operation without even opening the fileExamples:1. To Delete a particular line say n in this exampleSyntax: $ sed 'nd' filename.txt Example: $ sed '5d' filename.txt 2. To Delete a last lineSyntax: $ sed '$d' filename.txt 3. To Delete line from range x to ySyntax: $ sed 'x,yd' filename.txt Example: $ sed '3,6d' filename.txt 4. To Delete from nth to last lineSyntax: $ sed 'nth,$d' filename.txt Example: $ sed '12,$d' filename.txt 5. To Delete pattern matching lineSyntax: $ sed '/pattern/d' filename.txt Example: $ sed '/abc/d' filename.txt Replacing or substituting string : Sed command is mostly used to replace the text in a file. The below simple sed command replaces the word “unix” with “linux” in the file.$sed 's/unix/linux/' geekfile.txt Output :linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Here the “s” specifies the substitution operation. The “/” are delimiters. The “unix” is the search pattern and the “linux” is the replacement string.By default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the second, third...occurrence in the line. $sed 's/unix/linux/' geekfile.txt Output : linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Here the “s” specifies the substitution operation. The “/” are delimiters. The “unix” is the search pattern and the “linux” is the replacement string. By default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the second, third...occurrence in the line. Replacing the nth occurrence of a pattern in a line : Use the /1, /2 etc flags to replace the first, second occurrence of a pattern in a line. The below command replaces the second occurrence of the word “unix” with “linux” in a line.$sed 's/unix/linux/2' geekfile.txt Output:unix is great os. linux is opensource. unix is free os. learn operating system. unix linux which one you choose. unix is easy to learn.linux is a multiuser os.Learn unix .unix is a powerful. $sed 's/unix/linux/2' geekfile.txt Output: unix is great os. linux is opensource. unix is free os. learn operating system. unix linux which one you choose. unix is easy to learn.linux is a multiuser os.Learn unix .unix is a powerful. Replacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line.$sed 's/unix/linux/g' geekfile.txt Output :linux is great os. linux is opensource. linux is free os. learn operating system. linux linux which one you choose. linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful. $sed 's/unix/linux/g' geekfile.txt Output : linux is great os. linux is opensource. linux is free os. learn operating system. linux linux which one you choose. linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful. Replacing from nth occurrence to all occurrences in a line : Use the combination of /1, /2 etc and /g to replace all the patterns from the nth occurrence of a pattern in a line. The following sed command replaces the third, fourth, fifth... “unix” word with “linux” word in a line.$sed 's/unix/linux/3g' geekfile.txt Output:unix is great os. unix is opensource. linux is free os. learn operating system. unix linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn linux .linux is a powerful. $sed 's/unix/linux/3g' geekfile.txt Output: unix is great os. unix is opensource. linux is free os. learn operating system. unix linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn linux .linux is a powerful. Parenthesize first character of each word : This sed example prints the first character of every word in parenthesis.$ echo "Welcome To The Geek Stuff" | sed 's/\(\b[A-Z]\)/\(\1\)/g' Output:(W)elcome (T)o (T)he (G)eek (S)tuff $ echo "Welcome To The Geek Stuff" | sed 's/\(\b[A-Z]\)/\(\1\)/g' Output: (W)elcome (T)o (T)he (G)eek (S)tuff Replacing string on a specific line number : You can restrict the sed command to replace the string on a specific line number. An example is$sed '3 s/unix/linux/' geekfile.txt Output:unix is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. The above sed command replaces the string only on the third line. $sed '3 s/unix/linux/' geekfile.txt Output: unix is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. The above sed command replaces the string only on the third line. Duplicating the replaced line with /p flag : The /p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once.$sed 's/unix/linux/p' geekfile.txt Output:linux is great os. unix is opensource. unix is free os. linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. $sed 's/unix/linux/p' geekfile.txt Output: linux is great os. unix is opensource. unix is free os. linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Printing only the replaced lines : Use the -n option along with the /p print flag to display only the replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time.$sed -n 's/unix/linux/p' geekfile.txt Output:linux is great os. unix is opensource. unix is free os. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. If you use -n alone without /p, then the sed does not print anything. $sed -n 's/unix/linux/p' geekfile.txt Output: linux is great os. unix is opensource. unix is free os. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. If you use -n alone without /p, then the sed does not print anything. Replacing string on a range of lines : You can specify a range of line numbers to the sed command for replacing a string.$sed '1,3 s/unix/linux/' geekfile.txt Output:linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Here the sed command replaces the lines with range from 1 to 3. Another example is$sed '2,$ s/unix/linux/' geekfile.txt Output:unix is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful Here $ indicates the last line in the file. So the sed command replaces the text from second line to last line in the file. $sed '1,3 s/unix/linux/' geekfile.txt Output: linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Here the sed command replaces the lines with range from 1 to 3. Another example is $sed '2,$ s/unix/linux/' geekfile.txt Output: unix is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful Here $ indicates the last line in the file. So the sed command replaces the text from second line to last line in the file. Deleting lines from a particular file : SED command can also be used for deleting lines from a particular file. SED command is used for performing deletion operation without even opening the fileExamples:1. To Delete a particular line say n in this exampleSyntax: $ sed 'nd' filename.txt Example: $ sed '5d' filename.txt 2. To Delete a last lineSyntax: $ sed '$d' filename.txt 3. To Delete line from range x to ySyntax: $ sed 'x,yd' filename.txt Example: $ sed '3,6d' filename.txt 4. To Delete from nth to last lineSyntax: $ sed 'nth,$d' filename.txt Example: $ sed '12,$d' filename.txt 5. To Delete pattern matching lineSyntax: $ sed '/pattern/d' filename.txt Example: $ sed '/abc/d' filename.txt Syntax: $ sed 'nd' filename.txt Example: $ sed '5d' filename.txt 2. To Delete a last line Syntax: $ sed '$d' filename.txt 3. To Delete line from range x to y Syntax: $ sed 'x,yd' filename.txt Example: $ sed '3,6d' filename.txt 4. To Delete from nth to last line Syntax: $ sed 'nth,$d' filename.txt Example: $ sed '12,$d' filename.txt 5. To Delete pattern matching line Syntax: $ sed '/pattern/d' filename.txt Example: $ sed '/abc/d' filename.txt SED command in Linux | Set 2 This article is contributed by Akshay Rajput and Mohak Agrawal. 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. ManasChhabra2 meetgor linux-command Linux-text-processing-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Dec, 2021" }, { "code": null, "e": 478, "s": 52, "text": "SED command in UNIX stands for stream editor and it can perform lots of functions on file like searching, find and replace, insertion or deletion. Though most common use of SED command in UNIX is for substitution or for find and replace. By using SED you can edit files even without opening them, which is much quicker way to find and replace something in file, than first opening that file in VI Editor and then changing it." }, { "code": null, "e": 578, "s": 478, "text": "SED is a powerful text stream editor. Can do insertion, deletion, search and replace(substitution)." }, { "code": null, "e": 676, "s": 578, "text": "SED command in unix supports regular expression which allows it perform complex pattern matching." }, { "code": null, "e": 684, "s": 676, "text": "Syntax:" }, { "code": null, "e": 724, "s": 684, "text": "sed OPTIONS... [SCRIPT] [INPUTFILE...] " }, { "code": null, "e": 774, "s": 724, "text": "Example:Consider the below text file as an input." }, { "code": null, "e": 795, "s": 774, "text": "$cat > geekfile.txt\n" }, { "code": null, "e": 985, "s": 795, "text": "unix is great os. unix is opensource. unix is free os.\nlearn operating system.\nunix linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n" }, { "code": null, "e": 1001, "s": 985, "text": "Sample Commands" }, { "code": null, "e": 6407, "s": 1001, "text": "Replacing or substituting string : Sed command is mostly used to replace the text in a file. The below simple sed command replaces the word “unix” with “linux” in the file.$sed 's/unix/linux/' geekfile.txt\nOutput :linux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\nHere the “s” specifies the substitution operation. The “/” are delimiters. The “unix” is the search pattern and the “linux” is the replacement string.By default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the second, third...occurrence in the line.Replacing the nth occurrence of a pattern in a line : Use the /1, /2 etc flags to replace the first, second occurrence of a pattern in a line. The below command replaces the second occurrence of the word “unix” with “linux” in a line.$sed 's/unix/linux/2' geekfile.txt\nOutput:unix is great os. linux is opensource. unix is free os.\nlearn operating system.\nunix linux which one you choose.\nunix is easy to learn.linux is a multiuser os.Learn unix .unix is a powerful.\nReplacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line.$sed 's/unix/linux/g' geekfile.txt\nOutput :linux is great os. linux is opensource. linux is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.\nReplacing from nth occurrence to all occurrences in a line : Use the combination of /1, /2 etc and /g to replace all the patterns from the nth occurrence of a pattern in a line. The following sed command replaces the third, fourth, fifth... “unix” word with “linux” word in a line.$sed 's/unix/linux/3g' geekfile.txt\nOutput:unix is great os. unix is opensource. linux is free os.\nlearn operating system.\nunix linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn linux .linux is a powerful.\nParenthesize first character of each word : This sed example prints the first character of every word in parenthesis.$ echo \"Welcome To The Geek Stuff\" | sed 's/\\(\\b[A-Z]\\)/\\(\\1\\)/g'\nOutput:(W)elcome (T)o (T)he (G)eek (S)tuff\nReplacing string on a specific line number : You can restrict the sed command to replace the string on a specific line number. An example is$sed '3 s/unix/linux/' geekfile.txt\nOutput:unix is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\nThe above sed command replaces the string only on the third line.Duplicating the replaced line with /p flag : The /p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once.$sed 's/unix/linux/p' geekfile.txt\nOutput:linux is great os. unix is opensource. unix is free os.\nlinux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\nPrinting only the replaced lines : Use the -n option along with the /p print flag to display only the replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time.$sed -n 's/unix/linux/p' geekfile.txt\nOutput:linux is great os. unix is opensource. unix is free os.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\nIf you use -n alone without /p, then the sed does not print anything.Replacing string on a range of lines : You can specify a range of line numbers to the sed command for replacing a string.$sed '1,3 s/unix/linux/' geekfile.txt\nOutput:linux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\nHere the sed command replaces the lines with range from 1 to 3. Another example is$sed '2,$ s/unix/linux/' geekfile.txt\nOutput:unix is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful\nHere $ indicates the last line in the file. So the sed command replaces the text from second line to last line in the file.Deleting lines from a particular file : SED command can also be used for deleting lines from a particular file. SED command is used for performing deletion operation without even opening the fileExamples:1. To Delete a particular line say n in this exampleSyntax:\n$ sed 'nd' filename.txt\nExample:\n$ sed '5d' filename.txt\n2. To Delete a last lineSyntax:\n$ sed '$d' filename.txt\n3. To Delete line from range x to ySyntax:\n$ sed 'x,yd' filename.txt\nExample:\n$ sed '3,6d' filename.txt\n4. To Delete from nth to last lineSyntax:\n$ sed 'nth,$d' filename.txt\nExample:\n$ sed '12,$d' filename.txt\n5. To Delete pattern matching lineSyntax:\n$ sed '/pattern/d' filename.txt\nExample:\n$ sed '/abc/d' filename.txt\n" }, { "code": null, "e": 7114, "s": 6407, "text": "Replacing or substituting string : Sed command is mostly used to replace the text in a file. The below simple sed command replaces the word “unix” with “linux” in the file.$sed 's/unix/linux/' geekfile.txt\nOutput :linux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\nHere the “s” specifies the substitution operation. The “/” are delimiters. The “unix” is the search pattern and the “linux” is the replacement string.By default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the second, third...occurrence in the line." }, { "code": null, "e": 7149, "s": 7114, "text": "$sed 's/unix/linux/' geekfile.txt\n" }, { "code": null, "e": 7158, "s": 7149, "text": "Output :" }, { "code": null, "e": 7351, "s": 7158, "text": "linux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n" }, { "code": null, "e": 7502, "s": 7351, "text": "Here the “s” specifies the substitution operation. The “/” are delimiters. The “unix” is the search pattern and the “linux” is the replacement string." }, { "code": null, "e": 7653, "s": 7502, "text": "By default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the second, third...occurrence in the line." }, { "code": null, "e": 8121, "s": 7653, "text": "Replacing the nth occurrence of a pattern in a line : Use the /1, /2 etc flags to replace the first, second occurrence of a pattern in a line. The below command replaces the second occurrence of the word “unix” with “linux” in a line.$sed 's/unix/linux/2' geekfile.txt\nOutput:unix is great os. linux is opensource. unix is free os.\nlearn operating system.\nunix linux which one you choose.\nunix is easy to learn.linux is a multiuser os.Learn unix .unix is a powerful.\n" }, { "code": null, "e": 8157, "s": 8121, "text": "$sed 's/unix/linux/2' geekfile.txt\n" }, { "code": null, "e": 8165, "s": 8157, "text": "Output:" }, { "code": null, "e": 8357, "s": 8165, "text": "unix is great os. linux is opensource. unix is free os.\nlearn operating system.\nunix linux which one you choose.\nunix is easy to learn.linux is a multiuser os.Learn unix .unix is a powerful.\n" }, { "code": null, "e": 8781, "s": 8357, "text": "Replacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line.$sed 's/unix/linux/g' geekfile.txt\nOutput :linux is great os. linux is opensource. linux is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.\n" }, { "code": null, "e": 8817, "s": 8781, "text": "$sed 's/unix/linux/g' geekfile.txt\n" }, { "code": null, "e": 8826, "s": 8817, "text": "Output :" }, { "code": null, "e": 9024, "s": 8826, "text": "linux is great os. linux is opensource. linux is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.\n" }, { "code": null, "e": 9541, "s": 9024, "text": "Replacing from nth occurrence to all occurrences in a line : Use the combination of /1, /2 etc and /g to replace all the patterns from the nth occurrence of a pattern in a line. The following sed command replaces the third, fourth, fifth... “unix” word with “linux” word in a line.$sed 's/unix/linux/3g' geekfile.txt\nOutput:unix is great os. unix is opensource. linux is free os.\nlearn operating system.\nunix linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn linux .linux is a powerful.\n" }, { "code": null, "e": 9578, "s": 9541, "text": "$sed 's/unix/linux/3g' geekfile.txt\n" }, { "code": null, "e": 9586, "s": 9578, "text": "Output:" }, { "code": null, "e": 9779, "s": 9586, "text": "unix is great os. unix is opensource. linux is free os.\nlearn operating system.\nunix linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn linux .linux is a powerful.\n" }, { "code": null, "e": 10006, "s": 9779, "text": "Parenthesize first character of each word : This sed example prints the first character of every word in parenthesis.$ echo \"Welcome To The Geek Stuff\" | sed 's/\\(\\b[A-Z]\\)/\\(\\1\\)/g'\nOutput:(W)elcome (T)o (T)he (G)eek (S)tuff\n" }, { "code": null, "e": 10073, "s": 10006, "text": "$ echo \"Welcome To The Geek Stuff\" | sed 's/\\(\\b[A-Z]\\)/\\(\\1\\)/g'\n" }, { "code": null, "e": 10081, "s": 10073, "text": "Output:" }, { "code": null, "e": 10118, "s": 10081, "text": "(W)elcome (T)o (T)he (G)eek (S)tuff\n" }, { "code": null, "e": 10557, "s": 10118, "text": "Replacing string on a specific line number : You can restrict the sed command to replace the string on a specific line number. An example is$sed '3 s/unix/linux/' geekfile.txt\nOutput:unix is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\nThe above sed command replaces the string only on the third line." }, { "code": null, "e": 10594, "s": 10557, "text": "$sed '3 s/unix/linux/' geekfile.txt\n" }, { "code": null, "e": 10602, "s": 10594, "text": "Output:" }, { "code": null, "e": 10793, "s": 10602, "text": "unix is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n" }, { "code": null, "e": 10859, "s": 10793, "text": "The above sed command replaces the string only on the third line." }, { "code": null, "e": 11476, "s": 10859, "text": "Duplicating the replaced line with /p flag : The /p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once.$sed 's/unix/linux/p' geekfile.txt\nOutput:linux is great os. unix is opensource. unix is free os.\nlinux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n" }, { "code": null, "e": 11512, "s": 11476, "text": "$sed 's/unix/linux/p' geekfile.txt\n" }, { "code": null, "e": 11520, "s": 11512, "text": "Output:" }, { "code": null, "e": 11881, "s": 11520, "text": "linux is great os. unix is opensource. unix is free os.\nlinux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n" }, { "code": null, "e": 12400, "s": 11881, "text": "Printing only the replaced lines : Use the -n option along with the /p print flag to display only the replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time.$sed -n 's/unix/linux/p' geekfile.txt\nOutput:linux is great os. unix is opensource. unix is free os.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\nIf you use -n alone without /p, then the sed does not print anything." }, { "code": null, "e": 12439, "s": 12400, "text": "$sed -n 's/unix/linux/p' geekfile.txt\n" }, { "code": null, "e": 12447, "s": 12439, "text": "Output:" }, { "code": null, "e": 12616, "s": 12447, "text": "linux is great os. unix is opensource. unix is free os.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n" }, { "code": null, "e": 12686, "s": 12616, "text": "If you use -n alone without /p, then the sed does not print anything." }, { "code": null, "e": 13484, "s": 12686, "text": "Replacing string on a range of lines : You can specify a range of line numbers to the sed command for replacing a string.$sed '1,3 s/unix/linux/' geekfile.txt\nOutput:linux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\nHere the sed command replaces the lines with range from 1 to 3. Another example is$sed '2,$ s/unix/linux/' geekfile.txt\nOutput:unix is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful\nHere $ indicates the last line in the file. So the sed command replaces the text from second line to last line in the file." }, { "code": null, "e": 13523, "s": 13484, "text": "$sed '1,3 s/unix/linux/' geekfile.txt\n" }, { "code": null, "e": 13531, "s": 13523, "text": "Output:" }, { "code": null, "e": 13723, "s": 13531, "text": "linux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n" }, { "code": null, "e": 13806, "s": 13723, "text": "Here the sed command replaces the lines with range from 1 to 3. Another example is" }, { "code": null, "e": 13845, "s": 13806, "text": "$sed '2,$ s/unix/linux/' geekfile.txt\n" }, { "code": null, "e": 13853, "s": 13845, "text": "Output:" }, { "code": null, "e": 14044, "s": 13853, "text": "unix is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful\n" }, { "code": null, "e": 14168, "s": 14044, "text": "Here $ indicates the last line in the file. So the sed command replaces the text from second line to last line in the file." }, { "code": null, "e": 14867, "s": 14168, "text": "Deleting lines from a particular file : SED command can also be used for deleting lines from a particular file. SED command is used for performing deletion operation without even opening the fileExamples:1. To Delete a particular line say n in this exampleSyntax:\n$ sed 'nd' filename.txt\nExample:\n$ sed '5d' filename.txt\n2. To Delete a last lineSyntax:\n$ sed '$d' filename.txt\n3. To Delete line from range x to ySyntax:\n$ sed 'x,yd' filename.txt\nExample:\n$ sed '3,6d' filename.txt\n4. To Delete from nth to last lineSyntax:\n$ sed 'nth,$d' filename.txt\nExample:\n$ sed '12,$d' filename.txt\n5. To Delete pattern matching lineSyntax:\n$ sed '/pattern/d' filename.txt\nExample:\n$ sed '/abc/d' filename.txt\n" }, { "code": null, "e": 14933, "s": 14867, "text": "Syntax:\n$ sed 'nd' filename.txt\nExample:\n$ sed '5d' filename.txt\n" }, { "code": null, "e": 14958, "s": 14933, "text": "2. To Delete a last line" }, { "code": null, "e": 14991, "s": 14958, "text": "Syntax:\n$ sed '$d' filename.txt\n" }, { "code": null, "e": 15027, "s": 14991, "text": "3. To Delete line from range x to y" }, { "code": null, "e": 15097, "s": 15027, "text": "Syntax:\n$ sed 'x,yd' filename.txt\nExample:\n$ sed '3,6d' filename.txt\n" }, { "code": null, "e": 15132, "s": 15097, "text": "4. To Delete from nth to last line" }, { "code": null, "e": 15205, "s": 15132, "text": "Syntax:\n$ sed 'nth,$d' filename.txt\nExample:\n$ sed '12,$d' filename.txt\n" }, { "code": null, "e": 15240, "s": 15205, "text": "5. To Delete pattern matching line" }, { "code": null, "e": 15318, "s": 15240, "text": "Syntax:\n$ sed '/pattern/d' filename.txt\nExample:\n$ sed '/abc/d' filename.txt\n" }, { "code": null, "e": 15347, "s": 15318, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 15662, "s": 15347, "text": "This article is contributed by Akshay Rajput and Mohak Agrawal. 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." }, { "code": null, "e": 15787, "s": 15662, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 15801, "s": 15787, "text": "ManasChhabra2" }, { "code": null, "e": 15809, "s": 15801, "text": "meetgor" }, { "code": null, "e": 15823, "s": 15809, "text": "linux-command" }, { "code": null, "e": 15854, "s": 15823, "text": "Linux-text-processing-commands" }, { "code": null, "e": 15865, "s": 15854, "text": "Linux-Unix" } ]
Python - Search Tree
A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties.The left sub-tree of a node has a key less than or equal to its parent node's key.The right sub-tree of a node has a key greater than to its parent node's key.Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right sub-tree left_subtree (keys) ≤ node (key) ≤ right_subtree (keys) Searching for a value in a tree involves comparing the incoming value with the value exiting nodes. Here also we traverse the nodes from left to right and then finally with the parent. If the searched for value does not match any of the exiting value, then we return not found message, or else the found message is returned. class Node: def __init__(self, data): self.left = None self.right = None self.data = data # Insert method to create nodes def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) else data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) else: self.data = data # findval method to compare the value with nodes def findval(self, lkpval): if lkpval < self.data: if self.left is None: return str(lkpval)+" Not Found" return self.left.findval(lkpval) else if lkpval > self.data: if self.right is None: return str(lkpval)+" Not Found" return self.right.findval(lkpval) else: print(str(self.data) + ' is found') # Print the tree def PrintTree(self): if self.left: self.left.PrintTree() print( self.data), if self.right: self.right.PrintTree() root = Node(12) root.insert(6) root.insert(14) root.insert(3) print(root.findval(7)) print(root.findval(14)) When the above code is executed, it produces the following result − 7 Not Found 14 is found
[ { "code": null, "e": 2814, "s": 2461, "text": "A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties.The left sub-tree of a node has a key less than or equal to its parent node's key.The right sub-tree of a node has a key greater than to its parent node's key.Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right sub-tree" }, { "code": null, "e": 2875, "s": 2814, "text": "left_subtree (keys) ≤ node (key) ≤ right_subtree (keys)\n" }, { "code": null, "e": 3200, "s": 2875, "text": "Searching for a value in a tree involves comparing the incoming value with the value exiting nodes. Here also we traverse the nodes from left to right and then finally with the parent. If the searched for value does not match any of the exiting value, then we return not found message, or else the found message is returned." }, { "code": null, "e": 4499, "s": 3200, "text": "class Node:\n def __init__(self, data):\n self.left = None\n self.right = None\n self.data = data\n# Insert method to create nodes\n def insert(self, data):\n if self.data:\n if data < self.data:\n if self.left is None:\n self.left = Node(data)\n else:\n self.left.insert(data)\n else data > self.data:\n if self.right is None:\n self.right = Node(data)\n else:\n self.right.insert(data)\n else:\n self.data = data\n# findval method to compare the value with nodes\n def findval(self, lkpval):\n if lkpval < self.data:\n if self.left is None:\n return str(lkpval)+\" Not Found\"\n return self.left.findval(lkpval)\n else if lkpval > self.data:\n if self.right is None:\n return str(lkpval)+\" Not Found\"\n return self.right.findval(lkpval)\n else:\n print(str(self.data) + ' is found')\n# Print the tree\n def PrintTree(self):\n if self.left:\n self.left.PrintTree()\n print( self.data),\n if self.right:\n self.right.PrintTree()\nroot = Node(12)\nroot.insert(6)\nroot.insert(14)\nroot.insert(3)\nprint(root.findval(7))\nprint(root.findval(14))" }, { "code": null, "e": 4567, "s": 4499, "text": "When the above code is executed, it produces the following result −" } ]
Detect Cycle in a Directed Graph using BFS
28 Dec, 2021 Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains two cycles 0->1->2->3->0 and 2->4->2, so your function must return true. We have discussed a DFS based solution to detect cycle in a directed graph. In this post, BFS based solution is discussed.The idea is to simply use Kahn’s algorithm for Topological Sorting Steps involved in detecting cycle in a directed graph using BFS.Step-1: Compute in-degree (number of incoming edges) for each of the vertex present in the graph and initialize the count of visited nodes as 0.Step-2: Pick all the vertices with in-degree as 0 and add them into a queue (Enqueue operation)Step-3: Remove a vertex from the queue (Dequeue operation) and then. Increment count of visited nodes by 1.Decrease in-degree by 1 for all its neighboring nodes.If in-degree of a neighboring nodes is reduced to zero, then add it to the queue. Increment count of visited nodes by 1. Decrease in-degree by 1 for all its neighboring nodes. If in-degree of a neighboring nodes is reduced to zero, then add it to the queue. Step 4: Repeat Step 3 until the queue is empty.Step 5: If count of visited nodes is not equal to the number of nodes in the graph has cycle, otherwise not. How to find in-degree of each node? There are 2 ways to calculate in-degree of every vertex: Take an in-degree array which will keep track of 1) Traverse the array of edges and simply increase the counter of the destination node by 1. for each node in Nodes indegree[node] = 0; for each edge(src,dest) in Edges indegree[dest]++ Time Complexity: O(V+E) 2) Traverse the list for every node and then increment the in-degree of all the nodes connected to it by 1. for each node in Nodes If (list[node].size()!=0) then for each dest in list indegree[dest]++; Time Complexity: The outer for loop will be executed V number of times and the inner for loop will be executed E number of times, Thus overall time complexity is O(V+E). The overall time complexity of the algorithm is O(V+E) C++ Java Python3 C# Javascript // A C++ program to check if there is a cycle in// directed graph using BFS.#include <bits/stdc++.h>using namespace std; // Class to represent a graphclass Graph { int V; // No. of vertices' // Pointer to an array containing adjacency list list<int>* adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v); // Returns true if there is a cycle in the graph // else false. bool isCycle();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int u, int v){ adj[u].push_back(v);} // This function returns true if there is a cycle// in directed graph, else returns false.bool Graph::isCycle(){ // Create a vector to store indegrees of all // vertices. Initialize all indegrees as 0. vector<int> in_degree(V, 0); // Traverse adjacency lists to fill indegrees of // vertices. This step takes O(V+E) time for (int u = 0; u < V; u++) { for (auto v : adj[u]) in_degree[v]++; } // Create an queue and enqueue all vertices with // indegree 0 queue<int> q; for (int i = 0; i < V; i++) if (in_degree[i] == 0) q.push(i); // Initialize count of visited vertices // 1 For src Node int cnt = 1; // Create a vector to store result (A topological // ordering of the vertices) vector<int> top_order; // One by one dequeue vertices from queue and enqueue // adjacents if indegree of adjacent becomes 0 while (!q.empty()) { // Extract front of queue (or perform dequeue) // and add it to topological order int u = q.front(); q.pop(); top_order.push_back(u); // Iterate through all its neighbouring nodes // of dequeued node u and decrease their in-degree // by 1 list<int>::iterator itr; for (itr = adj[u].begin(); itr != adj[u].end(); itr++) // If in-degree becomes zero, add it to queue if (--in_degree[*itr] == 0) { q.push(*itr); //while we are pushing elements to the queue we will incrementing the cnt cnt++; } } // Check if there was a cycle if (cnt != V) return true; else return false;} // Driver program to test above functionsint main(){ // Create a graph given in the above diagram Graph g(6); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(3, 4); g.addEdge(4, 5); if (g.isCycle()) cout << "Yes"; else cout << "No"; return 0;} // Java program to check if there is a cycle in// directed graph using BFS.import java.io.*;import java.util.*; class GFG{ // Class to represent a graph static class Graph { int V; // No. of vertices' // Pointer to an array containing adjacency list Vector<Integer>[] adj; @SuppressWarnings("unchecked") Graph(int V) { // Constructor this.V = V; this.adj = new Vector[V]; for (int i = 0; i < V; i++) adj[i] = new Vector<>(); } // function to add an edge to graph void addEdge(int u, int v) { adj[u].add(v); } // Returns true if there is a cycle in the graph // else false. // This function returns true if there is a cycle // in directed graph, else returns false. boolean isCycle() { // Create a vector to store indegrees of all // vertices. Initialize all indegrees as 0. int[] in_degree = new int[this.V]; Arrays.fill(in_degree, 0); // Traverse adjacency lists to fill indegrees of // vertices. This step takes O(V+E) time for (int u = 0; u < V; u++) { for (int v : adj[u]) in_degree[v]++; } // Create an queue and enqueue all vertices with // indegree 0 Queue<Integer> q = new LinkedList<Integer>(); for (int i = 0; i < V; i++) if (in_degree[i] == 0) q.add(i); // Initialize count of visited vertices int cnt = 0; // Create a vector to store result (A topological // ordering of the vertices) Vector<Integer> top_order = new Vector<>(); // One by one dequeue vertices from queue and enqueue // adjacents if indegree of adjacent becomes 0 while (!q.isEmpty()) { // Extract front of queue (or perform dequeue) // and add it to topological order int u = q.poll(); top_order.add(u); // Iterate through all its neighbouring nodes // of dequeued node u and decrease their in-degree // by 1 for (int itr : adj[u]) if (--in_degree[itr] == 0) q.add(itr); cnt++; } // Check if there was a cycle if (cnt != this.V) return true; else return false; } } // Driver Code public static void main(String[] args) { // Create a graph given in the above diagram Graph g = new Graph(6); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(3, 4); g.addEdge(4, 5); if (g.isCycle()) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by// sanjeev2552 # A Python3 program to check if there is a cycle in # directed graph using BFS.import mathimport sysfrom collections import defaultdict # Class to represent a graphclass Graph: def __init__(self,vertices): self.graph=defaultdict(list) self.V=vertices # No. of vertices' # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # This function returns true if there is a cycle# in directed graph, else returns false.def isCycleExist(n,graph): # Create a vector to store indegrees of all # vertices. Initialize all indegrees as 0. in_degree=[0]*n # Traverse adjacency lists to fill indegrees of # vertices. This step takes O(V+E) time for i in range(n): for j in graph[i]: in_degree[j]+=1 # Create an queue and enqueue all vertices with # indegree 0 queue=[] for i in range(len(in_degree)): if in_degree[i]==0: queue.append(i) # Initialize count of visited vertices cnt=0 # One by one dequeue vertices from queue and enqueue # adjacents if indegree of adjacent becomes 0 while(queue): # Extract front of queue (or perform dequeue) # and add it to topological order nu=queue.pop(0) # Iterate through all its neighbouring nodes # of dequeued node u and decrease their in-degree # by 1 for v in graph[nu]: in_degree[v]-=1 # If in-degree becomes zero, add it to queue if in_degree[v]==0: queue.append(v) cnt+=1 # Check if there was a cycle if cnt==n: return False else: return True # Driver program to test above functionsif __name__=='__main__': # Create a graph given in the above diagram g=Graph(6) g.addEdge(0,1) g.addEdge(1,2) g.addEdge(2,0) g.addEdge(3,4) g.addEdge(4,5) if isCycleExist(g.V,g.graph): print("Yes") else: print("No") # This Code is Contributed by Vikash Kumar 37 // C# program to check if there is a cycle in// directed graph using BFS.using System;using System.Collections.Generic; class GFG{ // Class to represent a graphpublic class Graph{ // No. of vertices' public int V; // Pointer to an array containing // adjacency list public List<int>[] adj; public Graph(int V) { // Constructor this.V = V; this.adj = new List<int>[V]; for (int i = 0; i < V; i++) adj[i] = new List<int>(); } // Function to add an edge to graph public void addEdge(int u, int v) { adj[u].Add(v); } // Returns true if there is a cycle in the // graph else false. // This function returns true if there is // a cycle in directed graph, else returns // false. public bool isCycle() { // Create a vector to store indegrees of all // vertices. Initialize all indegrees as 0. int[] in_degree = new int[this.V]; // Traverse adjacency lists to fill indegrees // of vertices. This step takes O(V+E) time for(int u = 0; u < V; u++) { foreach(int v in adj[u]) in_degree[v]++; } // Create an queue and enqueue all // vertices with indegree 0 Queue<int> q = new Queue<int>(); for(int i = 0; i < V; i++) if (in_degree[i] == 0) q.Enqueue(i); // Initialize count of visited vertices int cnt = 0; // Create a vector to store result // (A topological ordering of the // vertices) List<int> top_order = new List<int>(); // One by one dequeue vertices from // queue and enqueue adjacents if // indegree of adjacent becomes 0 while (q.Count != 0) { // Extract front of queue (or perform // dequeue) and add it to topological // order int u = q.Peek(); q.Dequeue(); top_order.Add(u); // Iterate through all its neighbouring // nodes of dequeued node u and decrease // their in-degree by 1 foreach(int itr in adj[u]) if (--in_degree[itr] == 0) q.Enqueue(itr); cnt++; } // Check if there was a cycle if (cnt != this.V) return true; else return false; }} // Driver Codepublic static void Main(String[] args){ // Create a graph given in the above diagram Graph g = new Graph(6); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(3, 4); g.addEdge(4, 5); if (g.isCycle()) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by Princi Singh <script> // JavaScript program to check if there is a cycle in// directed graph using BFS. // Class to represent a graph// No. of vertices'var V = 0; // Pointer to an array containing// adjacency listvar adj ; function initialize(v){ // Constructor V = v; adj = Array.from(Array(V), ()=>Array(V));} // Function to add an edge to graphfunction addEdge(u, v){ adj[u].push(v);} // Returns true if there is a cycle in the// graph else false. // This function returns true if there is// a cycle in directed graph, else returns// false.function isCycle(){ // Create a vector to store indegrees of all // vertices. Initialize all indegrees as 0. var in_degree = Array(V).fill(0); // Traverse adjacency lists to fill indegrees // of vertices. This step takes O(V+E) time for(var u = 0; u < V; u++) { for(var v of adj[u]) in_degree[v]++; } // Create an queue and enqueue all // vertices with indegree 0 var q = []; for(var i = 0; i < V; i++) if (in_degree[i] == 0) q.push(i); // Initialize count of visited vertices var cnt = 0; // Create a vector to store result // (A topological ordering of the // vertices) var top_order = []; // One by one dequeue vertices from // queue and enqueue adjacents if // indegree of adjacent becomes 0 while (q.length != 0) { // Extract front of queue (or perform // dequeue) and add it to topological // order var u = q[0]; q.shift(); top_order.push(u); // Iterate through all its neighbouring // nodes of dequeued node u and decrease // their in-degree by 1 for(var itr of adj[u]) if (--in_degree[itr] == 0) q.push(itr); cnt++; } // Check if there was a cycle if (cnt != V) return true; else return false;} // Create a graph given in the above diagraminitialize(6)addEdge(0, 1);addEdge(1, 2);addEdge(2, 0);addEdge(3, 4);addEdge(4, 5);if (isCycle()) document.write("Yes");else document.write("No"); </script> Yes Time Complexity: O(V+E) MilanToriya Vikash Kumar 37 sanjeev2552 princi singh itsok kashishsoda bansalashish2101 Amazon BFS graph-cycle Topological Sorting Graph Amazon Graph BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path between two vertices in a directed graph Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Find if there is a path between two vertices in an undirected graph Minimum steps to reach target by a Knight | Set 1 Top 50 Graph Coding Problems for Interviews Bridges in a graph Water Jug problem using BFS Longest Path in a Directed Acyclic Graph Graph Coloring | Set 1 (Introduction and Applications)
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Dec, 2021" }, { "code": null, "e": 342, "s": 54, "text": "Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains two cycles 0->1->2->3->0 and 2->4->2, so your function must return true." }, { "code": null, "e": 531, "s": 342, "text": "We have discussed a DFS based solution to detect cycle in a directed graph. In this post, BFS based solution is discussed.The idea is to simply use Kahn’s algorithm for Topological Sorting" }, { "code": null, "e": 904, "s": 531, "text": "Steps involved in detecting cycle in a directed graph using BFS.Step-1: Compute in-degree (number of incoming edges) for each of the vertex present in the graph and initialize the count of visited nodes as 0.Step-2: Pick all the vertices with in-degree as 0 and add them into a queue (Enqueue operation)Step-3: Remove a vertex from the queue (Dequeue operation) and then. " }, { "code": null, "e": 1078, "s": 904, "text": "Increment count of visited nodes by 1.Decrease in-degree by 1 for all its neighboring nodes.If in-degree of a neighboring nodes is reduced to zero, then add it to the queue." }, { "code": null, "e": 1117, "s": 1078, "text": "Increment count of visited nodes by 1." }, { "code": null, "e": 1172, "s": 1117, "text": "Decrease in-degree by 1 for all its neighboring nodes." }, { "code": null, "e": 1254, "s": 1172, "text": "If in-degree of a neighboring nodes is reduced to zero, then add it to the queue." }, { "code": null, "e": 1410, "s": 1254, "text": "Step 4: Repeat Step 3 until the queue is empty.Step 5: If count of visited nodes is not equal to the number of nodes in the graph has cycle, otherwise not." }, { "code": null, "e": 1646, "s": 1410, "text": "How to find in-degree of each node? There are 2 ways to calculate in-degree of every vertex: Take an in-degree array which will keep track of 1) Traverse the array of edges and simply increase the counter of the destination node by 1. " }, { "code": null, "e": 1747, "s": 1646, "text": "for each node in Nodes\n indegree[node] = 0;\nfor each edge(src,dest) in Edges\n indegree[dest]++" }, { "code": null, "e": 1771, "s": 1747, "text": "Time Complexity: O(V+E)" }, { "code": null, "e": 1880, "s": 1771, "text": "2) Traverse the list for every node and then increment the in-degree of all the nodes connected to it by 1. " }, { "code": null, "e": 2006, "s": 1880, "text": " for each node in Nodes\n If (list[node].size()!=0) then\n for each dest in list\n indegree[dest]++;" }, { "code": null, "e": 2176, "s": 2006, "text": "Time Complexity: The outer for loop will be executed V number of times and the inner for loop will be executed E number of times, Thus overall time complexity is O(V+E)." }, { "code": null, "e": 2232, "s": 2176, "text": "The overall time complexity of the algorithm is O(V+E) " }, { "code": null, "e": 2236, "s": 2232, "text": "C++" }, { "code": null, "e": 2241, "s": 2236, "text": "Java" }, { "code": null, "e": 2249, "s": 2241, "text": "Python3" }, { "code": null, "e": 2252, "s": 2249, "text": "C#" }, { "code": null, "e": 2263, "s": 2252, "text": "Javascript" }, { "code": "// A C++ program to check if there is a cycle in// directed graph using BFS.#include <bits/stdc++.h>using namespace std; // Class to represent a graphclass Graph { int V; // No. of vertices' // Pointer to an array containing adjacency list list<int>* adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v); // Returns true if there is a cycle in the graph // else false. bool isCycle();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int u, int v){ adj[u].push_back(v);} // This function returns true if there is a cycle// in directed graph, else returns false.bool Graph::isCycle(){ // Create a vector to store indegrees of all // vertices. Initialize all indegrees as 0. vector<int> in_degree(V, 0); // Traverse adjacency lists to fill indegrees of // vertices. This step takes O(V+E) time for (int u = 0; u < V; u++) { for (auto v : adj[u]) in_degree[v]++; } // Create an queue and enqueue all vertices with // indegree 0 queue<int> q; for (int i = 0; i < V; i++) if (in_degree[i] == 0) q.push(i); // Initialize count of visited vertices // 1 For src Node int cnt = 1; // Create a vector to store result (A topological // ordering of the vertices) vector<int> top_order; // One by one dequeue vertices from queue and enqueue // adjacents if indegree of adjacent becomes 0 while (!q.empty()) { // Extract front of queue (or perform dequeue) // and add it to topological order int u = q.front(); q.pop(); top_order.push_back(u); // Iterate through all its neighbouring nodes // of dequeued node u and decrease their in-degree // by 1 list<int>::iterator itr; for (itr = adj[u].begin(); itr != adj[u].end(); itr++) // If in-degree becomes zero, add it to queue if (--in_degree[*itr] == 0) { q.push(*itr); //while we are pushing elements to the queue we will incrementing the cnt cnt++; } } // Check if there was a cycle if (cnt != V) return true; else return false;} // Driver program to test above functionsint main(){ // Create a graph given in the above diagram Graph g(6); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(3, 4); g.addEdge(4, 5); if (g.isCycle()) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 4849, "s": 2263, "text": null }, { "code": "// Java program to check if there is a cycle in// directed graph using BFS.import java.io.*;import java.util.*; class GFG{ // Class to represent a graph static class Graph { int V; // No. of vertices' // Pointer to an array containing adjacency list Vector<Integer>[] adj; @SuppressWarnings(\"unchecked\") Graph(int V) { // Constructor this.V = V; this.adj = new Vector[V]; for (int i = 0; i < V; i++) adj[i] = new Vector<>(); } // function to add an edge to graph void addEdge(int u, int v) { adj[u].add(v); } // Returns true if there is a cycle in the graph // else false. // This function returns true if there is a cycle // in directed graph, else returns false. boolean isCycle() { // Create a vector to store indegrees of all // vertices. Initialize all indegrees as 0. int[] in_degree = new int[this.V]; Arrays.fill(in_degree, 0); // Traverse adjacency lists to fill indegrees of // vertices. This step takes O(V+E) time for (int u = 0; u < V; u++) { for (int v : adj[u]) in_degree[v]++; } // Create an queue and enqueue all vertices with // indegree 0 Queue<Integer> q = new LinkedList<Integer>(); for (int i = 0; i < V; i++) if (in_degree[i] == 0) q.add(i); // Initialize count of visited vertices int cnt = 0; // Create a vector to store result (A topological // ordering of the vertices) Vector<Integer> top_order = new Vector<>(); // One by one dequeue vertices from queue and enqueue // adjacents if indegree of adjacent becomes 0 while (!q.isEmpty()) { // Extract front of queue (or perform dequeue) // and add it to topological order int u = q.poll(); top_order.add(u); // Iterate through all its neighbouring nodes // of dequeued node u and decrease their in-degree // by 1 for (int itr : adj[u]) if (--in_degree[itr] == 0) q.add(itr); cnt++; } // Check if there was a cycle if (cnt != this.V) return true; else return false; } } // Driver Code public static void main(String[] args) { // Create a graph given in the above diagram Graph g = new Graph(6); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(3, 4); g.addEdge(4, 5); if (g.isCycle()) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by// sanjeev2552", "e": 7910, "s": 4849, "text": null }, { "code": "# A Python3 program to check if there is a cycle in # directed graph using BFS.import mathimport sysfrom collections import defaultdict # Class to represent a graphclass Graph: def __init__(self,vertices): self.graph=defaultdict(list) self.V=vertices # No. of vertices' # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # This function returns true if there is a cycle# in directed graph, else returns false.def isCycleExist(n,graph): # Create a vector to store indegrees of all # vertices. Initialize all indegrees as 0. in_degree=[0]*n # Traverse adjacency lists to fill indegrees of # vertices. This step takes O(V+E) time for i in range(n): for j in graph[i]: in_degree[j]+=1 # Create an queue and enqueue all vertices with # indegree 0 queue=[] for i in range(len(in_degree)): if in_degree[i]==0: queue.append(i) # Initialize count of visited vertices cnt=0 # One by one dequeue vertices from queue and enqueue # adjacents if indegree of adjacent becomes 0 while(queue): # Extract front of queue (or perform dequeue) # and add it to topological order nu=queue.pop(0) # Iterate through all its neighbouring nodes # of dequeued node u and decrease their in-degree # by 1 for v in graph[nu]: in_degree[v]-=1 # If in-degree becomes zero, add it to queue if in_degree[v]==0: queue.append(v) cnt+=1 # Check if there was a cycle if cnt==n: return False else: return True # Driver program to test above functionsif __name__=='__main__': # Create a graph given in the above diagram g=Graph(6) g.addEdge(0,1) g.addEdge(1,2) g.addEdge(2,0) g.addEdge(3,4) g.addEdge(4,5) if isCycleExist(g.V,g.graph): print(\"Yes\") else: print(\"No\") # This Code is Contributed by Vikash Kumar 37", "e": 9929, "s": 7910, "text": null }, { "code": "// C# program to check if there is a cycle in// directed graph using BFS.using System;using System.Collections.Generic; class GFG{ // Class to represent a graphpublic class Graph{ // No. of vertices' public int V; // Pointer to an array containing // adjacency list public List<int>[] adj; public Graph(int V) { // Constructor this.V = V; this.adj = new List<int>[V]; for (int i = 0; i < V; i++) adj[i] = new List<int>(); } // Function to add an edge to graph public void addEdge(int u, int v) { adj[u].Add(v); } // Returns true if there is a cycle in the // graph else false. // This function returns true if there is // a cycle in directed graph, else returns // false. public bool isCycle() { // Create a vector to store indegrees of all // vertices. Initialize all indegrees as 0. int[] in_degree = new int[this.V]; // Traverse adjacency lists to fill indegrees // of vertices. This step takes O(V+E) time for(int u = 0; u < V; u++) { foreach(int v in adj[u]) in_degree[v]++; } // Create an queue and enqueue all // vertices with indegree 0 Queue<int> q = new Queue<int>(); for(int i = 0; i < V; i++) if (in_degree[i] == 0) q.Enqueue(i); // Initialize count of visited vertices int cnt = 0; // Create a vector to store result // (A topological ordering of the // vertices) List<int> top_order = new List<int>(); // One by one dequeue vertices from // queue and enqueue adjacents if // indegree of adjacent becomes 0 while (q.Count != 0) { // Extract front of queue (or perform // dequeue) and add it to topological // order int u = q.Peek(); q.Dequeue(); top_order.Add(u); // Iterate through all its neighbouring // nodes of dequeued node u and decrease // their in-degree by 1 foreach(int itr in adj[u]) if (--in_degree[itr] == 0) q.Enqueue(itr); cnt++; } // Check if there was a cycle if (cnt != this.V) return true; else return false; }} // Driver Codepublic static void Main(String[] args){ // Create a graph given in the above diagram Graph g = new Graph(6); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(3, 4); g.addEdge(4, 5); if (g.isCycle()) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by Princi Singh", "e": 12817, "s": 9929, "text": null }, { "code": "<script> // JavaScript program to check if there is a cycle in// directed graph using BFS. // Class to represent a graph// No. of vertices'var V = 0; // Pointer to an array containing// adjacency listvar adj ; function initialize(v){ // Constructor V = v; adj = Array.from(Array(V), ()=>Array(V));} // Function to add an edge to graphfunction addEdge(u, v){ adj[u].push(v);} // Returns true if there is a cycle in the// graph else false. // This function returns true if there is// a cycle in directed graph, else returns// false.function isCycle(){ // Create a vector to store indegrees of all // vertices. Initialize all indegrees as 0. var in_degree = Array(V).fill(0); // Traverse adjacency lists to fill indegrees // of vertices. This step takes O(V+E) time for(var u = 0; u < V; u++) { for(var v of adj[u]) in_degree[v]++; } // Create an queue and enqueue all // vertices with indegree 0 var q = []; for(var i = 0; i < V; i++) if (in_degree[i] == 0) q.push(i); // Initialize count of visited vertices var cnt = 0; // Create a vector to store result // (A topological ordering of the // vertices) var top_order = []; // One by one dequeue vertices from // queue and enqueue adjacents if // indegree of adjacent becomes 0 while (q.length != 0) { // Extract front of queue (or perform // dequeue) and add it to topological // order var u = q[0]; q.shift(); top_order.push(u); // Iterate through all its neighbouring // nodes of dequeued node u and decrease // their in-degree by 1 for(var itr of adj[u]) if (--in_degree[itr] == 0) q.push(itr); cnt++; } // Check if there was a cycle if (cnt != V) return true; else return false;} // Create a graph given in the above diagraminitialize(6)addEdge(0, 1);addEdge(1, 2);addEdge(2, 0);addEdge(3, 4);addEdge(4, 5);if (isCycle()) document.write(\"Yes\");else document.write(\"No\"); </script>", "e": 14975, "s": 12817, "text": null }, { "code": null, "e": 14979, "s": 14975, "text": "Yes" }, { "code": null, "e": 15006, "s": 14981, "text": "Time Complexity: O(V+E) " }, { "code": null, "e": 15018, "s": 15006, "text": "MilanToriya" }, { "code": null, "e": 15034, "s": 15018, "text": "Vikash Kumar 37" }, { "code": null, "e": 15046, "s": 15034, "text": "sanjeev2552" }, { "code": null, "e": 15059, "s": 15046, "text": "princi singh" }, { "code": null, "e": 15065, "s": 15059, "text": "itsok" }, { "code": null, "e": 15077, "s": 15065, "text": "kashishsoda" }, { "code": null, "e": 15094, "s": 15077, "text": "bansalashish2101" }, { "code": null, "e": 15101, "s": 15094, "text": "Amazon" }, { "code": null, "e": 15105, "s": 15101, "text": "BFS" }, { "code": null, "e": 15117, "s": 15105, "text": "graph-cycle" }, { "code": null, "e": 15137, "s": 15117, "text": "Topological Sorting" }, { "code": null, "e": 15143, "s": 15137, "text": "Graph" }, { "code": null, "e": 15150, "s": 15143, "text": "Amazon" }, { "code": null, "e": 15156, "s": 15150, "text": "Graph" }, { "code": null, "e": 15160, "s": 15156, "text": "BFS" }, { "code": null, "e": 15258, "s": 15160, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15323, "s": 15258, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 15355, "s": 15323, "text": "Introduction to Data Structures" }, { "code": null, "e": 15419, "s": 15355, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 15487, "s": 15419, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 15537, "s": 15487, "text": "Minimum steps to reach target by a Knight | Set 1" }, { "code": null, "e": 15581, "s": 15537, "text": "Top 50 Graph Coding Problems for Interviews" }, { "code": null, "e": 15600, "s": 15581, "text": "Bridges in a graph" }, { "code": null, "e": 15628, "s": 15600, "text": "Water Jug problem using BFS" }, { "code": null, "e": 15669, "s": 15628, "text": "Longest Path in a Directed Acyclic Graph" } ]
Iterable forEach() method in Java with Examples
22 May, 2019 It has been Quite a while since Java 8 released. With the release, they have improved some of the existing APIs and added few new features. One of them is forEach Method in java.lang.Iterable Interface. Whenever we need to traverse over a collection we have to create an Iterator to iterate over the collection and then we can have our business logic inside a loop for each of the elements inside the collection. We may greeted with ConcurrentModificationException if it is not implemented properly. The implementation of forEach method in Iterable interface is: default void forEach(Consumer action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } } Parameter: This method takes a parameter action of type java.util.function.Consumer which represents the action to be performed for each element. Returns: The return type of forEach is void. Hence it do not returns anything. Exception: Throws NullPointerException if the input action is null. Program 1: Program to iterate a list of String using the Iterator. // Java program to demonstrate// forEach() method of Iterable interface import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.function.Consumer; public class ForEachExample { public static void main(String[] args) { List<String> data = new ArrayList<>(); data.add("New Delhi"); data.add("New York"); data.add("Mumbai"); data.add("London"); Iterator<String> itr = data.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); // data.remove(itr.next()); // this line can introduce you to // java.util.ConcurrentModificationException. } }} New Delhi New York Mumbai London Program 2: Program to demonstrate forEach() method on a List which contains list of cities. // Java program to demonstrate// forEach() method of Iterable interface import java.util.ArrayList;import java.util.List;import java.util.function.Consumer; public class ForEachExample { public static void main(String[] args) { List<String> data = new ArrayList<>(); data.add("New Delhi"); data.add("New York"); data.add("Mumbai"); data.add("London"); data.forEach(new Consumer<String>() { @Override public void accept(String t) { System.out.println(t); } }); }} New Delhi New York Mumbai London In the above program, we have created a List of String with 4 elements and then we have iterated over the list using the forEach method. As described earlier forEach method take Consumer object as input, we have created an anonymous inner class implementation of Consumer interface and overrides the accept method. In this example, we have kept the business logic inside the anonymous inner class and we can not reuse it. Program 3: In this program we will demonstrate the implementation of Consumer interface separately so that we can reuse it. Let’s create a class CityConsumer which implements Consumer interface and overrides its accept method. // Java program to demonstrate// forEach() method of Iterable interface import java.util.*;import java.util.function.Consumer; class CityConsumer implements Consumer<String> { @Override public void accept(String t) { System.out.println(t); }} // Now we can use the CityConsumer// with forEach method by just creating// an object of CityConsumer class as below. public class ForEachExample { public static void main(String[] args) { List<String> data = new ArrayList<>(); data.add("New Delhi"); data.add("New York"); data.add("Mumbai"); data.add("London"); // create an object of CityConsumer // and pass it to forEach method CityConsumer cityConsumer = new CityConsumer(); data.forEach(cityConsumer); }} New Delhi New York Mumbai London Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Functional Interfaces in Java Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n22 May, 2019" }, { "code": null, "e": 256, "s": 53, "text": "It has been Quite a while since Java 8 released. With the release, they have improved some of the existing APIs and added few new features. One of them is forEach Method in java.lang.Iterable Interface." }, { "code": null, "e": 553, "s": 256, "text": "Whenever we need to traverse over a collection we have to create an Iterator to iterate over the collection and then we can have our business logic inside a loop for each of the elements inside the collection. We may greeted with ConcurrentModificationException if it is not implemented properly." }, { "code": null, "e": 616, "s": 553, "text": "The implementation of forEach method in Iterable interface is:" }, { "code": null, "e": 769, "s": 616, "text": "default void forEach(Consumer action) {\n Objects.requireNonNull(action);\n for (T t : this) {\n action.accept(t);\n }\n }" }, { "code": null, "e": 915, "s": 769, "text": "Parameter: This method takes a parameter action of type java.util.function.Consumer which represents the action to be performed for each element." }, { "code": null, "e": 994, "s": 915, "text": "Returns: The return type of forEach is void. Hence it do not returns anything." }, { "code": null, "e": 1062, "s": 994, "text": "Exception: Throws NullPointerException if the input action is null." }, { "code": null, "e": 1129, "s": 1062, "text": "Program 1: Program to iterate a list of String using the Iterator." }, { "code": "// Java program to demonstrate// forEach() method of Iterable interface import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.function.Consumer; public class ForEachExample { public static void main(String[] args) { List<String> data = new ArrayList<>(); data.add(\"New Delhi\"); data.add(\"New York\"); data.add(\"Mumbai\"); data.add(\"London\"); Iterator<String> itr = data.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); // data.remove(itr.next()); // this line can introduce you to // java.util.ConcurrentModificationException. } }}", "e": 1833, "s": 1129, "text": null }, { "code": null, "e": 1867, "s": 1833, "text": "New Delhi\nNew York\nMumbai\nLondon\n" }, { "code": null, "e": 1959, "s": 1867, "text": "Program 2: Program to demonstrate forEach() method on a List which contains list of cities." }, { "code": "// Java program to demonstrate// forEach() method of Iterable interface import java.util.ArrayList;import java.util.List;import java.util.function.Consumer; public class ForEachExample { public static void main(String[] args) { List<String> data = new ArrayList<>(); data.add(\"New Delhi\"); data.add(\"New York\"); data.add(\"Mumbai\"); data.add(\"London\"); data.forEach(new Consumer<String>() { @Override public void accept(String t) { System.out.println(t); } }); }}", "e": 2551, "s": 1959, "text": null }, { "code": null, "e": 2585, "s": 2551, "text": "New Delhi\nNew York\nMumbai\nLondon\n" }, { "code": null, "e": 3007, "s": 2585, "text": "In the above program, we have created a List of String with 4 elements and then we have iterated over the list using the forEach method. As described earlier forEach method take Consumer object as input, we have created an anonymous inner class implementation of Consumer interface and overrides the accept method. In this example, we have kept the business logic inside the anonymous inner class and we can not reuse it." }, { "code": null, "e": 3234, "s": 3007, "text": "Program 3: In this program we will demonstrate the implementation of Consumer interface separately so that we can reuse it. Let’s create a class CityConsumer which implements Consumer interface and overrides its accept method." }, { "code": "// Java program to demonstrate// forEach() method of Iterable interface import java.util.*;import java.util.function.Consumer; class CityConsumer implements Consumer<String> { @Override public void accept(String t) { System.out.println(t); }} // Now we can use the CityConsumer// with forEach method by just creating// an object of CityConsumer class as below. public class ForEachExample { public static void main(String[] args) { List<String> data = new ArrayList<>(); data.add(\"New Delhi\"); data.add(\"New York\"); data.add(\"Mumbai\"); data.add(\"London\"); // create an object of CityConsumer // and pass it to forEach method CityConsumer cityConsumer = new CityConsumer(); data.forEach(cityConsumer); }}", "e": 4039, "s": 3234, "text": null }, { "code": null, "e": 4073, "s": 4039, "text": "New Delhi\nNew York\nMumbai\nLondon\n" }, { "code": null, "e": 4150, "s": 4073, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html" }, { "code": null, "e": 4165, "s": 4150, "text": "Java-Functions" }, { "code": null, "e": 4170, "s": 4165, "text": "Java" }, { "code": null, "e": 4175, "s": 4170, "text": "Java" }, { "code": null, "e": 4273, "s": 4175, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4288, "s": 4273, "text": "Stream In Java" }, { "code": null, "e": 4309, "s": 4288, "text": "Introduction to Java" }, { "code": null, "e": 4330, "s": 4309, "text": "Constructors in Java" }, { "code": null, "e": 4349, "s": 4330, "text": "Exceptions in Java" }, { "code": null, "e": 4366, "s": 4349, "text": "Generics in Java" }, { "code": null, "e": 4392, "s": 4366, "text": "Java Programming Examples" }, { "code": null, "e": 4422, "s": 4392, "text": "Functional Interfaces in Java" }, { "code": null, "e": 4438, "s": 4422, "text": "Strings in Java" }, { "code": null, "e": 4475, "s": 4438, "text": "Differences between JDK, JRE and JVM" } ]
Remove an Entry using value from HashMap while Iterating over it
11 Dec, 2018 Given a HashMap and a value in Java, the task is to remove an entry from this HashMap using the value, while iterating over it. Examples: Input: HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, value = “ForGeeks”Output: {1=Geeks, 3=GeeksForGeeks} Input: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, value = kOutput: {1=G, 2=e, 3=e, 5=s} Using Java 7 and before:Get the HashMap and the ValueCreate an iterator to iterate over the HashMap using HashMap.iterate() method.Iterate over the HashMap using the Iterator.hasNext() method.While iterating, check for the value at that iteration to be equal to the value specified. The entry value of the Map can be obtained with the help of entry.getValue() method.If the value matches, remove the entry of that iteration from the HashMap using remove() method.The required entry has been successfully removed.Syntax:Iterator<>> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = iterator.next(); if (valueToBeRemoved.equals(entry.getValue())) { iterator.remove(); } } Below is the implementation of the above approach:// Java program to remove an entry using value// from a HashMap while iterating over it import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, "Geeks"); map.put(2, "ForGeeks"); map.put(3, "GeeksForGeeks"); // Get the value to be removed String valueToBeRemoved = "ForGeeks"; // Print the initial HashMap System.out.println("Original HashMap: " + map); // Get the iterator over the HashMap Iterator<Map.Entry<Integer, String> > iterator = map.entrySet().iterator(); // Iterate over the HashMap while (iterator.hasNext()) { // Get the entry at this iteration Map.Entry<Integer, String> entry = iterator.next(); // Check if this value is the required value if (valueToBeRemoved.equals(entry.getValue())) { // Remove this entry from HashMap iterator.remove(); } } // Print the modified HashMap System.out.println("Modified HashMap: " + map); }}Output:Original HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks} Modified HashMap: {1=Geeks, 3=GeeksForGeeks} Get the HashMap and the ValueCreate an iterator to iterate over the HashMap using HashMap.iterate() method.Iterate over the HashMap using the Iterator.hasNext() method.While iterating, check for the value at that iteration to be equal to the value specified. The entry value of the Map can be obtained with the help of entry.getValue() method.If the value matches, remove the entry of that iteration from the HashMap using remove() method.The required entry has been successfully removed. Get the HashMap and the Value Create an iterator to iterate over the HashMap using HashMap.iterate() method. Iterate over the HashMap using the Iterator.hasNext() method. While iterating, check for the value at that iteration to be equal to the value specified. The entry value of the Map can be obtained with the help of entry.getValue() method. If the value matches, remove the entry of that iteration from the HashMap using remove() method. The required entry has been successfully removed. Syntax: Iterator<>> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = iterator.next(); if (valueToBeRemoved.equals(entry.getValue())) { iterator.remove(); } } Below is the implementation of the above approach: // Java program to remove an entry using value// from a HashMap while iterating over it import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, "Geeks"); map.put(2, "ForGeeks"); map.put(3, "GeeksForGeeks"); // Get the value to be removed String valueToBeRemoved = "ForGeeks"; // Print the initial HashMap System.out.println("Original HashMap: " + map); // Get the iterator over the HashMap Iterator<Map.Entry<Integer, String> > iterator = map.entrySet().iterator(); // Iterate over the HashMap while (iterator.hasNext()) { // Get the entry at this iteration Map.Entry<Integer, String> entry = iterator.next(); // Check if this value is the required value if (valueToBeRemoved.equals(entry.getValue())) { // Remove this entry from HashMap iterator.remove(); } } // Print the modified HashMap System.out.println("Modified HashMap: " + map); }} Original HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks} Modified HashMap: {1=Geeks, 3=GeeksForGeeks} Using Java 8 lambda expressions:Get the HashMap and the ValueGet the entry set of this map using HashMap.entrySet() method.Using lambda expression, remove the entry from the map if the value is equal to the value specified. The entry value of the Map can be obtained with the help of entry.getValue() method.The required entry has been successfully removed.Syntax:map.entrySet() .removeIf( entry -> (valueToBeRemoved .equals(entry.getValue()))); Below is the implementation of the above approach:// Java program to remove an entry using value// from a HashMap while iterating over it import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, "Geeks"); map.put(2, "ForGeeks"); map.put(3, "GeeksForGeeks"); // Get the value to be removed String valueToBeRemoved = "ForGeeks"; // Print the initial HashMap System.out.println("Original HashMap: " + map); // Remove the specified entry from the Map map.entrySet() .removeIf( entry -> (valueToBeRemoved.equals(entry.getValue()))); // Print the modified HashMap System.out.println("Modified HashMap: " + map); }}Output:Original HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks} Modified HashMap: {1=Geeks, 3=GeeksForGeeks} Get the HashMap and the ValueGet the entry set of this map using HashMap.entrySet() method.Using lambda expression, remove the entry from the map if the value is equal to the value specified. The entry value of the Map can be obtained with the help of entry.getValue() method.The required entry has been successfully removed. Get the HashMap and the Value Get the entry set of this map using HashMap.entrySet() method. Using lambda expression, remove the entry from the map if the value is equal to the value specified. The entry value of the Map can be obtained with the help of entry.getValue() method. The required entry has been successfully removed. Syntax: map.entrySet() .removeIf( entry -> (valueToBeRemoved .equals(entry.getValue()))); Below is the implementation of the above approach: // Java program to remove an entry using value// from a HashMap while iterating over it import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, "Geeks"); map.put(2, "ForGeeks"); map.put(3, "GeeksForGeeks"); // Get the value to be removed String valueToBeRemoved = "ForGeeks"; // Print the initial HashMap System.out.println("Original HashMap: " + map); // Remove the specified entry from the Map map.entrySet() .removeIf( entry -> (valueToBeRemoved.equals(entry.getValue()))); // Print the modified HashMap System.out.println("Modified HashMap: " + map); }} Original HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks} Modified HashMap: {1=Geeks, 3=GeeksForGeeks} Java - util package Java-Collections Java-HashMap Java-Map-Programs Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Queue Interface In Java Multidimensional Arrays in Java How to add an element to an Array in Java? Stack Class in Java PriorityQueue in Java Math pow() method in Java with Example Initialize an ArrayList in Java List Interface in Java with Examples ArrayList in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Dec, 2018" }, { "code": null, "e": 156, "s": 28, "text": "Given a HashMap and a value in Java, the task is to remove an entry from this HashMap using the value, while iterating over it." }, { "code": null, "e": 166, "s": 156, "text": "Examples:" }, { "code": null, "e": 275, "s": 166, "text": "Input: HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, value = “ForGeeks”Output: {1=Geeks, 3=GeeksForGeeks}" }, { "code": null, "e": 356, "s": 275, "text": "Input: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, value = kOutput: {1=G, 2=e, 3=e, 5=s}" }, { "code": null, "e": 2554, "s": 356, "text": "Using Java 7 and before:Get the HashMap and the ValueCreate an iterator to iterate over the HashMap using HashMap.iterate() method.Iterate over the HashMap using the Iterator.hasNext() method.While iterating, check for the value at that iteration to be equal to the value specified. The entry value of the Map can be obtained with the help of entry.getValue() method.If the value matches, remove the entry of that iteration from the HashMap using remove() method.The required entry has been successfully removed.Syntax:Iterator<>> \n iterator = map.entrySet().iterator();\n\nwhile (iterator.hasNext()) {\n Map.Entry entry = iterator.next();\n if (valueToBeRemoved.equals(entry.getValue())) {\n iterator.remove();\n }\n}\nBelow is the implementation of the above approach:// Java program to remove an entry using value// from a HashMap while iterating over it import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, \"Geeks\"); map.put(2, \"ForGeeks\"); map.put(3, \"GeeksForGeeks\"); // Get the value to be removed String valueToBeRemoved = \"ForGeeks\"; // Print the initial HashMap System.out.println(\"Original HashMap: \" + map); // Get the iterator over the HashMap Iterator<Map.Entry<Integer, String> > iterator = map.entrySet().iterator(); // Iterate over the HashMap while (iterator.hasNext()) { // Get the entry at this iteration Map.Entry<Integer, String> entry = iterator.next(); // Check if this value is the required value if (valueToBeRemoved.equals(entry.getValue())) { // Remove this entry from HashMap iterator.remove(); } } // Print the modified HashMap System.out.println(\"Modified HashMap: \" + map); }}Output:Original HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}\nModified HashMap: {1=Geeks, 3=GeeksForGeeks}\n" }, { "code": null, "e": 3043, "s": 2554, "text": "Get the HashMap and the ValueCreate an iterator to iterate over the HashMap using HashMap.iterate() method.Iterate over the HashMap using the Iterator.hasNext() method.While iterating, check for the value at that iteration to be equal to the value specified. The entry value of the Map can be obtained with the help of entry.getValue() method.If the value matches, remove the entry of that iteration from the HashMap using remove() method.The required entry has been successfully removed." }, { "code": null, "e": 3073, "s": 3043, "text": "Get the HashMap and the Value" }, { "code": null, "e": 3152, "s": 3073, "text": "Create an iterator to iterate over the HashMap using HashMap.iterate() method." }, { "code": null, "e": 3214, "s": 3152, "text": "Iterate over the HashMap using the Iterator.hasNext() method." }, { "code": null, "e": 3390, "s": 3214, "text": "While iterating, check for the value at that iteration to be equal to the value specified. The entry value of the Map can be obtained with the help of entry.getValue() method." }, { "code": null, "e": 3487, "s": 3390, "text": "If the value matches, remove the entry of that iteration from the HashMap using remove() method." }, { "code": null, "e": 3537, "s": 3487, "text": "The required entry has been successfully removed." }, { "code": null, "e": 3545, "s": 3537, "text": "Syntax:" }, { "code": null, "e": 3758, "s": 3545, "text": "Iterator<>> \n iterator = map.entrySet().iterator();\n\nwhile (iterator.hasNext()) {\n Map.Entry entry = iterator.next();\n if (valueToBeRemoved.equals(entry.getValue())) {\n iterator.remove();\n }\n}\n" }, { "code": null, "e": 3809, "s": 3758, "text": "Below is the implementation of the above approach:" }, { "code": "// Java program to remove an entry using value// from a HashMap while iterating over it import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, \"Geeks\"); map.put(2, \"ForGeeks\"); map.put(3, \"GeeksForGeeks\"); // Get the value to be removed String valueToBeRemoved = \"ForGeeks\"; // Print the initial HashMap System.out.println(\"Original HashMap: \" + map); // Get the iterator over the HashMap Iterator<Map.Entry<Integer, String> > iterator = map.entrySet().iterator(); // Iterate over the HashMap while (iterator.hasNext()) { // Get the entry at this iteration Map.Entry<Integer, String> entry = iterator.next(); // Check if this value is the required value if (valueToBeRemoved.equals(entry.getValue())) { // Remove this entry from HashMap iterator.remove(); } } // Print the modified HashMap System.out.println(\"Modified HashMap: \" + map); }}", "e": 5117, "s": 3809, "text": null }, { "code": null, "e": 5220, "s": 5117, "text": "Original HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}\nModified HashMap: {1=Geeks, 3=GeeksForGeeks}\n" }, { "code": null, "e": 6750, "s": 5220, "text": "Using Java 8 lambda expressions:Get the HashMap and the ValueGet the entry set of this map using HashMap.entrySet() method.Using lambda expression, remove the entry from the map if the value is equal to the value specified. The entry value of the Map can be obtained with the help of entry.getValue() method.The required entry has been successfully removed.Syntax:map.entrySet()\n .removeIf(\n entry -> (valueToBeRemoved\n .equals(entry.getValue())));\nBelow is the implementation of the above approach:// Java program to remove an entry using value// from a HashMap while iterating over it import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, \"Geeks\"); map.put(2, \"ForGeeks\"); map.put(3, \"GeeksForGeeks\"); // Get the value to be removed String valueToBeRemoved = \"ForGeeks\"; // Print the initial HashMap System.out.println(\"Original HashMap: \" + map); // Remove the specified entry from the Map map.entrySet() .removeIf( entry -> (valueToBeRemoved.equals(entry.getValue()))); // Print the modified HashMap System.out.println(\"Modified HashMap: \" + map); }}Output:Original HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}\nModified HashMap: {1=Geeks, 3=GeeksForGeeks}\n" }, { "code": null, "e": 7076, "s": 6750, "text": "Get the HashMap and the ValueGet the entry set of this map using HashMap.entrySet() method.Using lambda expression, remove the entry from the map if the value is equal to the value specified. The entry value of the Map can be obtained with the help of entry.getValue() method.The required entry has been successfully removed." }, { "code": null, "e": 7106, "s": 7076, "text": "Get the HashMap and the Value" }, { "code": null, "e": 7169, "s": 7106, "text": "Get the entry set of this map using HashMap.entrySet() method." }, { "code": null, "e": 7355, "s": 7169, "text": "Using lambda expression, remove the entry from the map if the value is equal to the value specified. The entry value of the Map can be obtained with the help of entry.getValue() method." }, { "code": null, "e": 7405, "s": 7355, "text": "The required entry has been successfully removed." }, { "code": null, "e": 7413, "s": 7405, "text": "Syntax:" }, { "code": null, "e": 7526, "s": 7413, "text": "map.entrySet()\n .removeIf(\n entry -> (valueToBeRemoved\n .equals(entry.getValue())));\n" }, { "code": null, "e": 7577, "s": 7526, "text": "Below is the implementation of the above approach:" }, { "code": "// Java program to remove an entry using value// from a HashMap while iterating over it import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, \"Geeks\"); map.put(2, \"ForGeeks\"); map.put(3, \"GeeksForGeeks\"); // Get the value to be removed String valueToBeRemoved = \"ForGeeks\"; // Print the initial HashMap System.out.println(\"Original HashMap: \" + map); // Remove the specified entry from the Map map.entrySet() .removeIf( entry -> (valueToBeRemoved.equals(entry.getValue()))); // Print the modified HashMap System.out.println(\"Modified HashMap: \" + map); }}", "e": 8472, "s": 7577, "text": null }, { "code": null, "e": 8575, "s": 8472, "text": "Original HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}\nModified HashMap: {1=Geeks, 3=GeeksForGeeks}\n" }, { "code": null, "e": 8595, "s": 8575, "text": "Java - util package" }, { "code": null, "e": 8612, "s": 8595, "text": "Java-Collections" }, { "code": null, "e": 8625, "s": 8612, "text": "Java-HashMap" }, { "code": null, "e": 8643, "s": 8625, "text": "Java-Map-Programs" }, { "code": null, "e": 8648, "s": 8643, "text": "Java" }, { "code": null, "e": 8653, "s": 8648, "text": "Java" }, { "code": null, "e": 8670, "s": 8653, "text": "Java-Collections" }, { "code": null, "e": 8768, "s": 8670, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8787, "s": 8768, "text": "Interfaces in Java" }, { "code": null, "e": 8811, "s": 8787, "text": "Queue Interface In Java" }, { "code": null, "e": 8843, "s": 8811, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 8886, "s": 8843, "text": "How to add an element to an Array in Java?" }, { "code": null, "e": 8906, "s": 8886, "text": "Stack Class in Java" }, { "code": null, "e": 8928, "s": 8906, "text": "PriorityQueue in Java" }, { "code": null, "e": 8967, "s": 8928, "text": "Math pow() method in Java with Example" }, { "code": null, "e": 8999, "s": 8967, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 9036, "s": 8999, "text": "List Interface in Java with Examples" } ]
How to Define an Auto Increment Primary Key in PostgreSQL using Python?
11 Dec, 2020 Prerequisite: PostgreSQL Python has various database drivers for PostgreSQL. Currently, most used version is psycopg2 because it fully implements the Python DB-API 2.0 specification. The psycopg2 provides many useful features such as client-side and server-side cursors, asynchronous notification and communication, COPY command support, etc. psycopg2 can be downloaded like any other module using the following command: pip install psycopg2 PostgreSQL’s way of creating Primary key with auto increment feature : A column has to be defined with SERIAL PRIMARY KEY. Here SERIAL is not a true data type, but is simply shorthand notation that tells Postgres to create an auto incremented, unique identifier for the specified column. By simply setting a column as SERIAL with PRIMARY KEY attached, Postgres will handle all the complicated behind-the-scenes work and automatically increment our the specified column with a unique, primary key value for every INSERT. Database name: testdb Table name: EMPLOYEE In the EMPLOYEE TABLE, column named EMPLOYEE_ID will be implemented as an auto-incremented Primary key column. Syntax: CREATE TABLE <table_name>( <column1_name> SERIAL NOT NULL PRIMARY KEY, . . ); The implementation of creating a table with such specification is given below: Python3 import psycopg2 def create_table(): conn = None try: # connect to the PostgreSQL server conn = psycopg2.connect(database="testdb", user="postgres", password="password", host="127.0.0.1", port="5432") print("Opened database successfully") # create a cursor cursor = conn.cursor() # Droping EMPLOYEE table if already exists. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") # Creating table as per requirement, let us have EMPLOYEE table # and in order to have auto increment primary key, EMPLOYEE_ID SERIAL PRIMARY KEY # is used and it is explained before code sql = '''CREATE TABLE EMPLOYEE( EMPLOYEE_ID SERIAL PRIMARY KEY, FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )''' cursor.execute(sql) print("Table created successfully........") # close communication with the PostgreSQL database server cursor.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_table() We can see the table created using pgadmin tool Now, Insertion needs to done to see if our auto-increment feature works or not. This can be done either directly through pgadmin or using python code. pgadmin way : Below is the screenshot that shows execution of insert queries and resultant result-set. Explanation of auto increment primary key Using python code: Python3 import psycopg2try: connection = psycopg2.connect(user="postgres", password="password", host="127.0.0.1", port="5432", database="testdb") cursor = connection.cursor() # As Employee table is having auto incremented primary id column(employee_id), no need to specify about that value here postgres_insert_query = ''' INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE,SEX,INCOME) VALUES (%s,%s,%s,%s,%s)''' record_to_insert = ('asd', 'wer', 19, 'f', 5000) cursor.execute(postgres_insert_query, record_to_insert) connection.commit() count = cursor.rowcount print(count, "Record inserted successfully into Employee table") except (Exception, psycopg2.Error) as error: if(connection): print("Failed to insert record into Employee table", error) finally: # closing database connection. if(connection): cursor.close() connection.close() print("PostgreSQL connection is closed") Output of employee table after executing above program : Python-database Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Dec, 2020" }, { "code": null, "e": 53, "s": 28, "text": "Prerequisite: PostgreSQL" }, { "code": null, "e": 372, "s": 53, "text": "Python has various database drivers for PostgreSQL. Currently, most used version is psycopg2 because it fully implements the Python DB-API 2.0 specification. The psycopg2 provides many useful features such as client-side and server-side cursors, asynchronous notification and communication, COPY command support, etc." }, { "code": null, "e": 450, "s": 372, "text": "psycopg2 can be downloaded like any other module using the following command:" }, { "code": null, "e": 471, "s": 450, "text": "pip install psycopg2" }, { "code": null, "e": 542, "s": 471, "text": "PostgreSQL’s way of creating Primary key with auto increment feature :" }, { "code": null, "e": 991, "s": 542, "text": "A column has to be defined with SERIAL PRIMARY KEY. Here SERIAL is not a true data type, but is simply shorthand notation that tells Postgres to create an auto incremented, unique identifier for the specified column. By simply setting a column as SERIAL with PRIMARY KEY attached, Postgres will handle all the complicated behind-the-scenes work and automatically increment our the specified column with a unique, primary key value for every INSERT." }, { "code": null, "e": 1013, "s": 991, "text": "Database name: testdb" }, { "code": null, "e": 1034, "s": 1013, "text": "Table name: EMPLOYEE" }, { "code": null, "e": 1146, "s": 1034, "text": "In the EMPLOYEE TABLE, column named EMPLOYEE_ID will be implemented as an auto-incremented Primary key column. " }, { "code": null, "e": 1154, "s": 1146, "text": "Syntax:" }, { "code": null, "e": 1181, "s": 1154, "text": "CREATE TABLE <table_name>(" }, { "code": null, "e": 1225, "s": 1181, "text": "<column1_name> SERIAL NOT NULL PRIMARY KEY," }, { "code": null, "e": 1227, "s": 1225, "text": "." }, { "code": null, "e": 1229, "s": 1227, "text": "." }, { "code": null, "e": 1232, "s": 1229, "text": ");" }, { "code": null, "e": 1311, "s": 1232, "text": "The implementation of creating a table with such specification is given below:" }, { "code": null, "e": 1319, "s": 1311, "text": "Python3" }, { "code": "import psycopg2 def create_table(): conn = None try: # connect to the PostgreSQL server conn = psycopg2.connect(database=\"testdb\", user=\"postgres\", password=\"password\", host=\"127.0.0.1\", port=\"5432\") print(\"Opened database successfully\") # create a cursor cursor = conn.cursor() # Droping EMPLOYEE table if already exists. cursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\") # Creating table as per requirement, let us have EMPLOYEE table # and in order to have auto increment primary key, EMPLOYEE_ID SERIAL PRIMARY KEY # is used and it is explained before code sql = '''CREATE TABLE EMPLOYEE( EMPLOYEE_ID SERIAL PRIMARY KEY, FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )''' cursor.execute(sql) print(\"Table created successfully........\") # close communication with the PostgreSQL database server cursor.close() # commit the changes conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() if __name__ == '__main__': create_table()", "e": 2658, "s": 1319, "text": null }, { "code": null, "e": 2706, "s": 2658, "text": "We can see the table created using pgadmin tool" }, { "code": null, "e": 2857, "s": 2706, "text": "Now, Insertion needs to done to see if our auto-increment feature works or not. This can be done either directly through pgadmin or using python code." }, { "code": null, "e": 2871, "s": 2857, "text": "pgadmin way :" }, { "code": null, "e": 2960, "s": 2871, "text": "Below is the screenshot that shows execution of insert queries and resultant result-set." }, { "code": null, "e": 3002, "s": 2960, "text": "Explanation of auto increment primary key" }, { "code": null, "e": 3021, "s": 3002, "text": "Using python code:" }, { "code": null, "e": 3029, "s": 3021, "text": "Python3" }, { "code": "import psycopg2try: connection = psycopg2.connect(user=\"postgres\", password=\"password\", host=\"127.0.0.1\", port=\"5432\", database=\"testdb\") cursor = connection.cursor() # As Employee table is having auto incremented primary id column(employee_id), no need to specify about that value here postgres_insert_query = ''' INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE,SEX,INCOME) VALUES (%s,%s,%s,%s,%s)''' record_to_insert = ('asd', 'wer', 19, 'f', 5000) cursor.execute(postgres_insert_query, record_to_insert) connection.commit() count = cursor.rowcount print(count, \"Record inserted successfully into Employee table\") except (Exception, psycopg2.Error) as error: if(connection): print(\"Failed to insert record into Employee table\", error) finally: # closing database connection. if(connection): cursor.close() connection.close() print(\"PostgreSQL connection is closed\")", "e": 4110, "s": 3029, "text": null }, { "code": null, "e": 4167, "s": 4110, "text": "Output of employee table after executing above program :" }, { "code": null, "e": 4183, "s": 4167, "text": "Python-database" }, { "code": null, "e": 4207, "s": 4183, "text": "Technical Scripter 2020" }, { "code": null, "e": 4214, "s": 4207, "text": "Python" }, { "code": null, "e": 4233, "s": 4214, "text": "Technical Scripter" }, { "code": null, "e": 4331, "s": 4233, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4363, "s": 4331, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4390, "s": 4363, "text": "Python Classes and Objects" }, { "code": null, "e": 4411, "s": 4390, "text": "Python OOPs Concepts" }, { "code": null, "e": 4434, "s": 4411, "text": "Introduction To PYTHON" }, { "code": null, "e": 4490, "s": 4434, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4521, "s": 4490, "text": "Python | os.path.join() method" }, { "code": null, "e": 4563, "s": 4521, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4605, "s": 4563, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4644, "s": 4605, "text": "Python | Get unique values from a list" } ]
What is Reflection in C#?
28 Aug, 2019 Reflection is the process of describing the metadata of types, methods and fields in a code. The namespace System.Reflection enables you to obtain data about the loaded assemblies, the elements within them like classes, methods and value types. Some of the commonly used classes of System.Reflection are: Note: There are numerous other classes, the above table gives info about only the commonly used. Let us now look at an example to depict how reflection works in C#. Example 1: In the code given below, we load the type t as a string using the typeof method. Then we apply reflection on t to find any information about string class, like its name, fullname, namespace, and basetype. // C# program to illustrate// the use of Reflectionusing System;using System.Reflection; namespace Reflection_Demo { class Program { // Main Method static void Main(string[] args) { // Initialise t as typeof string Type t = typeof(string); // Use Reflection to find about // any sort of data related to t Console.WriteLine("Name : {0}", t.Name); Console.WriteLine("Full Name : {0}", t.FullName); Console.WriteLine("Namespace : {0}", t.Namespace); Console.WriteLine("Base Type : {0}", t.BaseType); }}} Output: Name : String Full Name : System.String Namespace : System Base Type : System.Object Example 2: In this code, we use reflection to show all the metadata related to the program which includes classes, methods of these classes and the parameters associated with these parameters. // C# program to illustrate// the use of Reflectionusing System;using System.Reflection; namespace Reflection_Metadata { // Define a class Studentclass Student { // Properties definition public int RollNo { get; set; } public string Name { get; set; } // No Argument Constructor public Student() { RollNo = 0; Name = string.Empty; } // Parameterised Constructor public Student(int rno, string n) { RollNo = rno; Name = n; } // Method to Display Student Data public void displayData() { Console.WriteLine("Roll Number : {0}", RollNo); Console.WriteLine("Name : {0}", Name); }} class GFG { // Main Method static void Main(string[] args) { // Declare Instance of class Assembly // Call the GetExecutingAssembly method // to load the current assembly Assembly executing = Assembly.GetExecutingAssembly(); // Array to store types of the assembly Type[] types = executing.GetTypes(); foreach(var item in types) { // Display each type Console.WriteLine("Class : {0}", item.Name); // Array to store methods MethodInfo[] methods = item.GetMethods(); foreach(var method in methods) { // Display each method Console.WriteLine("--> Method : {0}", method.Name); // Array to store parameters ParameterInfo[] parameters = method.GetParameters(); foreach(var arg in parameters) { // Display each parameter Console.WriteLine("----> Parameter : {0} Type : {1}", arg.Name, arg.ParameterType); } } } }}} Output: Class : Student --> Method : get_RollNo --> Method : set_RollNo ----> Parameter : value Type : System.Int32 --> Method : get_Name --> Method : set_Name ----> Parameter : value Type : System.String --> Method : displayData --> Method : ToString --> Method : Equals ----> Parameter : obj Type : System.Object --> Method : GetHashCode --> Method : GetType Class : Program --> Method : ToString --> Method : Equals ----> Parameter : obj Type : System.Object --> Method : GetHashCode --> Method : GetType C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Multiple inheritance using interfaces Introduction to .NET Framework C# | Delegates Differences Between .NET Core and .NET Framework C# | Data Types C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Replace() Method C# | Arrays
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Aug, 2019" }, { "code": null, "e": 333, "s": 28, "text": "Reflection is the process of describing the metadata of types, methods and fields in a code. The namespace System.Reflection enables you to obtain data about the loaded assemblies, the elements within them like classes, methods and value types. Some of the commonly used classes of System.Reflection are:" }, { "code": null, "e": 430, "s": 333, "text": "Note: There are numerous other classes, the above table gives info about only the commonly used." }, { "code": null, "e": 498, "s": 430, "text": "Let us now look at an example to depict how reflection works in C#." }, { "code": null, "e": 714, "s": 498, "text": "Example 1: In the code given below, we load the type t as a string using the typeof method. Then we apply reflection on t to find any information about string class, like its name, fullname, namespace, and basetype." }, { "code": "// C# program to illustrate// the use of Reflectionusing System;using System.Reflection; namespace Reflection_Demo { class Program { // Main Method static void Main(string[] args) { // Initialise t as typeof string Type t = typeof(string); // Use Reflection to find about // any sort of data related to t Console.WriteLine(\"Name : {0}\", t.Name); Console.WriteLine(\"Full Name : {0}\", t.FullName); Console.WriteLine(\"Namespace : {0}\", t.Namespace); Console.WriteLine(\"Base Type : {0}\", t.BaseType); }}}", "e": 1297, "s": 714, "text": null }, { "code": null, "e": 1305, "s": 1297, "text": "Output:" }, { "code": null, "e": 1391, "s": 1305, "text": "Name : String\nFull Name : System.String\nNamespace : System\nBase Type : System.Object\n" }, { "code": null, "e": 1584, "s": 1391, "text": "Example 2: In this code, we use reflection to show all the metadata related to the program which includes classes, methods of these classes and the parameters associated with these parameters." }, { "code": "// C# program to illustrate// the use of Reflectionusing System;using System.Reflection; namespace Reflection_Metadata { // Define a class Studentclass Student { // Properties definition public int RollNo { get; set; } public string Name { get; set; } // No Argument Constructor public Student() { RollNo = 0; Name = string.Empty; } // Parameterised Constructor public Student(int rno, string n) { RollNo = rno; Name = n; } // Method to Display Student Data public void displayData() { Console.WriteLine(\"Roll Number : {0}\", RollNo); Console.WriteLine(\"Name : {0}\", Name); }} class GFG { // Main Method static void Main(string[] args) { // Declare Instance of class Assembly // Call the GetExecutingAssembly method // to load the current assembly Assembly executing = Assembly.GetExecutingAssembly(); // Array to store types of the assembly Type[] types = executing.GetTypes(); foreach(var item in types) { // Display each type Console.WriteLine(\"Class : {0}\", item.Name); // Array to store methods MethodInfo[] methods = item.GetMethods(); foreach(var method in methods) { // Display each method Console.WriteLine(\"--> Method : {0}\", method.Name); // Array to store parameters ParameterInfo[] parameters = method.GetParameters(); foreach(var arg in parameters) { // Display each parameter Console.WriteLine(\"----> Parameter : {0} Type : {1}\", arg.Name, arg.ParameterType); } } } }}}", "e": 3470, "s": 1584, "text": null }, { "code": null, "e": 3478, "s": 3470, "text": "Output:" }, { "code": null, "e": 3986, "s": 3478, "text": " Class : Student\n--> Method : get_RollNo\n--> Method : set_RollNo\n----> Parameter : value Type : System.Int32\n--> Method : get_Name\n--> Method : set_Name\n----> Parameter : value Type : System.String\n--> Method : displayData\n--> Method : ToString\n--> Method : Equals\n----> Parameter : obj Type : System.Object\n--> Method : GetHashCode\n--> Method : GetType\n\n Class : Program\n--> Method : ToString\n--> Method : Equals\n----> Parameter : obj Type : System.Object\n--> Method : GetHashCode\n--> Method : GetType\n" }, { "code": null, "e": 3989, "s": 3986, "text": "C#" }, { "code": null, "e": 4087, "s": 3989, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4115, "s": 4087, "text": "C# Dictionary with examples" }, { "code": null, "e": 4158, "s": 4115, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 4189, "s": 4158, "text": "Introduction to .NET Framework" }, { "code": null, "e": 4204, "s": 4189, "text": "C# | Delegates" }, { "code": null, "e": 4253, "s": 4204, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 4269, "s": 4253, "text": "C# | Data Types" }, { "code": null, "e": 4309, "s": 4269, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 4332, "s": 4309, "text": "Extension Method in C#" }, { "code": null, "e": 4354, "s": 4332, "text": "C# | Replace() Method" } ]
What is the size_t data type in C?
17 Jul, 2020 size_t is an unsigned integral data type which is defined in various header files such as: <stddef.h>, <stdio.h>, <stdlib.h>, <string.h>, <time.h>, <wchar.h> It’s a type which is used to represent the size of objects in bytes and is therefore used as the return type by the sizeof operator. It is guaranteed to be big enough to contain the size of the biggest object the host system can handle. Basically the maximum permissible size is dependent on the compiler; if the compiler is 32 bit then it is simply a typedef(i.e., alias) for unsigned int but if the compiler is 64 bit then it would be a typedef for unsigned long long. The size_t data type is never negative.Therefore many C library functions like malloc, memcpy and strlen declare their arguments and return type as size_t. For instance, // Declaration of various standard library functions. // Here argument of 'n' refers to maximum blocks that can be// allocated which is guaranteed to be non-negative.void *malloc(size_t n); // While copying 'n' bytes from 's2' to 's1'// n must be non-negative integer.void *memcpy(void *s1, void const *s2, size_t n); // strlen() uses size_t because the length of any string// will always be at least 0.size_t strlen(char const *s); size_t or any unsigned type might be seen used as loop variable as loop variables are typically greater than or equal to 0.Note: When we use a size_t object, we have to make sure that in all the contexts it is used, including arithmetic, we want only non-negative values. For instance, the following program would definitely give the unexpected result: // C program to demonstrate that size_t or// any unsigned int type should be used // carefully when used in a loop.#include<stdio.h> #define N 10 int main(){ int a[N]; // This is fine. for (size_t n = 0; n < N; ++n) { a[n] = n; } // But reverse cycles are tricky for unsigned // types as they can lead to infinite loops. for (size_t n = N-1; n >= 0; --n) printf("%d ", a[n]);} Output Infinite loop and then segmentation fault This article is contributed by Shubham Bansal. 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. jflopezfernandez prathusingal cpp-data-types C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ std::string class in C++ Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jul, 2020" }, { "code": null, "e": 147, "s": 54, "text": "size_t is an unsigned integral data type which is defined in various header files such as: " }, { "code": "<stddef.h>, <stdio.h>, <stdlib.h>, <string.h>, <time.h>, <wchar.h>", "e": 214, "s": 147, "text": null }, { "code": null, "e": 857, "s": 214, "text": "It’s a type which is used to represent the size of objects in bytes and is therefore used as the return type by the sizeof operator. It is guaranteed to be big enough to contain the size of the biggest object the host system can handle. Basically the maximum permissible size is dependent on the compiler; if the compiler is 32 bit then it is simply a typedef(i.e., alias) for unsigned int but if the compiler is 64 bit then it would be a typedef for unsigned long long. The size_t data type is never negative.Therefore many C library functions like malloc, memcpy and strlen declare their arguments and return type as size_t. For instance, " }, { "code": "// Declaration of various standard library functions. // Here argument of 'n' refers to maximum blocks that can be// allocated which is guaranteed to be non-negative.void *malloc(size_t n); // While copying 'n' bytes from 's2' to 's1'// n must be non-negative integer.void *memcpy(void *s1, void const *s2, size_t n); // strlen() uses size_t because the length of any string// will always be at least 0.size_t strlen(char const *s);", "e": 1293, "s": 857, "text": null }, { "code": null, "e": 1648, "s": 1293, "text": "size_t or any unsigned type might be seen used as loop variable as loop variables are typically greater than or equal to 0.Note: When we use a size_t object, we have to make sure that in all the contexts it is used, including arithmetic, we want only non-negative values. For instance, the following program would definitely give the unexpected result: " }, { "code": "// C program to demonstrate that size_t or// any unsigned int type should be used // carefully when used in a loop.#include<stdio.h> #define N 10 int main(){ int a[N]; // This is fine. for (size_t n = 0; n < N; ++n) { a[n] = n; } // But reverse cycles are tricky for unsigned // types as they can lead to infinite loops. for (size_t n = N-1; n >= 0; --n) printf(\"%d \", a[n]);}", "e": 2075, "s": 1648, "text": null }, { "code": null, "e": 2125, "s": 2075, "text": "Output\nInfinite loop and then segmentation fault\n" }, { "code": null, "e": 2428, "s": 2125, "text": "This article is contributed by Shubham Bansal. 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. " }, { "code": null, "e": 2445, "s": 2428, "text": "jflopezfernandez" }, { "code": null, "e": 2458, "s": 2445, "text": "prathusingal" }, { "code": null, "e": 2473, "s": 2458, "text": "cpp-data-types" }, { "code": null, "e": 2484, "s": 2473, "text": "C Language" }, { "code": null, "e": 2488, "s": 2484, "text": "C++" }, { "code": null, "e": 2492, "s": 2488, "text": "CPP" }, { "code": null, "e": 2590, "s": 2492, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2607, "s": 2590, "text": "Substring in C++" }, { "code": null, "e": 2629, "s": 2607, "text": "Function Pointer in C" }, { "code": null, "e": 2675, "s": 2629, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 2720, "s": 2675, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 2745, "s": 2720, "text": "std::string class in C++" }, { "code": null, "e": 2763, "s": 2745, "text": "Vector in C++ STL" }, { "code": null, "e": 2806, "s": 2763, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 2852, "s": 2806, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 2895, "s": 2852, "text": "Set in C++ Standard Template Library (STL)" } ]
Manipulate Date and Time with the Datetime Module in Python
12 May, 2021 Have you ever wondered about working with Date and Time with Python? If you have then you must have noticed that Python does not provide any built-in method to work with either Date or Time. But thanks to the DateTime module that comes pre-loaded with Python’s standard utility modules we can easily manipulate date and time according to our own need. We can even perform operations like getting a current date, adding or subtracting date and time, and much more. In this article, we will learn all the operations that can be performed on the Date and Time using the DateTime module in Python. So before starting let’s see the basics of the DateTime module and the classes it contains. The datetime classes are categorized into 6 main classes – date – An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Its attributes are year, month and day. time – An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60 seconds. Its attributes are hour, minute, second, microsecond, and tzinfo. datetime – Its a combination of date and time along with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo. timedelta – A duration expressing the difference between two date, time, or datetime instances to microsecond resolution. tzinfo – It provides time zone information objects. timezone – A class that implements the tzinfo abstract base class as a fixed offset from the UTC (New in version 3.2). To get both the current Date and Time datetime.now() method is used. It returns the local current date and time. Syntax: datetime.now(tz) Example: Python3 # Python3 code to demonstrate # Getting current date and time using # now(). # importing datetime module for now() import datetime # using now() to get current time current_time = datetime.datetime.now() # Printing value of now. print ("Time now at greenwich meridian is : ", end = "") print (current_time) Output: Time now at greenwich meridian is : 2021-03-16 17:59:03.837572 The now() function has various attributes that can give the desired detail from the above output. Some of the attributes are year, month, date, hour, minute, second. See the below example for a better understanding. Example: Python3 # Python3 code to demonstrate # attributes of now() # importing datetime module for now() import datetime # using now() to get current time current_time = datetime.datetime.now() # Printing attributes of now(). print ("The attributes of now() are : ") print ("Year : ", end = "") print (current_time.year) print ("Month : ", end = "") print (current_time.month) print ("Day : ", end = "") print (current_time.day) print ("Hour : ", end = "") print (current_time.hour) print ("Minute : ", end = "") print (current_time.minute) print ("Second : ", end = "") print (current_time.second) print ("Microsecond : ", end = "") print (current_time.microsecond) Output: The attributes of now() are : Year : 2021 Month : 3 Day : 16 Hour : 18 Minute : 1 Second : 59 Microsecond : 490402 DateTime module also provides another method called today() that only prints the value of today’s date. Example: Python3 # Python program to get # current date # Import date class from datetime module from datetime import date # Returns the current local date today = date.today() print("Today date is: ", today) Output: Today date is: 2021-03-16 We can create a time object using the time() function. Consider the below example. Example: Python3 from datetime import datetime # Time object containing # the current time. time = datetime.now().time() print("Current Time =", time) Output: Current Time = 18:13:35.003918 Refer to the below articles to get detailed information about getting the current date and time. Get Current Date and Time using Python Get current date using Python Python program to get Current Time Get current time in milliseconds using Python Get Current Time in different Timezone using Python Across various regions in the world, different types of date formats are used. DateTime provides strftime() method to deal with such formatting. This function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation. Syntax: strftime(format) Example: Python3 # Python program to demonstrate # strftime() function from datetime import datetime # Getting current date and time now = datetime.now() print("Without formatting", now) # Example 1 s = now.strftime("%a %m %y") print('\nExample 1:', s) # Example 2 s = now.strftime("%A %-m %Y") print('\nExample 2:', s) # Example 3 s = now.strftime("%-I %p %S") print('\nExample 3:', s) # Example 4 s = now.strftime("%-j") print('\nExample 4:', s) Output: Without formatting 2021-03-16 18:28:59.055609 Example 1: Tue 03 21 Example 2: Tuesday 3 2021 Example 3: 6 PM 59 Example 4: 75 Refer to the below article to get detailed information about formatting date and time in Python. Formatting Dates in Python Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. Syntax: timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) Example: Python3 # import datetimefrom datetime import timedelta # create timedelta object with difference # of 1 weeksd1 = timedelta(weeks=1) # create timedelta object with difference # of 1 weeksd2 = timedelta(days=30) print(d1)print(d2) Output: 7 days, 0:00:00 30 days, 0:00:00 We can also use the + and – operators to add or subtract the timedelta objects from datetime objects. Example: Python3 # Timedelta function demonstration from datetime import datetime, timedelta # Using current time ini_time_for_now = datetime.now() # printing initial_date print ("initial_date", str(ini_time_for_now)) # Calculating future dates # for two years future_date_after_2yrs = ini_time_for_now + timedelta(days = 730) future_date_after_2days = ini_time_for_now + timedelta(days = 2) # printing calculated future_dates print('future_date_after_2yrs:', str(future_date_after_2yrs)) print('future_date_after_2days:', str(future_date_after_2days)) Output: initial_date 2021-03-16 18:47:53.103230 future_date_after_2yrs: 2023-03-16 18:47:53.103230 future_date_after_2days: 2021-03-18 18:47:53.103230 Note: The output will be a DateTime object. As discussed above, timedelta object represents the difference between the two dates. We can subtract one date from another and the resultant will be a timedelta object. Example 1: Python3 # import datetimefrom datetime import date # Create two dates with year, month, # dated1 = date(2021, 3, 16)d2 = date(2021, 3, 31) # Difference between two datesdiff = d2 - d1 print("Difference: ", diff.days) Output: Difference: 15 Example 2: Python3 # import datetimefrom datetime import datetime # Create two dates with year, month, # date, hour, minute, secondsd1 = datetime(2021, 3, 16, 19, 6, 6)d2 = datetime(2021, 3, 31, 12, 2, 2) # Difference between two datesdiff = d2 - d1 print("Difference: ", diff) Output: Difference: 14 days, 16:55:56 Refer to the below articles to get detailed information about finding differences in date. Difference between two dates (in minutes) using datetime.timedelta() method Python program to find number of days between two given dates The dates can also be compared using comparison operators (like <, >, <=, >=, != etc.) Example 1: Using comparison operators Python3 # Simple Python program to compare dates # importing datetime module import datetime # date in yyyy/mm/dd format d1 = datetime.datetime(2018, 5, 3) d2 = datetime.datetime(2018, 6, 1) # Comparing the dates will return # either True or False print("d1 is greater than d2 : ", d1 > d2) print("d1 is less than d2 : ", d1 < d2) print("d1 is not equal to d2 : ", d1 != d2) Output: d1 is greater than d2 : False d1 is less than d2 : True d1 is not equal to d2 : True Refer to the below article to get detailed information about comparing dates. Comparing dates in Python The datetime.now() does not have any information about the time zones. It just uses the current system time. In some situations, the time zone details may be needed. In such cases the tzinfo abstract class is used. tzinfo is an abstract base class. It cannot be instantiated directly. A concrete subclass has to derive it and implement the methods provided by this abstract class. A datetime object which does not contain any information on time zone is said to be a naive datetime object. For a naive datetime object, datetime_object.tzinfo will be None. An Aware datetime object contains the time zone information embedded in it. The methods available for implementation in tzinfo base class are : utcoffset(): It returns the offset of the datetime instance passed as an argument. It refers to the time zone offset which denotes how many hours the time zone is ahead of the Coordinated Universal Time or Universal Time Coordinate (UTC). The offset is written as +00:00. For example: for Asia/Taipei, it is written as UTC +08:00. dst(): It is abbreviated as Day-light Saving Time. It denotes advancing the clock 1 hour in the summertime so that darkness falls later according to the clock. It is set to on or off. It is checked based on a tuple containing 9 elements as follows : (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, 0) tzname(): This is used to find the time zone name of the datetime object passed. It returns a Python String object. fromutc(): This function takes up the date and time of the object in UTC and returns the equivalent local time. It is used mostly for adjusting the date and time. It is called from default datetime.astimezone() implementation. The dt.tzinfo will be passed as self, dt’s date and time data will be returned as an equivalent local time. Example: Python3 import datetime as dt from dateutil import tz tz_string = dt.datetime.now(dt.timezone.utc).astimezone().tzname() print("datetime.now() :", tz_string) NYC = tz.gettz('Europe / Berlin') dt1 = dt.datetime(2015, 5, 21, 12, 0) dt2 = dt.datetime(2015, 12, 21, 12, 0, tzinfo = NYC) print("Naive Object :", dt1.tzname()) print("Aware Object :", dt2.tzname()) Output: datetime.now() : UTC Naive Object : None Aware Object : CET We can also use pytz module to deal with cross-timezones conversion. Let’s see how it works. Pytz brings the Olson tz database into Python and thus supports almost all time zones. This module serves the date-time conversion functionalities and helps user serving international client’s base. By using astimezone() function we can convert the time into a different timezone. Syntax: astimezone(t) Example: Python3 from datetime import datetime from pytz import timezone format = "%Y-%m-%d %H:%M:%S %Z%z" # Current time in UTC now_utc = datetime.now(timezone('UTC')) print(now_utc.strftime(format)) # Convert to Asia/Kolkata time zone now_asia = now_utc.astimezone(timezone('Asia/Kolkata')) print(now_asia.strftime(format)) Output: 2021-03-17 07:41:19 UTC+0000 2021-03-17 13:11:19 IST+0530 Refer to the below articles to get detailed information about working with timezones. Python – datetime.tzinfo() Python | Timezone Conversion Python pytz Python-datetime 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 Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n12 May, 2021" }, { "code": null, "e": 492, "s": 28, "text": "Have you ever wondered about working with Date and Time with Python? If you have then you must have noticed that Python does not provide any built-in method to work with either Date or Time. But thanks to the DateTime module that comes pre-loaded with Python’s standard utility modules we can easily manipulate date and time according to our own need. We can even perform operations like getting a current date, adding or subtracting date and time, and much more." }, { "code": null, "e": 714, "s": 492, "text": "In this article, we will learn all the operations that can be performed on the Date and Time using the DateTime module in Python. So before starting let’s see the basics of the DateTime module and the classes it contains." }, { "code": null, "e": 773, "s": 714, "text": "The datetime classes are categorized into 6 main classes –" }, { "code": null, "e": 928, "s": 773, "text": "date – An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Its attributes are year, month and day." }, { "code": null, "e": 1109, "s": 928, "text": "time – An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60 seconds. Its attributes are hour, minute, second, microsecond, and tzinfo." }, { "code": null, "e": 1246, "s": 1109, "text": "datetime – Its a combination of date and time along with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo." }, { "code": null, "e": 1368, "s": 1246, "text": "timedelta – A duration expressing the difference between two date, time, or datetime instances to microsecond resolution." }, { "code": null, "e": 1420, "s": 1368, "text": "tzinfo – It provides time zone information objects." }, { "code": null, "e": 1539, "s": 1420, "text": "timezone – A class that implements the tzinfo abstract base class as a fixed offset from the UTC (New in version 3.2)." }, { "code": null, "e": 1652, "s": 1539, "text": "To get both the current Date and Time datetime.now() method is used. It returns the local current date and time." }, { "code": null, "e": 1660, "s": 1652, "text": "Syntax:" }, { "code": null, "e": 1677, "s": 1660, "text": "datetime.now(tz)" }, { "code": null, "e": 1686, "s": 1677, "text": "Example:" }, { "code": null, "e": 1694, "s": 1686, "text": "Python3" }, { "code": "# Python3 code to demonstrate # Getting current date and time using # now(). # importing datetime module for now() import datetime # using now() to get current time current_time = datetime.datetime.now() # Printing value of now. print (\"Time now at greenwich meridian is : \", end = \"\") print (current_time) ", "e": 2020, "s": 1694, "text": null }, { "code": null, "e": 2028, "s": 2020, "text": "Output:" }, { "code": null, "e": 2091, "s": 2028, "text": "Time now at greenwich meridian is : 2021-03-16 17:59:03.837572" }, { "code": null, "e": 2307, "s": 2091, "text": "The now() function has various attributes that can give the desired detail from the above output. Some of the attributes are year, month, date, hour, minute, second. See the below example for a better understanding." }, { "code": null, "e": 2316, "s": 2307, "text": "Example:" }, { "code": null, "e": 2324, "s": 2316, "text": "Python3" }, { "code": "# Python3 code to demonstrate # attributes of now() # importing datetime module for now() import datetime # using now() to get current time current_time = datetime.datetime.now() # Printing attributes of now(). print (\"The attributes of now() are : \") print (\"Year : \", end = \"\") print (current_time.year) print (\"Month : \", end = \"\") print (current_time.month) print (\"Day : \", end = \"\") print (current_time.day) print (\"Hour : \", end = \"\") print (current_time.hour) print (\"Minute : \", end = \"\") print (current_time.minute) print (\"Second : \", end = \"\") print (current_time.second) print (\"Microsecond : \", end = \"\") print (current_time.microsecond)", "e": 3036, "s": 2324, "text": null }, { "code": null, "e": 3044, "s": 3036, "text": "Output:" }, { "code": null, "e": 3160, "s": 3044, "text": "The attributes of now() are : \nYear : 2021\nMonth : 3\nDay : 16\nHour : 18\nMinute : 1\nSecond : 59\nMicrosecond : 490402" }, { "code": null, "e": 3264, "s": 3160, "text": "DateTime module also provides another method called today() that only prints the value of today’s date." }, { "code": null, "e": 3273, "s": 3264, "text": "Example:" }, { "code": null, "e": 3281, "s": 3273, "text": "Python3" }, { "code": "# Python program to get # current date # Import date class from datetime module from datetime import date # Returns the current local date today = date.today() print(\"Today date is: \", today)", "e": 3481, "s": 3281, "text": null }, { "code": null, "e": 3489, "s": 3481, "text": "Output:" }, { "code": null, "e": 3516, "s": 3489, "text": "Today date is: 2021-03-16" }, { "code": null, "e": 3599, "s": 3516, "text": "We can create a time object using the time() function. Consider the below example." }, { "code": null, "e": 3608, "s": 3599, "text": "Example:" }, { "code": null, "e": 3616, "s": 3608, "text": "Python3" }, { "code": "from datetime import datetime # Time object containing # the current time. time = datetime.now().time() print(\"Current Time =\", time)", "e": 3754, "s": 3616, "text": null }, { "code": null, "e": 3762, "s": 3754, "text": "Output:" }, { "code": null, "e": 3793, "s": 3762, "text": "Current Time = 18:13:35.003918" }, { "code": null, "e": 3890, "s": 3793, "text": "Refer to the below articles to get detailed information about getting the current date and time." }, { "code": null, "e": 3929, "s": 3890, "text": "Get Current Date and Time using Python" }, { "code": null, "e": 3959, "s": 3929, "text": "Get current date using Python" }, { "code": null, "e": 3994, "s": 3959, "text": "Python program to get Current Time" }, { "code": null, "e": 4040, "s": 3994, "text": "Get current time in milliseconds using Python" }, { "code": null, "e": 4092, "s": 4040, "text": "Get Current Time in different Timezone using Python" }, { "code": null, "e": 4408, "s": 4092, "text": "Across various regions in the world, different types of date formats are used. DateTime provides strftime() method to deal with such formatting. This function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation." }, { "code": null, "e": 4416, "s": 4408, "text": "Syntax:" }, { "code": null, "e": 4433, "s": 4416, "text": "strftime(format)" }, { "code": null, "e": 4442, "s": 4433, "text": "Example:" }, { "code": null, "e": 4450, "s": 4442, "text": "Python3" }, { "code": "# Python program to demonstrate # strftime() function from datetime import datetime # Getting current date and time now = datetime.now() print(\"Without formatting\", now) # Example 1 s = now.strftime(\"%a %m %y\") print('\\nExample 1:', s) # Example 2 s = now.strftime(\"%A %-m %Y\") print('\\nExample 2:', s) # Example 3 s = now.strftime(\"%-I %p %S\") print('\\nExample 3:', s) # Example 4 s = now.strftime(\"%-j\") print('\\nExample 4:', s)", "e": 4894, "s": 4450, "text": null }, { "code": null, "e": 4902, "s": 4894, "text": "Output:" }, { "code": null, "e": 5032, "s": 4902, "text": "Without formatting 2021-03-16 18:28:59.055609\n\nExample 1: Tue 03 21\n\nExample 2: Tuesday 3 2021\n\nExample 3: 6 PM 59\n\nExample 4: 75" }, { "code": null, "e": 5129, "s": 5032, "text": "Refer to the below article to get detailed information about formatting date and time in Python." }, { "code": null, "e": 5156, "s": 5129, "text": "Formatting Dates in Python" }, { "code": null, "e": 5334, "s": 5156, "text": "Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python." }, { "code": null, "e": 5342, "s": 5334, "text": "Syntax:" }, { "code": null, "e": 5432, "s": 5342, "text": "timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)" }, { "code": null, "e": 5441, "s": 5432, "text": "Example:" }, { "code": null, "e": 5449, "s": 5441, "text": "Python3" }, { "code": "# import datetimefrom datetime import timedelta # create timedelta object with difference # of 1 weeksd1 = timedelta(weeks=1) # create timedelta object with difference # of 1 weeksd2 = timedelta(days=30) print(d1)print(d2)", "e": 5675, "s": 5449, "text": null }, { "code": null, "e": 5683, "s": 5675, "text": "Output:" }, { "code": null, "e": 5716, "s": 5683, "text": "7 days, 0:00:00\n30 days, 0:00:00" }, { "code": null, "e": 5818, "s": 5716, "text": "We can also use the + and – operators to add or subtract the timedelta objects from datetime objects." }, { "code": null, "e": 5827, "s": 5818, "text": "Example:" }, { "code": null, "e": 5835, "s": 5827, "text": "Python3" }, { "code": "# Timedelta function demonstration from datetime import datetime, timedelta # Using current time ini_time_for_now = datetime.now() # printing initial_date print (\"initial_date\", str(ini_time_for_now)) # Calculating future dates # for two years future_date_after_2yrs = ini_time_for_now + timedelta(days = 730) future_date_after_2days = ini_time_for_now + timedelta(days = 2) # printing calculated future_dates print('future_date_after_2yrs:', str(future_date_after_2yrs)) print('future_date_after_2days:', str(future_date_after_2days)) ", "e": 6414, "s": 5835, "text": null }, { "code": null, "e": 6422, "s": 6414, "text": "Output:" }, { "code": null, "e": 6565, "s": 6422, "text": "initial_date 2021-03-16 18:47:53.103230\nfuture_date_after_2yrs: 2023-03-16 18:47:53.103230\nfuture_date_after_2days: 2021-03-18 18:47:53.103230" }, { "code": null, "e": 6609, "s": 6565, "text": "Note: The output will be a DateTime object." }, { "code": null, "e": 6779, "s": 6609, "text": "As discussed above, timedelta object represents the difference between the two dates. We can subtract one date from another and the resultant will be a timedelta object." }, { "code": null, "e": 6790, "s": 6779, "text": "Example 1:" }, { "code": null, "e": 6798, "s": 6790, "text": "Python3" }, { "code": "# import datetimefrom datetime import date # Create two dates with year, month, # dated1 = date(2021, 3, 16)d2 = date(2021, 3, 31) # Difference between two datesdiff = d2 - d1 print(\"Difference: \", diff.days)", "e": 7012, "s": 6798, "text": null }, { "code": null, "e": 7020, "s": 7012, "text": "Output:" }, { "code": null, "e": 7036, "s": 7020, "text": "Difference: 15" }, { "code": null, "e": 7047, "s": 7036, "text": "Example 2:" }, { "code": null, "e": 7055, "s": 7047, "text": "Python3" }, { "code": "# import datetimefrom datetime import datetime # Create two dates with year, month, # date, hour, minute, secondsd1 = datetime(2021, 3, 16, 19, 6, 6)d2 = datetime(2021, 3, 31, 12, 2, 2) # Difference between two datesdiff = d2 - d1 print(\"Difference: \", diff)", "e": 7319, "s": 7055, "text": null }, { "code": null, "e": 7327, "s": 7319, "text": "Output:" }, { "code": null, "e": 7358, "s": 7327, "text": "Difference: 14 days, 16:55:56" }, { "code": null, "e": 7449, "s": 7358, "text": "Refer to the below articles to get detailed information about finding differences in date." }, { "code": null, "e": 7525, "s": 7449, "text": "Difference between two dates (in minutes) using datetime.timedelta() method" }, { "code": null, "e": 7587, "s": 7525, "text": "Python program to find number of days between two given dates" }, { "code": null, "e": 7674, "s": 7587, "text": "The dates can also be compared using comparison operators (like <, >, <=, >=, != etc.)" }, { "code": null, "e": 7712, "s": 7674, "text": "Example 1: Using comparison operators" }, { "code": null, "e": 7720, "s": 7712, "text": "Python3" }, { "code": "# Simple Python program to compare dates # importing datetime module import datetime # date in yyyy/mm/dd format d1 = datetime.datetime(2018, 5, 3) d2 = datetime.datetime(2018, 6, 1) # Comparing the dates will return # either True or False print(\"d1 is greater than d2 : \", d1 > d2) print(\"d1 is less than d2 : \", d1 < d2) print(\"d1 is not equal to d2 : \", d1 != d2)", "e": 8093, "s": 7720, "text": null }, { "code": null, "e": 8101, "s": 8093, "text": "Output:" }, { "code": null, "e": 8189, "s": 8101, "text": "d1 is greater than d2 : False\nd1 is less than d2 : True\nd1 is not equal to d2 : True" }, { "code": null, "e": 8267, "s": 8189, "text": "Refer to the below article to get detailed information about comparing dates." }, { "code": null, "e": 8293, "s": 8267, "text": "Comparing dates in Python" }, { "code": null, "e": 8674, "s": 8293, "text": "The datetime.now() does not have any information about the time zones. It just uses the current system time. In some situations, the time zone details may be needed. In such cases the tzinfo abstract class is used. tzinfo is an abstract base class. It cannot be instantiated directly. A concrete subclass has to derive it and implement the methods provided by this abstract class." }, { "code": null, "e": 8925, "s": 8674, "text": "A datetime object which does not contain any information on time zone is said to be a naive datetime object. For a naive datetime object, datetime_object.tzinfo will be None. An Aware datetime object contains the time zone information embedded in it." }, { "code": null, "e": 8993, "s": 8925, "text": "The methods available for implementation in tzinfo base class are :" }, { "code": null, "e": 9324, "s": 8993, "text": "utcoffset(): It returns the offset of the datetime instance passed as an argument. It refers to the time zone offset which denotes how many hours the time zone is ahead of the Coordinated Universal Time or Universal Time Coordinate (UTC). The offset is written as +00:00. For example: for Asia/Taipei, it is written as UTC +08:00." }, { "code": null, "e": 9574, "s": 9324, "text": "dst(): It is abbreviated as Day-light Saving Time. It denotes advancing the clock 1 hour in the summertime so that darkness falls later according to the clock. It is set to on or off. It is checked based on a tuple containing 9 elements as follows :" }, { "code": null, "e": 9653, "s": 9574, "text": "(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, 0)" }, { "code": null, "e": 9769, "s": 9653, "text": "tzname(): This is used to find the time zone name of the datetime object passed. It returns a Python String object." }, { "code": null, "e": 10104, "s": 9769, "text": "fromutc(): This function takes up the date and time of the object in UTC and returns the equivalent local time. It is used mostly for adjusting the date and time. It is called from default datetime.astimezone() implementation. The dt.tzinfo will be passed as self, dt’s date and time data will be returned as an equivalent local time." }, { "code": null, "e": 10113, "s": 10104, "text": "Example:" }, { "code": null, "e": 10121, "s": 10113, "text": "Python3" }, { "code": "import datetime as dt from dateutil import tz tz_string = dt.datetime.now(dt.timezone.utc).astimezone().tzname() print(\"datetime.now() :\", tz_string) NYC = tz.gettz('Europe / Berlin') dt1 = dt.datetime(2015, 5, 21, 12, 0) dt2 = dt.datetime(2015, 12, 21, 12, 0, tzinfo = NYC) print(\"Naive Object :\", dt1.tzname()) print(\"Aware Object :\", dt2.tzname())", "e": 10482, "s": 10121, "text": null }, { "code": null, "e": 10490, "s": 10482, "text": "Output:" }, { "code": null, "e": 10550, "s": 10490, "text": "datetime.now() : UTC\nNaive Object : None\nAware Object : CET" }, { "code": null, "e": 10643, "s": 10550, "text": "We can also use pytz module to deal with cross-timezones conversion. Let’s see how it works." }, { "code": null, "e": 10842, "s": 10643, "text": "Pytz brings the Olson tz database into Python and thus supports almost all time zones. This module serves the date-time conversion functionalities and helps user serving international client’s base." }, { "code": null, "e": 10924, "s": 10842, "text": "By using astimezone() function we can convert the time into a different timezone." }, { "code": null, "e": 10932, "s": 10924, "text": "Syntax:" }, { "code": null, "e": 10946, "s": 10932, "text": "astimezone(t)" }, { "code": null, "e": 10955, "s": 10946, "text": "Example:" }, { "code": null, "e": 10963, "s": 10955, "text": "Python3" }, { "code": "from datetime import datetime from pytz import timezone format = \"%Y-%m-%d %H:%M:%S %Z%z\" # Current time in UTC now_utc = datetime.now(timezone('UTC')) print(now_utc.strftime(format)) # Convert to Asia/Kolkata time zone now_asia = now_utc.astimezone(timezone('Asia/Kolkata')) print(now_asia.strftime(format))", "e": 11277, "s": 10963, "text": null }, { "code": null, "e": 11285, "s": 11277, "text": "Output:" }, { "code": null, "e": 11343, "s": 11285, "text": "2021-03-17 07:41:19 UTC+0000\n2021-03-17 13:11:19 IST+0530" }, { "code": null, "e": 11429, "s": 11343, "text": "Refer to the below articles to get detailed information about working with timezones." }, { "code": null, "e": 11456, "s": 11429, "text": "Python – datetime.tzinfo()" }, { "code": null, "e": 11485, "s": 11456, "text": "Python | Timezone Conversion" }, { "code": null, "e": 11497, "s": 11485, "text": "Python pytz" }, { "code": null, "e": 11513, "s": 11497, "text": "Python-datetime" }, { "code": null, "e": 11520, "s": 11513, "text": "Python" }, { "code": null, "e": 11618, "s": 11520, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11650, "s": 11618, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 11677, "s": 11650, "text": "Python Classes and Objects" }, { "code": null, "e": 11698, "s": 11677, "text": "Python OOPs Concepts" }, { "code": null, "e": 11721, "s": 11698, "text": "Introduction To PYTHON" }, { "code": null, "e": 11752, "s": 11721, "text": "Python | os.path.join() method" }, { "code": null, "e": 11808, "s": 11752, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 11850, "s": 11808, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 11892, "s": 11850, "text": "Check if element exists in list in Python" }, { "code": null, "e": 11931, "s": 11892, "text": "Python | Get unique values from a list" } ]
Python – 68-95-99.7 rule in Statistics
01 Sep, 2021 The Empirical Rule(also called the 68-95-99.7 Rule or the Three Sigma Rule) states that for any normal distribution, we have the following observations : 68% of the observed values lie between 1 standard deviation around the mean : 95% of the observed values lie between 2 standard deviations around the mean : 99.7% of the observed values lie between 3 standard deviation around the mean : Below is a standard normal distribution graph with (mean = 0 and standard deviation = 1), illustrating the Empirical Rule. We, can verify this using functions provided by Python’s SciPy module. We can use the cdf() function of the scipy.stats.norm module to calculate the cumulative probability(area under a distribution curve). Syntax : cdf(x, mean, SD)Parameters : x : value up to which cumulative probability is to be calculated mean : mean of the distribution SD : standard deviation of the distribution Below is the implementation : import matplotlib.pyplot as pltimport numpy as npfrom scipy.stats import norm # setting the values of# mean and S.D.mean = 0SD = 1 # value of cdf between one, two# and three S.D. around the meanone_sd = norm.cdf(SD, mean, SD) - norm.cdf(-SD, mean, SD)two_sd = norm.cdf(2 * SD, mean, SD) - norm.cdf(-2 * SD, mean, SD)three_sd = norm.cdf(3 * SD, mean, SD) - norm.cdf(-3 * SD, mean, SD) # printing the value of fractions# within each bandprint("Fraction of values within one SD =", one_sd)print("Fraction of values within two SD =", two_sd)print("Fraction of values within three SD =", three_sd) Output : Fraction of values within one SD = 0.6826894921370859 Fraction of values within two SD = 0.9544997361036416 Fraction of values within three SD = 0.9973002039367398 Hence, we see that the fraction of values are almost equal to 0.65, 0.95 and 0.997. Thus, the empirical Rule is verified. surinderdawra388 data-science Probability Python Probability Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Sep, 2021" }, { "code": null, "e": 182, "s": 28, "text": "The Empirical Rule(also called the 68-95-99.7 Rule or the Three Sigma Rule) states that for any normal distribution, we have the following observations :" }, { "code": null, "e": 261, "s": 182, "text": "68% of the observed values lie between 1 standard deviation around the mean : " }, { "code": null, "e": 341, "s": 261, "text": "95% of the observed values lie between 2 standard deviations around the mean : " }, { "code": null, "e": 422, "s": 341, "text": "99.7% of the observed values lie between 3 standard deviation around the mean : " }, { "code": null, "e": 545, "s": 422, "text": "Below is a standard normal distribution graph with (mean = 0 and standard deviation = 1), illustrating the Empirical Rule." }, { "code": null, "e": 616, "s": 545, "text": "We, can verify this using functions provided by Python’s SciPy module." }, { "code": null, "e": 751, "s": 616, "text": "We can use the cdf() function of the scipy.stats.norm module to calculate the cumulative probability(area under a distribution curve)." }, { "code": null, "e": 789, "s": 751, "text": "Syntax : cdf(x, mean, SD)Parameters :" }, { "code": null, "e": 854, "s": 789, "text": "x : value up to which cumulative probability is to be calculated" }, { "code": null, "e": 886, "s": 854, "text": "mean : mean of the distribution" }, { "code": null, "e": 930, "s": 886, "text": "SD : standard deviation of the distribution" }, { "code": null, "e": 960, "s": 930, "text": "Below is the implementation :" }, { "code": "import matplotlib.pyplot as pltimport numpy as npfrom scipy.stats import norm # setting the values of# mean and S.D.mean = 0SD = 1 # value of cdf between one, two# and three S.D. around the meanone_sd = norm.cdf(SD, mean, SD) - norm.cdf(-SD, mean, SD)two_sd = norm.cdf(2 * SD, mean, SD) - norm.cdf(-2 * SD, mean, SD)three_sd = norm.cdf(3 * SD, mean, SD) - norm.cdf(-3 * SD, mean, SD) # printing the value of fractions# within each bandprint(\"Fraction of values within one SD =\", one_sd)print(\"Fraction of values within two SD =\", two_sd)print(\"Fraction of values within three SD =\", three_sd)", "e": 1553, "s": 960, "text": null }, { "code": null, "e": 1562, "s": 1553, "text": "Output :" }, { "code": null, "e": 1727, "s": 1562, "text": "Fraction of values within one SD = 0.6826894921370859\nFraction of values within two SD = 0.9544997361036416\nFraction of values within three SD = 0.9973002039367398\n" }, { "code": null, "e": 1849, "s": 1727, "text": "Hence, we see that the fraction of values are almost equal to 0.65, 0.95 and 0.997. Thus, the empirical Rule is verified." }, { "code": null, "e": 1866, "s": 1849, "text": "surinderdawra388" }, { "code": null, "e": 1879, "s": 1866, "text": "data-science" }, { "code": null, "e": 1891, "s": 1879, "text": "Probability" }, { "code": null, "e": 1898, "s": 1891, "text": "Python" }, { "code": null, "e": 1910, "s": 1898, "text": "Probability" } ]
Python | Pandas Index.duplicated()
16 Dec, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.duplicated() function Indicate duplicate index values. Duplicated values are indicated as True values in the resulting array. Either all duplicates, all except the first, or all except the last occurrence of duplicates can be indicated. Syntax: Index.duplicated(keep=’first’) Parameters :keep : {‘first’, ‘last’, False}, default ‘first’The value or values in a set of duplicates to mark as missing.-> ‘first’ : Mark duplicates as True except for the first occurrence.-> ‘last’ : Mark duplicates as True except for the last occurrence.-> False : Mark all duplicates as True. Returns : numpy.ndarray Example #1: Use Index.duplicated() function to indicate all the duplicated value in the Index except the first one. # importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['Labrador', 'Beagle', 'Labrador', 'Lhasa', 'Husky', 'Beagle']) # Print the Indexidx Output : Let’s find if a value present in Index is a duplicate value or unique. # Identify the duplicated values except the firstidx.duplicated(keep ='first') Output :As we can see in the output, the Index.duplicated() function has marked all the occurrence of duplicate value as True except the first occurrence. Example #2: Use Index.duplicated() function to identify all the duplicate values. here all the duplicate values will be marked as True # importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index([100, 50, 45, 100, 12, 50, None]) # Print the Indexidx Output : Let’s identify all the duplicated values in the Index. Note : We are having NaN values in the Index. # Identify all duplicated occurrence of valuesidx.duplicated(keep = False) Output : The function has marked all the duplicate value as True. It has also treated the single occurrence of NaN value as unique and has marked it false. Python pandas-indexing Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Dec, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 492, "s": 242, "text": "Pandas Index.duplicated() function Indicate duplicate index values. Duplicated values are indicated as True values in the resulting array. Either all duplicates, all except the first, or all except the last occurrence of duplicates can be indicated." }, { "code": null, "e": 531, "s": 492, "text": "Syntax: Index.duplicated(keep=’first’)" }, { "code": null, "e": 829, "s": 531, "text": "Parameters :keep : {‘first’, ‘last’, False}, default ‘first’The value or values in a set of duplicates to mark as missing.-> ‘first’ : Mark duplicates as True except for the first occurrence.-> ‘last’ : Mark duplicates as True except for the last occurrence.-> False : Mark all duplicates as True." }, { "code": null, "e": 853, "s": 829, "text": "Returns : numpy.ndarray" }, { "code": null, "e": 969, "s": 853, "text": "Example #1: Use Index.duplicated() function to indicate all the duplicated value in the Index except the first one." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['Labrador', 'Beagle', 'Labrador', 'Lhasa', 'Husky', 'Beagle']) # Print the Indexidx", "e": 1157, "s": 969, "text": null }, { "code": null, "e": 1166, "s": 1157, "text": "Output :" }, { "code": null, "e": 1237, "s": 1166, "text": "Let’s find if a value present in Index is a duplicate value or unique." }, { "code": "# Identify the duplicated values except the firstidx.duplicated(keep ='first')", "e": 1316, "s": 1237, "text": null }, { "code": null, "e": 1606, "s": 1316, "text": "Output :As we can see in the output, the Index.duplicated() function has marked all the occurrence of duplicate value as True except the first occurrence. Example #2: Use Index.duplicated() function to identify all the duplicate values. here all the duplicate values will be marked as True" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index([100, 50, 45, 100, 12, 50, None]) # Print the Indexidx", "e": 1742, "s": 1606, "text": null }, { "code": null, "e": 1751, "s": 1742, "text": "Output :" }, { "code": null, "e": 1806, "s": 1751, "text": "Let’s identify all the duplicated values in the Index." }, { "code": null, "e": 1852, "s": 1806, "text": "Note : We are having NaN values in the Index." }, { "code": "# Identify all duplicated occurrence of valuesidx.duplicated(keep = False)", "e": 1927, "s": 1852, "text": null }, { "code": null, "e": 1936, "s": 1927, "text": "Output :" }, { "code": null, "e": 2083, "s": 1936, "text": "The function has marked all the duplicate value as True. It has also treated the single occurrence of NaN value as unique and has marked it false." }, { "code": null, "e": 2106, "s": 2083, "text": "Python pandas-indexing" }, { "code": null, "e": 2120, "s": 2106, "text": "Python-pandas" }, { "code": null, "e": 2127, "s": 2120, "text": "Python" } ]
Structure vs class in C++
23 Jun, 2022 In C++, a structure works the same way as a class, except for just two small differences. The most important of them is hiding implementation details. A structure will by default not hide its implementation details from whomever uses it in code, while a class by default hides all its implementation details and will therefore by default prevent the programmer from accessing them. The following table summarizes all of the fundamental differences. Class Structure Some examples that elaborate on these differences: 1) Members of a class are private by default and members of a structure are public by default. For example, program 1 fails in compilation but program 2 works fine, Program 1: C++ // Program 1// C++ Program to demonstrate that// Members of a class are private// by defaultusing namespace std; class Test { // x is private int x;}; int main(){ Test t; t.x = 20; // compiler error because x // is private return t.x;} Output: prog.cpp: In function ‘int main()’: prog.cpp:8:9: error: ‘int Test::x’ is private int x; ^ prog.cpp:13:7: error: within this context t.x = 20; ^ Program 2: C++ // Program 2// C++ Program to demonstrate that// members of a structure are public// by default.#include <iostream> struct Test { // x is public int x;}; int main(){ Test t; t.x = 20; // works fine because x is public std::cout << t.x;} 20 2) A class is declared using the class keyword, and a structure is declared using the struct keyword. Syntax: class ClassName { private: member1; member2; public: member3; . . memberN; }; Syntax: struct StructureName { member1; member2; . . . memberN; }; 3) Inheritance is possible with classes, and with structures. For example, programs 3 and 4 work fine. Program 3: C++ // Program 3// C++ program to demonstrate// inheritance with classes.#include <iostream>using namespace std; // Base classclass Parent {public: int x;}; // Subclass inheriting from// base class (Parent).class Child : public Parent {public: int y;}; int main(){ Child obj1; // An object of class Child has // all data members and member // functions of class Parent. obj1.y = 7; obj1.x = 91; cout << obj1.y << endl; cout << obj1.x << endl; return 0;} 7 91 Program 4: C++ // Program 4// C++ program to demonstrate// inheritance with structures.#include <iostream>using namespace std; struct Base {public: int x;}; // is equivalent to// struct Derived : public Base {}struct Derived : Base {public: int y;}; int main(){ Derived d; // Works fine because inheritance // is public. d.x = 20; cout << d.x; cin.get(); return 0;} Output 20 Must Read: Difference between C structures and C++ structuresPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. roopkatha ruchirharbhajanka sidhijain ravi14577 clintra 1805325 minimoyse anshikajain26 lysenkoartem508 plerenius hannesharnisch mayank007rawa joydeephalder C++ Difference Between CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set in C++ Standard Template Library (STL) Priority Queue in C++ Standard Template Library (STL) vector erase() and clear() in C++ Substring in C++ unordered_map in C++ STL Class method vs Static method in Python Difference between BFS and DFS Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 501, "s": 52, "text": "In C++, a structure works the same way as a class, except for just two small differences. The most important of them is hiding implementation details. A structure will by default not hide its implementation details from whomever uses it in code, while a class by default hides all its implementation details and will therefore by default prevent the programmer from accessing them. The following table summarizes all of the fundamental differences." }, { "code": null, "e": 507, "s": 501, "text": "Class" }, { "code": null, "e": 517, "s": 507, "text": "Structure" }, { "code": null, "e": 568, "s": 517, "text": "Some examples that elaborate on these differences:" }, { "code": null, "e": 664, "s": 568, "text": "1) Members of a class are private by default and members of a structure are public by default. " }, { "code": null, "e": 735, "s": 664, "text": "For example, program 1 fails in compilation but program 2 works fine, " }, { "code": null, "e": 746, "s": 735, "text": "Program 1:" }, { "code": null, "e": 750, "s": 746, "text": "C++" }, { "code": "// Program 1// C++ Program to demonstrate that// Members of a class are private// by defaultusing namespace std; class Test { // x is private int x;}; int main(){ Test t; t.x = 20; // compiler error because x // is private return t.x;}", "e": 1017, "s": 750, "text": null }, { "code": null, "e": 1027, "s": 1017, "text": " Output:" }, { "code": null, "e": 1194, "s": 1027, "text": "prog.cpp: In function ‘int main()’:\nprog.cpp:8:9: error: ‘int Test::x’ is private\n int x;\n ^\nprog.cpp:13:7: error: within this context\n t.x = 20;\n ^" }, { "code": null, "e": 1206, "s": 1194, "text": "Program 2: " }, { "code": null, "e": 1210, "s": 1206, "text": "C++" }, { "code": "// Program 2// C++ Program to demonstrate that// members of a structure are public// by default.#include <iostream> struct Test { // x is public int x;}; int main(){ Test t; t.x = 20; // works fine because x is public std::cout << t.x;}", "e": 1468, "s": 1210, "text": null }, { "code": null, "e": 1471, "s": 1468, "text": "20" }, { "code": null, "e": 1573, "s": 1471, "text": "2) A class is declared using the class keyword, and a structure is declared using the struct keyword." }, { "code": null, "e": 1582, "s": 1573, "text": "Syntax: " }, { "code": null, "e": 1685, "s": 1582, "text": "class ClassName {\nprivate:\n member1;\n member2;\n\npublic:\n member3;\n .\n .\n memberN;\n};" }, { "code": null, "e": 1694, "s": 1685, "text": "Syntax: " }, { "code": null, "e": 1777, "s": 1694, "text": "struct StructureName {\n member1;\n member2;\n .\n .\n .\n memberN;\n};" }, { "code": null, "e": 1839, "s": 1777, "text": "3) Inheritance is possible with classes, and with structures." }, { "code": null, "e": 1880, "s": 1839, "text": "For example, programs 3 and 4 work fine." }, { "code": null, "e": 1891, "s": 1880, "text": "Program 3:" }, { "code": null, "e": 1895, "s": 1891, "text": "C++" }, { "code": "// Program 3// C++ program to demonstrate// inheritance with classes.#include <iostream>using namespace std; // Base classclass Parent {public: int x;}; // Subclass inheriting from// base class (Parent).class Child : public Parent {public: int y;}; int main(){ Child obj1; // An object of class Child has // all data members and member // functions of class Parent. obj1.y = 7; obj1.x = 91; cout << obj1.y << endl; cout << obj1.x << endl; return 0;}", "e": 2382, "s": 1895, "text": null }, { "code": null, "e": 2387, "s": 2382, "text": "7\n91" }, { "code": null, "e": 2398, "s": 2387, "text": "Program 4:" }, { "code": null, "e": 2402, "s": 2398, "text": "C++" }, { "code": "// Program 4// C++ program to demonstrate// inheritance with structures.#include <iostream>using namespace std; struct Base {public: int x;}; // is equivalent to// struct Derived : public Base {}struct Derived : Base {public: int y;}; int main(){ Derived d; // Works fine because inheritance // is public. d.x = 20; cout << d.x; cin.get(); return 0;}", "e": 2783, "s": 2402, "text": null }, { "code": null, "e": 2791, "s": 2783, "text": " Output" }, { "code": null, "e": 2794, "s": 2791, "text": "20" }, { "code": null, "e": 2981, "s": 2794, "text": "Must Read: Difference between C structures and C++ structuresPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 2991, "s": 2981, "text": "roopkatha" }, { "code": null, "e": 3009, "s": 2991, "text": "ruchirharbhajanka" }, { "code": null, "e": 3019, "s": 3009, "text": "sidhijain" }, { "code": null, "e": 3029, "s": 3019, "text": "ravi14577" }, { "code": null, "e": 3037, "s": 3029, "text": "clintra" }, { "code": null, "e": 3045, "s": 3037, "text": "1805325" }, { "code": null, "e": 3055, "s": 3045, "text": "minimoyse" }, { "code": null, "e": 3069, "s": 3055, "text": "anshikajain26" }, { "code": null, "e": 3085, "s": 3069, "text": "lysenkoartem508" }, { "code": null, "e": 3095, "s": 3085, "text": "plerenius" }, { "code": null, "e": 3110, "s": 3095, "text": "hannesharnisch" }, { "code": null, "e": 3124, "s": 3110, "text": "mayank007rawa" }, { "code": null, "e": 3138, "s": 3124, "text": "joydeephalder" }, { "code": null, "e": 3142, "s": 3138, "text": "C++" }, { "code": null, "e": 3161, "s": 3142, "text": "Difference Between" }, { "code": null, "e": 3165, "s": 3161, "text": "CPP" }, { "code": null, "e": 3263, "s": 3165, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3306, "s": 3263, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 3360, "s": 3306, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 3394, "s": 3360, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 3411, "s": 3394, "text": "Substring in C++" }, { "code": null, "e": 3436, "s": 3411, "text": "unordered_map in C++ STL" }, { "code": null, "e": 3476, "s": 3436, "text": "Class method vs Static method in Python" }, { "code": null, "e": 3507, "s": 3476, "text": "Difference between BFS and DFS" }, { "code": null, "e": 3568, "s": 3507, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3636, "s": 3568, "text": "Difference Between Method Overloading and Method Overriding in Java" } ]
numpy.count() in Python
10 Oct, 2019 numpy.core.defchararray.count(arr, substring, start=0, end=None): Counts for the non-overlapping occurrence of sub-string in the specified range. Parameters:arr : array-like or string to be searched.substring : substring to search for.start, end : [int, optional] Range to search in. Returns : An integer array with the number of non-overlapping occurrences of sub-string. Code #1: # Python Program illustrating # numpy.char.count() method import numpy as np # 2D array arr = ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz'] print ("arr : ", arr) print ("Count of 'tt'", np.char.count(arr, 'tt'))print ("Count of 'tt'", np.char.count(arr, 'tt', start = 0))print ("Count of 'tt'", np.char.count(arr, 'tt', start = 8)) Output: arr : ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz'] Count of 'tt' [2 2 1 0] Count of 'tt' [2 2 1 0] Count of 'tt' [1 2 1 0] Code #2: # Python Program illustrating # numpy.char.count() method import numpy as np # 2D array arr = ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz'] print ("arr : ", arr) print ("Count of 'Aa'", np.char.count(arr, 'Aa'))print ("Count of 'Aa'", np.char.count(arr, 'Aa', start = 8)) Output: arr : ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz'] Count of 'Aa' [1 1 1 1] Count of 'Aa' [1 0 0 0] Akanksha_Rai Python numpy-String Operation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python 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": "\n10 Oct, 2019" }, { "code": null, "e": 174, "s": 28, "text": "numpy.core.defchararray.count(arr, substring, start=0, end=None): Counts for the non-overlapping occurrence of sub-string in the specified range." }, { "code": null, "e": 312, "s": 174, "text": "Parameters:arr : array-like or string to be searched.substring : substring to search for.start, end : [int, optional] Range to search in." }, { "code": null, "e": 401, "s": 312, "text": "Returns : An integer array with the number of non-overlapping occurrences of sub-string." }, { "code": null, "e": 410, "s": 401, "text": "Code #1:" }, { "code": "# Python Program illustrating # numpy.char.count() method import numpy as np # 2D array arr = ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz'] print (\"arr : \", arr) print (\"Count of 'tt'\", np.char.count(arr, 'tt'))print (\"Count of 'tt'\", np.char.count(arr, 'tt', start = 0))print (\"Count of 'tt'\", np.char.count(arr, 'tt', start = 8))", "e": 773, "s": 410, "text": null }, { "code": null, "e": 781, "s": 773, "text": "Output:" }, { "code": null, "e": 932, "s": 781, "text": "arr : ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz']\nCount of 'tt' [2 2 1 0]\nCount of 'tt' [2 2 1 0]\nCount of 'tt' [1 2 1 0]\n" }, { "code": null, "e": 942, "s": 932, "text": " Code #2:" }, { "code": "# Python Program illustrating # numpy.char.count() method import numpy as np # 2D array arr = ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz'] print (\"arr : \", arr) print (\"Count of 'Aa'\", np.char.count(arr, 'Aa'))print (\"Count of 'Aa'\", np.char.count(arr, 'Aa', start = 8))", "e": 1243, "s": 942, "text": null }, { "code": null, "e": 1251, "s": 1243, "text": "Output:" }, { "code": null, "e": 1379, "s": 1251, "text": "arr : ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz']\n\nCount of 'Aa' [1 1 1 1]\nCount of 'Aa' [1 0 0 0]\n" }, { "code": null, "e": 1392, "s": 1379, "text": "Akanksha_Rai" }, { "code": null, "e": 1422, "s": 1392, "text": "Python numpy-String Operation" }, { "code": null, "e": 1435, "s": 1422, "text": "Python-numpy" }, { "code": null, "e": 1442, "s": 1435, "text": "Python" }, { "code": null, "e": 1540, "s": 1442, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1558, "s": 1540, "text": "Python Dictionary" }, { "code": null, "e": 1600, "s": 1558, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1622, "s": 1600, "text": "Enumerate() in Python" }, { "code": null, "e": 1657, "s": 1622, "text": "Read a file line by line in Python" }, { "code": null, "e": 1683, "s": 1657, "text": "Python String | replace()" }, { "code": null, "e": 1715, "s": 1683, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1744, "s": 1715, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1774, "s": 1744, "text": "Iterate over a list in Python" }, { "code": null, "e": 1801, "s": 1774, "text": "Python Classes and Objects" } ]
Flask - Jinja Templates Example - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws Flask templates can do much more than replacing the placeholders that we have done in the previous tutorial, In this tutorial, we are going to see the most powerful features of the Flask template engine. The template engine used by Flask is a very powerful package that jinja that’s being installed as part of the Flask installation. A Jinja template can contain variables or expressions ideally these are placeholders expressed with {{}} which will get replaced with the actual dynamic values when it renders the page on the browser. Jinja supports different kinds of constructs for example conditional, looping, mathematical and etc. Let’s see some useful constructs. Python 3.8.5 Flask 2.0.1 Mac OS X (venv) flask-jinja-templates % . ├── app │ ├── __init__.py │ ├── routes.py │ └── templates │ └── index.html └── jinja-templates.py <html> <head> <title>Hello, World!</title> </head> <body> <h1 style="color:#093657"> Hello, {% if user %} {{user.name}} {% else %} Buddy! {% endif %} </h1> </body> </html> On the above code, I created a conditional User name that will provide an alternative user name Buddy when user not provided in the render template call. If you observe these conditional constructs are very similar to how we work with if statements in python. create routes.py from app import app from flask import render_template @app.route('/') def index(): user = { 'name':'Chandra' } return render_template('index.html') In the routes.py above, I am not passing the user object to render_template() function to see alternative user name in the browser. Output: Now let’s pass the user object and see the output. from app import app from flask import render_template @app.route('/') def index(): user = { 'name':'Chandra' } return render_template('index.html', user=user) Output: Continuing with conditional constructs now we are going to look at loops in jinja language. The loops are a very useful feature that allows us to work with a list of elements. routes.py from app import app from flask import render_template @app.route('/') def index(): user_info = { 'name':'Chandra', 'hobbies':['Blogging','Reading Books','Playing chess'], 'interested_books':{ 'Java':['Thinking in Java','Inside the Java virtual machine'], 'Python':['Fluent Python'] } } return render_template('index.html', user=user_info) on the above, I have created a little complicated user data that containing strings, a list of strings and a dict inside another dict. Let’s see how we can use jinja is being used to populate this data. <html> <head> <title>Hello, World!</title> </head> <body> <h1 style="color:#093657"> Hello, {% if user %} {{user.name}} {% else %} Buddy! {% endif %} </h1> Hobbies: <div> <p><ul> {% for hobby in user.hobbies %} <li>{{hobby}}</li> {% endfor %} </ul></p> </div> Interested Books: <div> <p><ul> {% for key in user.interested_books %} {{key}} <ul> {% for book in user.interested_books.get(key)%} <li>{{book}}</li> {% endfor %} </ul> {% endfor %} </ul></p> </div> </body> </html> The jinja for loops are very similar to how we use the for loops in python, that difference is that all structures are enclosed in {% %} this is what the jinja used to detect these control structures. The {{}} is used for placeholder variables. Output: Inside the code blocks, we are always allowed to assign variables using a set like below. {% set country = 'India' %} <p>I am from - {{country}}</p> In jinja variables can be modified by filters, for example changing the cases and finding the length of any collection. {% set hobbies = user.hobbies %} {{ 'Hobbies length: ' ~ hobbies | count }}</br> {% set name = user.name | upper %} Name in upper - {{ name}} Output: So we have a lot of support from jinja to prepare the templates you can go through the jinja official documentation for more details. Jinja templates Flask HTML Templates Happy Learning 🙂 Flask Simple HTML Templates Example Hello World Flask Example Python – How to install the Flask framework? Rendering Static HTML page using Django AngularJs Directive Example Tutorials Angularjs Services Example Tutorials Angularjs Custom Filter Example How to push docker image to docker hub ? Python Django Helloworld Example How to access for loop index in Python C How to Pass Arrays to Functions Using Array in AngularJs Example Python – AWS SAM Lambda Example Step by Step Tutorials AngularJs Example Python Tuple Data Structure in Depth Flask Simple HTML Templates Example Hello World Flask Example Python – How to install the Flask framework? Rendering Static HTML page using Django AngularJs Directive Example Tutorials Angularjs Services Example Tutorials Angularjs Custom Filter Example How to push docker image to docker hub ? Python Django Helloworld Example How to access for loop index in Python C How to Pass Arrays to Functions Using Array in AngularJs Example Python – AWS SAM Lambda Example Step by Step Tutorials AngularJs Example Python Tuple Data Structure in Depth
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 602, "s": 398, "text": "Flask templates can do much more than replacing the placeholders that we have done in the previous tutorial, In this tutorial, we are going to see the most powerful features of the Flask template engine." }, { "code": null, "e": 732, "s": 602, "text": "The template engine used by Flask is a very powerful package that jinja that’s being installed as part of the Flask installation." }, { "code": null, "e": 933, "s": 732, "text": "A Jinja template can contain variables or expressions ideally these are placeholders expressed with {{}} which will get replaced with the actual dynamic values when it renders the page on the browser." }, { "code": null, "e": 1068, "s": 933, "text": "Jinja supports different kinds of constructs for example conditional, looping, mathematical and etc. Let’s see some useful constructs." }, { "code": null, "e": 1081, "s": 1068, "text": "Python 3.8.5" }, { "code": null, "e": 1093, "s": 1081, "text": "Flask 2.0.1" }, { "code": null, "e": 1102, "s": 1093, "text": "Mac OS X" }, { "code": null, "e": 1246, "s": 1102, "text": "(venv) flask-jinja-templates % \n.\n├── app\n│ ├── __init__.py\n│ ├── routes.py\n│ └── templates\n│ └── index.html\n└── jinja-templates.py" }, { "code": null, "e": 1526, "s": 1246, "text": "<html>\n <head>\n <title>Hello, World!</title>\n </head>\n <body>\n <h1 style=\"color:#093657\"> Hello,\n {% if user %}\n {{user.name}}\n {% else %}\n Buddy!\n {% endif %}\n </h1>\n </body>\n</html>" }, { "code": null, "e": 1680, "s": 1526, "text": "On the above code, I created a conditional User name that will provide an alternative user name Buddy when user not provided in the render template call." }, { "code": null, "e": 1786, "s": 1680, "text": "If you observe these conditional constructs are very similar to how we work with if statements in python." }, { "code": null, "e": 1803, "s": 1786, "text": "create routes.py" }, { "code": null, "e": 1973, "s": 1803, "text": "from app import app\nfrom flask import render_template\n\n@app.route('/')\ndef index():\n user = {\n 'name':'Chandra'\n }\n return render_template('index.html')\n" }, { "code": null, "e": 2105, "s": 1973, "text": "In the routes.py above, I am not passing the user object to render_template() function to see alternative user name in the browser." }, { "code": null, "e": 2113, "s": 2105, "text": "Output:" }, { "code": null, "e": 2164, "s": 2113, "text": "Now let’s pass the user object and see the output." }, { "code": null, "e": 2345, "s": 2164, "text": "from app import app\nfrom flask import render_template\n\n@app.route('/')\ndef index():\n user = {\n 'name':'Chandra'\n }\n return render_template('index.html', user=user)\n" }, { "code": null, "e": 2353, "s": 2345, "text": "Output:" }, { "code": null, "e": 2445, "s": 2353, "text": "Continuing with conditional constructs now we are going to look at loops in jinja language." }, { "code": null, "e": 2529, "s": 2445, "text": "The loops are a very useful feature that allows us to work with a list of elements." }, { "code": null, "e": 2539, "s": 2529, "text": "routes.py" }, { "code": null, "e": 2948, "s": 2539, "text": "from app import app\nfrom flask import render_template\n\n@app.route('/')\ndef index():\n user_info = {\n 'name':'Chandra',\n 'hobbies':['Blogging','Reading Books','Playing chess'],\n 'interested_books':{\n 'Java':['Thinking in Java','Inside the Java virtual machine'],\n 'Python':['Fluent Python']\n }\n }\n return render_template('index.html', user=user_info)\n" }, { "code": null, "e": 3152, "s": 2948, "text": "on the above, I have created a little complicated user data that containing strings, a list of strings and a dict inside another dict. Let’s see how we can use jinja is being used to populate this data." }, { "code": null, "e": 4033, "s": 3152, "text": "<html>\n <head>\n <title>Hello, World!</title>\n </head>\n <body>\n <h1 style=\"color:#093657\"> Hello,\n {% if user %}\n {{user.name}}\n {% else %}\n Buddy!\n {% endif %}\n </h1>\n Hobbies:\n <div>\n <p><ul>\n {% for hobby in user.hobbies %}\n <li>{{hobby}}</li>\n {% endfor %}\n </ul></p>\n </div>\n Interested Books:\n <div>\n <p><ul>\n {% for key in user.interested_books %}\n {{key}}\n <ul>\n {% for book in user.interested_books.get(key)%}\n <li>{{book}}</li>\n {% endfor %}\n </ul>\n {% endfor %}\n </ul></p>\n </div>\n </body>\n</html>" }, { "code": null, "e": 4234, "s": 4033, "text": "The jinja for loops are very similar to how we use the for loops in python, that difference is that all structures are enclosed in {% %} this is what the jinja used to detect these control structures." }, { "code": null, "e": 4278, "s": 4234, "text": "The {{}} is used for placeholder variables." }, { "code": null, "e": 4286, "s": 4278, "text": "Output:" }, { "code": null, "e": 4376, "s": 4286, "text": "Inside the code blocks, we are always allowed to assign variables using a set like below." }, { "code": null, "e": 4435, "s": 4376, "text": "{% set country = 'India' %}\n<p>I am from - {{country}}</p>" }, { "code": null, "e": 4555, "s": 4435, "text": "In jinja variables can be modified by filters, for example changing the cases and finding the length of any collection." }, { "code": null, "e": 4701, "s": 4555, "text": "{% set hobbies = user.hobbies %}\n\n{{ 'Hobbies length: ' ~ hobbies | count }}</br>\n\n{% set name = user.name | upper %}\nName in upper - {{ name}}\n" }, { "code": null, "e": 4709, "s": 4701, "text": "Output:" }, { "code": null, "e": 4843, "s": 4709, "text": "So we have a lot of support from jinja to prepare the templates you can go through the jinja official documentation for more details." }, { "code": null, "e": 4859, "s": 4843, "text": "Jinja templates" }, { "code": null, "e": 4880, "s": 4859, "text": "Flask HTML Templates" }, { "code": null, "e": 4897, "s": 4880, "text": "Happy Learning 🙂" }, { "code": null, "e": 5443, "s": 4897, "text": "\nFlask Simple HTML Templates Example\nHello World Flask Example\nPython – How to install the Flask framework?\nRendering Static HTML page using Django\nAngularJs Directive Example Tutorials\nAngularjs Services Example Tutorials\nAngularjs Custom Filter Example\nHow to push docker image to docker hub ?\nPython Django Helloworld Example\nHow to access for loop index in Python\nC How to Pass Arrays to Functions\nUsing Array in AngularJs Example\nPython – AWS SAM Lambda Example\nStep by Step Tutorials AngularJs Example\nPython Tuple Data Structure in Depth\n" }, { "code": null, "e": 5479, "s": 5443, "text": "Flask Simple HTML Templates Example" }, { "code": null, "e": 5505, "s": 5479, "text": "Hello World Flask Example" }, { "code": null, "e": 5550, "s": 5505, "text": "Python – How to install the Flask framework?" }, { "code": null, "e": 5590, "s": 5550, "text": "Rendering Static HTML page using Django" }, { "code": null, "e": 5628, "s": 5590, "text": "AngularJs Directive Example Tutorials" }, { "code": null, "e": 5665, "s": 5628, "text": "Angularjs Services Example Tutorials" }, { "code": null, "e": 5697, "s": 5665, "text": "Angularjs Custom Filter Example" }, { "code": null, "e": 5738, "s": 5697, "text": "How to push docker image to docker hub ?" }, { "code": null, "e": 5771, "s": 5738, "text": "Python Django Helloworld Example" }, { "code": null, "e": 5810, "s": 5771, "text": "How to access for loop index in Python" }, { "code": null, "e": 5844, "s": 5810, "text": "C How to Pass Arrays to Functions" }, { "code": null, "e": 5877, "s": 5844, "text": "Using Array in AngularJs Example" }, { "code": null, "e": 5909, "s": 5877, "text": "Python – AWS SAM Lambda Example" }, { "code": null, "e": 5950, "s": 5909, "text": "Step by Step Tutorials AngularJs Example" } ]
Program to find uncommon elements in two arrays - JavaScript
Let’s say, we have two arrays of numbers − const arr1 = [12, 54, 2, 4, 6, 34, 3]; const arr2 = [54, 2, 5, 12, 4, 1, 3, 34]; We are required to write a JavaScript function that takes in two such arrays and returns the element from arrays that are not common to both. Let’s write the code for this function − Following is the code − const arr1 = [12, 54, 2, 4, 6, 34, 3]; const arr2 = [54, 2, 5, 12, 4, 1, 3, 34]; const unCommonArray = (first, second) => { const res = []; for(let i = 0; i < first.length; i++){ if(second.indexOf(first[i]) === -1){ res.push(first[i]); } }; for(let j = 0; j < second.length; j++){ if(first.indexOf(second[j]) === -1){ res.push(second[j]); }; }; return res; }; console.log(unCommonArray(arr1, arr2)); Following is the output in the console − [ 6, 5, 1 ]
[ { "code": null, "e": 1105, "s": 1062, "text": "Let’s say, we have two arrays of numbers −" }, { "code": null, "e": 1186, "s": 1105, "text": "const arr1 = [12, 54, 2, 4, 6, 34, 3];\nconst arr2 = [54, 2, 5, 12, 4, 1, 3, 34];" }, { "code": null, "e": 1328, "s": 1186, "text": "We are required to write a JavaScript function that takes in two such arrays and returns the element from arrays that are not common to both." }, { "code": null, "e": 1369, "s": 1328, "text": "Let’s write the code for this function −" }, { "code": null, "e": 1393, "s": 1369, "text": "Following is the code −" }, { "code": null, "e": 1853, "s": 1393, "text": "const arr1 = [12, 54, 2, 4, 6, 34, 3];\nconst arr2 = [54, 2, 5, 12, 4, 1, 3, 34];\nconst unCommonArray = (first, second) => {\n const res = [];\n for(let i = 0; i < first.length; i++){\n if(second.indexOf(first[i]) === -1){\n res.push(first[i]);\n }\n };\n for(let j = 0; j < second.length; j++){\n if(first.indexOf(second[j]) === -1){\n res.push(second[j]);\n };\n };\n return res;\n};\nconsole.log(unCommonArray(arr1, arr2));" }, { "code": null, "e": 1894, "s": 1853, "text": "Following is the output in the console −" }, { "code": null, "e": 1906, "s": 1894, "text": "[ 6, 5, 1 ]" } ]
Automatic data registration for Azure Machine Learning workspaces | by Iulia Feroli | Towards Data Science
Azure Machine Learning (AML) workspaces are a great platform in which data scientists and data engineers can collaborate and work on different projects. It brings together notebook coding environments, compute targets to power your code, datasets & datastores to keep references of your data sources, and a way to track your experiments. While most tasks around this workspace can be achieved through the User Interface or with the Cloud Shell / command line, once you scale out to a large number or workspaces or data sources it can become overwhelming to manage all your resources manually. Blog is a companion to github repo here. Create a way to automate the registration & management of the data in your AML workspace(s) (steps 1–4) Package useful scripts for these tasks in container(s) that can be triggered from one point of control (steps 5–6) Enable authorization & authentication measures to make sure the solution is “enterprise ready” (step 7) Reproducibility: same data (and versioning) for different projects / teams Scalability: Ease of managing different teams/projects: for example run Azure Data Factory pipelines to (simultaneously) populate new data in all your workspaces and subscriptions across your domain. Data tracing: Define RBAC and give access to trigger these tasks to only a few team members for increased security and traceability In the github repository project Python and the azureml-SDK Flask for adapting the python script to run as a web service In this Azure Tutorial blog Azure Data Lake as the source of your data Azure Machine Learning Workspaces as the place to register your data Azure Web service Azure Data Factory to trigger the HTTP requests to the web app For making this solution secure we will use Azure authorization and authentication concepts: Service Principal, Key Vault, Managed Identity, AAD. In this section we will go through the deployment of the necessary resources. See links for Azure documentation walkthroughs & more info. As many as you need, can be across different resource groups or regions For this tutorial I made one “basic” AML instance. Create a storage account and make sure to enable “hierarchical namespace” in the advanced settings to make it a Data Lake. I created one “main” container called silver (assuming data will come in here from whatever previous processes in your business generates data) I added folders with mock data: an accounting and sales container, each with one csv file we will need to register in our workspace later. The service principal (sp) is used to authenticate to AML in this automated scenario, as opposed to the user having to log in with Azure credentials at every run. 3.1. We will register a service principal as an app on your AAD (link) (link) Open the Azure Cloud Shell by clicking the >_ icon at the top right of your Azure Portal. Create the service principal by running this command with whatever name you want instead of sp-medium-demo: az ad sp create-for-rbac --sdk-auth --name sp-medium-demo Save the clientId, clientSecret, and tenantId fields you get in the json response for later (they will go into your key vault) 3.2 Give it the necessary permissions to your AML and Storage Account Go to your portal and open the Machine Learning and Storage Account resources, and prepare the name you gave your service principal to add to the “Role assignments” page. Make the service principal app Contributor to your AML workspace(s) Make the sp a Storage Blob Data Reader to your Storage account(s) Create a key vault in your resource group and create three secrets to store the credentials of the service principal you just created. (without quotes) The code you will clone later takes these credentials from the key vault to ensure automated & secure authentication /authorization. So to make it easy you can use the same names for your secrets, tenant-id sp-id and sp-password for the tenantId, clientId, andclientSecret values you got at step 3.1 Clone that repository in your IDE of choice. I’m going with Visual Studio Code (VSC) to make integration with Azure Web App easier. Clone github repository in VSC tutorial You can test that the code has been imported correctly in Visual Studio code by running it as a flask app as explained in the repo readme here. The only thing you need to fill in yourself in this code is the link to your newly created Key Vault (DNS name: yourname.vault.azure.net), and the names of the secrets if you changed them (see step 4), see instructions in the github Readme. To access the key vault you need to add Secret Reader permissions within the key vault Access Policies. You can do this for the place you’re running the code from now (for example a VM), but in this tutorial we give these permissions only to the web-app directly in the next step. Because of this the /send_data POST request should not work yet, which is a good thing for security Create a “Web Service” on Azure with Python for the Runtime Stack, and Linux for the OS. Go to the resource once deployed. Change the Startup Command for your App Service to match the name of your flask app and function with this: gunicorn --bind=0.0.0.0 --timeout 600 app_body:app (see picture left) Then save the configuration. Now you need to connect your code in Visual Studio to the app you created on the Azure Portal. Install the azure web service plug-in for VSC, then log in with your azure credentials as needed. Now you will have the Azure blade in VSC (1. in picture), and you can see the web app you created in the list under your subscription. Click the blue arrow that says deploy (2.) Fill in the ‘app’ folder from your cloned repo and the name of your newly deployed web all when the Command Pallet asks for it. Then click accept and you are now deploying the python flask app & dependencies to your new website. Go on the website once deployment is complete. It should say “Hello Iulia!” — change this message in app_body.py to whatever you want. 5.05 Give Web App access to the key vault For the other page of your web app, namely /send_data we need the Web App to read secrets from the key vault you set up in step 4. First the Web App needs to have an identity to grant authorization to. Enable this in the portal by going to your web app and to Identity Settings: Now go to your key vault in the portal, and check the Access Policies Setting. Click to add a new access policy and search for the name of your Web app (that you just created an identity for; it won’t show in the list before the previous step is saved) Use the Secret Management permission template, select your Web App name under Select Principal and save. Then save again for all changed to the access policy. Now your web app can send post requests to the /send_data tab and register your data using the credentials from the key vault. Deploy an Azure Data Factory, open the instance via Author & Monitor, and click on create pipeline. Now search for “Web” Activity and drag it into your pipeline area. This will be the only step in your pipeline. Fill in the name of your deployed web app, select POST request, and fill in the body of your request as the JSON input to the code you cloned. See how to create this JSON here. You can now debug or Trigger Now to run your function. When the pipeline has succeeded you can now check your AML workspaces. The datastores / datasets you sent via JSON should now be registered and available! At this point anyone can make calls to your web app which is not a robust and secure solution. While no data is being sent over the HTTP requests, nor does the app grant any insights into the application is works with; this is still not as robust and secure a solution as possible (and necessary for an enterprise solution) Desired state: ONLY your Azure Data Factory instance is authorized to make calls to your Web App, and thus register data to your workspaces. We do this by activating the managed identity of the data factory; so that authorizations can be given to it same as to a user And by setting up AAD authentication to the Web App, so a user (or app) must be logged in and their account must have the right authorization in order to make a call. This solution has already been designed by my colleague, René Bremer and he has a repository on github for it. Follow the steps there. You just have to adapt from Azure Function to Web App (same steps regardless). This is the security flow he designed: Hope you find this useful, either for the full solution or for separate parts of it you can use in different projects!
[ { "code": null, "e": 510, "s": 172, "text": "Azure Machine Learning (AML) workspaces are a great platform in which data scientists and data engineers can collaborate and work on different projects. It brings together notebook coding environments, compute targets to power your code, datasets & datastores to keep references of your data sources, and a way to track your experiments." }, { "code": null, "e": 765, "s": 510, "text": "While most tasks around this workspace can be achieved through the User Interface or with the Cloud Shell / command line, once you scale out to a large number or workspaces or data sources it can become overwhelming to manage all your resources manually." }, { "code": null, "e": 806, "s": 765, "text": "Blog is a companion to github repo here." }, { "code": null, "e": 910, "s": 806, "text": "Create a way to automate the registration & management of the data in your AML workspace(s) (steps 1–4)" }, { "code": null, "e": 1025, "s": 910, "text": "Package useful scripts for these tasks in container(s) that can be triggered from one point of control (steps 5–6)" }, { "code": null, "e": 1129, "s": 1025, "text": "Enable authorization & authentication measures to make sure the solution is “enterprise ready” (step 7)" }, { "code": null, "e": 1204, "s": 1129, "text": "Reproducibility: same data (and versioning) for different projects / teams" }, { "code": null, "e": 1404, "s": 1204, "text": "Scalability: Ease of managing different teams/projects: for example run Azure Data Factory pipelines to (simultaneously) populate new data in all your workspaces and subscriptions across your domain." }, { "code": null, "e": 1536, "s": 1404, "text": "Data tracing: Define RBAC and give access to trigger these tasks to only a few team members for increased security and traceability" }, { "code": null, "e": 1569, "s": 1536, "text": "In the github repository project" }, { "code": null, "e": 1596, "s": 1569, "text": "Python and the azureml-SDK" }, { "code": null, "e": 1657, "s": 1596, "text": "Flask for adapting the python script to run as a web service" }, { "code": null, "e": 1685, "s": 1657, "text": "In this Azure Tutorial blog" }, { "code": null, "e": 1728, "s": 1685, "text": "Azure Data Lake as the source of your data" }, { "code": null, "e": 1797, "s": 1728, "text": "Azure Machine Learning Workspaces as the place to register your data" }, { "code": null, "e": 1815, "s": 1797, "text": "Azure Web service" }, { "code": null, "e": 1878, "s": 1815, "text": "Azure Data Factory to trigger the HTTP requests to the web app" }, { "code": null, "e": 2024, "s": 1878, "text": "For making this solution secure we will use Azure authorization and authentication concepts: Service Principal, Key Vault, Managed Identity, AAD." }, { "code": null, "e": 2162, "s": 2024, "text": "In this section we will go through the deployment of the necessary resources. See links for Azure documentation walkthroughs & more info." }, { "code": null, "e": 2234, "s": 2162, "text": "As many as you need, can be across different resource groups or regions" }, { "code": null, "e": 2285, "s": 2234, "text": "For this tutorial I made one “basic” AML instance." }, { "code": null, "e": 2408, "s": 2285, "text": "Create a storage account and make sure to enable “hierarchical namespace” in the advanced settings to make it a Data Lake." }, { "code": null, "e": 2552, "s": 2408, "text": "I created one “main” container called silver (assuming data will come in here from whatever previous processes in your business generates data)" }, { "code": null, "e": 2691, "s": 2552, "text": "I added folders with mock data: an accounting and sales container, each with one csv file we will need to register in our workspace later." }, { "code": null, "e": 2854, "s": 2691, "text": "The service principal (sp) is used to authenticate to AML in this automated scenario, as opposed to the user having to log in with Azure credentials at every run." }, { "code": null, "e": 2932, "s": 2854, "text": "3.1. We will register a service principal as an app on your AAD (link) (link)" }, { "code": null, "e": 3022, "s": 2932, "text": "Open the Azure Cloud Shell by clicking the >_ icon at the top right of your Azure Portal." }, { "code": null, "e": 3130, "s": 3022, "text": "Create the service principal by running this command with whatever name you want instead of sp-medium-demo:" }, { "code": null, "e": 3188, "s": 3130, "text": "az ad sp create-for-rbac --sdk-auth --name sp-medium-demo" }, { "code": null, "e": 3315, "s": 3188, "text": "Save the clientId, clientSecret, and tenantId fields you get in the json response for later (they will go into your key vault)" }, { "code": null, "e": 3385, "s": 3315, "text": "3.2 Give it the necessary permissions to your AML and Storage Account" }, { "code": null, "e": 3556, "s": 3385, "text": "Go to your portal and open the Machine Learning and Storage Account resources, and prepare the name you gave your service principal to add to the “Role assignments” page." }, { "code": null, "e": 3624, "s": 3556, "text": "Make the service principal app Contributor to your AML workspace(s)" }, { "code": null, "e": 3690, "s": 3624, "text": "Make the sp a Storage Blob Data Reader to your Storage account(s)" }, { "code": null, "e": 3842, "s": 3690, "text": "Create a key vault in your resource group and create three secrets to store the credentials of the service principal you just created. (without quotes)" }, { "code": null, "e": 3975, "s": 3842, "text": "The code you will clone later takes these credentials from the key vault to ensure automated & secure authentication /authorization." }, { "code": null, "e": 4142, "s": 3975, "text": "So to make it easy you can use the same names for your secrets, tenant-id sp-id and sp-password for the tenantId, clientId, andclientSecret values you got at step 3.1" }, { "code": null, "e": 4274, "s": 4142, "text": "Clone that repository in your IDE of choice. I’m going with Visual Studio Code (VSC) to make integration with Azure Web App easier." }, { "code": null, "e": 4314, "s": 4274, "text": "Clone github repository in VSC tutorial" }, { "code": null, "e": 4458, "s": 4314, "text": "You can test that the code has been imported correctly in Visual Studio code by running it as a flask app as explained in the repo readme here." }, { "code": null, "e": 4699, "s": 4458, "text": "The only thing you need to fill in yourself in this code is the link to your newly created Key Vault (DNS name: yourname.vault.azure.net), and the names of the secrets if you changed them (see step 4), see instructions in the github Readme." }, { "code": null, "e": 4980, "s": 4699, "text": "To access the key vault you need to add Secret Reader permissions within the key vault Access Policies. You can do this for the place you’re running the code from now (for example a VM), but in this tutorial we give these permissions only to the web-app directly in the next step." }, { "code": null, "e": 5080, "s": 4980, "text": "Because of this the /send_data POST request should not work yet, which is a good thing for security" }, { "code": null, "e": 5203, "s": 5080, "text": "Create a “Web Service” on Azure with Python for the Runtime Stack, and Linux for the OS. Go to the resource once deployed." }, { "code": null, "e": 5311, "s": 5203, "text": "Change the Startup Command for your App Service to match the name of your flask app and function with this:" }, { "code": null, "e": 5362, "s": 5311, "text": "gunicorn --bind=0.0.0.0 --timeout 600 app_body:app" }, { "code": null, "e": 5410, "s": 5362, "text": "(see picture left) Then save the configuration." }, { "code": null, "e": 5505, "s": 5410, "text": "Now you need to connect your code in Visual Studio to the app you created on the Azure Portal." }, { "code": null, "e": 5603, "s": 5505, "text": "Install the azure web service plug-in for VSC, then log in with your azure credentials as needed." }, { "code": null, "e": 5781, "s": 5603, "text": "Now you will have the Azure blade in VSC (1. in picture), and you can see the web app you created in the list under your subscription. Click the blue arrow that says deploy (2.)" }, { "code": null, "e": 6010, "s": 5781, "text": "Fill in the ‘app’ folder from your cloned repo and the name of your newly deployed web all when the Command Pallet asks for it. Then click accept and you are now deploying the python flask app & dependencies to your new website." }, { "code": null, "e": 6145, "s": 6010, "text": "Go on the website once deployment is complete. It should say “Hello Iulia!” — change this message in app_body.py to whatever you want." }, { "code": null, "e": 6187, "s": 6145, "text": "5.05 Give Web App access to the key vault" }, { "code": null, "e": 6318, "s": 6187, "text": "For the other page of your web app, namely /send_data we need the Web App to read secrets from the key vault you set up in step 4." }, { "code": null, "e": 6466, "s": 6318, "text": "First the Web App needs to have an identity to grant authorization to. Enable this in the portal by going to your web app and to Identity Settings:" }, { "code": null, "e": 6719, "s": 6466, "text": "Now go to your key vault in the portal, and check the Access Policies Setting. Click to add a new access policy and search for the name of your Web app (that you just created an identity for; it won’t show in the list before the previous step is saved)" }, { "code": null, "e": 6878, "s": 6719, "text": "Use the Secret Management permission template, select your Web App name under Select Principal and save. Then save again for all changed to the access policy." }, { "code": null, "e": 7005, "s": 6878, "text": "Now your web app can send post requests to the /send_data tab and register your data using the credentials from the key vault." }, { "code": null, "e": 7105, "s": 7005, "text": "Deploy an Azure Data Factory, open the instance via Author & Monitor, and click on create pipeline." }, { "code": null, "e": 7217, "s": 7105, "text": "Now search for “Web” Activity and drag it into your pipeline area. This will be the only step in your pipeline." }, { "code": null, "e": 7394, "s": 7217, "text": "Fill in the name of your deployed web app, select POST request, and fill in the body of your request as the JSON input to the code you cloned. See how to create this JSON here." }, { "code": null, "e": 7449, "s": 7394, "text": "You can now debug or Trigger Now to run your function." }, { "code": null, "e": 7604, "s": 7449, "text": "When the pipeline has succeeded you can now check your AML workspaces. The datastores / datasets you sent via JSON should now be registered and available!" }, { "code": null, "e": 7699, "s": 7604, "text": "At this point anyone can make calls to your web app which is not a robust and secure solution." }, { "code": null, "e": 7928, "s": 7699, "text": "While no data is being sent over the HTTP requests, nor does the app grant any insights into the application is works with; this is still not as robust and secure a solution as possible (and necessary for an enterprise solution)" }, { "code": null, "e": 8069, "s": 7928, "text": "Desired state: ONLY your Azure Data Factory instance is authorized to make calls to your Web App, and thus register data to your workspaces." }, { "code": null, "e": 8196, "s": 8069, "text": "We do this by activating the managed identity of the data factory; so that authorizations can be given to it same as to a user" }, { "code": null, "e": 8363, "s": 8196, "text": "And by setting up AAD authentication to the Web App, so a user (or app) must be logged in and their account must have the right authorization in order to make a call." }, { "code": null, "e": 8578, "s": 8363, "text": "This solution has already been designed by my colleague, René Bremer and he has a repository on github for it. Follow the steps there. You just have to adapt from Azure Function to Web App (same steps regardless)." }, { "code": null, "e": 8617, "s": 8578, "text": "This is the security flow he designed:" } ]
How to Change Text Color of Toolbar Title in an Android App? - GeeksforGeeks
23 Feb, 2021 In an Android app, the toolbar title present at the upper part of the application. Below is a sample image that shows you where the toolbar title is present. In the above image, you may see that the color of the Toolbar Title is white which is by default. So in this article, you will learn how to change the text color of the Toolbar Title in an Android App. There are two ways to change the color of the Toolbar Title. In method 1 Just go to the activity_main.xml file and add a TextView in the toolbar widget with the text color attribute. The complete code for the activity_main.xml file is given below. 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"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="#0F9D58"> <TextView android:id="@+id/custom_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GeeksForGeeks" android:textColor="#D61010" android:textSize="20sp" android:textStyle="bold" /> </androidx.appcompat.widget.Toolbar> </RelativeLayout> Output UI: Step 1: 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 <?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"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="#0F9D58"> </androidx.appcompat.widget.Toolbar> </RelativeLayout> Step 2: Changes in the themes.xml file Go to the app > res > values > themes > themes.xml file and add the following line inside the <resources> tag. <item name=”windowNoTitle”>true</item> Step 3: Working with the MainActivity file In the activity’s onCreate() method, call the activity’s setSupportActionBar() method, and pass the activity’s toolbar. This method sets the toolbar as the app bar for the activity. Add below codes in your Activity to set the text color to the Toolbar title. Below is the complete code for the MainActivity.java / MainActivity.kt file. Java Kotlin import android.graphics.Color;import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import androidx.appcompat.widget.Toolbar; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setTitleTextColor(Color.RED); setSupportActionBar(toolbar); }} import android.graphics.Colorimport android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.appcompat.widget.Toolbar class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar: Toolbar = findViewById(R.id.toolbar) toolbar.setTitleTextColor(Color.RED) setSupportActionBar(toolbar) }} Output: namanjha10 Android-Bars Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android GridView in Android with Example How to Change the Background Color After Clicking the Button in Android? Android Listview in Java with Example Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 25116, "s": 25088, "text": "\n23 Feb, 2021" }, { "code": null, "e": 25274, "s": 25116, "text": "In an Android app, the toolbar title present at the upper part of the application. Below is a sample image that shows you where the toolbar title is present." }, { "code": null, "e": 25537, "s": 25274, "text": "In the above image, you may see that the color of the Toolbar Title is white which is by default. So in this article, you will learn how to change the text color of the Toolbar Title in an Android App. There are two ways to change the color of the Toolbar Title." }, { "code": null, "e": 25724, "s": 25537, "text": "In method 1 Just go to the activity_main.xml file and add a TextView in the toolbar widget with the text color attribute. The complete code for the activity_main.xml file is given below." }, { "code": null, "e": 25728, "s": 25724, "text": "XML" }, { "code": "<?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\"> <androidx.appcompat.widget.Toolbar android:id=\"@+id/toolbar\" android:layout_width=\"match_parent\" android:layout_height=\"?attr/actionBarSize\" android:background=\"#0F9D58\"> <TextView android:id=\"@+id/custom_title\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"GeeksForGeeks\" android:textColor=\"#D61010\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> </androidx.appcompat.widget.Toolbar> </RelativeLayout>", "e": 26581, "s": 25728, "text": null }, { "code": null, "e": 26592, "s": 26581, "text": "Output UI:" }, { "code": null, "e": 26640, "s": 26592, "text": "Step 1: Working with the activity_main.xml file" }, { "code": null, "e": 26756, "s": 26640, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file." }, { "code": null, "e": 26760, "s": 26756, "text": "XML" }, { "code": "<?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\"> <androidx.appcompat.widget.Toolbar android:id=\"@+id/toolbar\" android:layout_width=\"match_parent\" android:layout_height=\"?attr/actionBarSize\" android:background=\"#0F9D58\"> </androidx.appcompat.widget.Toolbar> </RelativeLayout>", "e": 27302, "s": 26760, "text": null }, { "code": null, "e": 27341, "s": 27302, "text": "Step 2: Changes in the themes.xml file" }, { "code": null, "e": 27452, "s": 27341, "text": "Go to the app > res > values > themes > themes.xml file and add the following line inside the <resources> tag." }, { "code": null, "e": 27491, "s": 27452, "text": "<item name=”windowNoTitle”>true</item>" }, { "code": null, "e": 27535, "s": 27491, "text": "Step 3: Working with the MainActivity file " }, { "code": null, "e": 27873, "s": 27535, "text": "In the activity’s onCreate() method, call the activity’s setSupportActionBar() method, and pass the activity’s toolbar. This method sets the toolbar as the app bar for the activity. Add below codes in your Activity to set the text color to the Toolbar title. Below is the complete code for the MainActivity.java / MainActivity.kt file. " }, { "code": null, "e": 27878, "s": 27873, "text": "Java" }, { "code": null, "e": 27885, "s": 27878, "text": "Kotlin" }, { "code": "import android.graphics.Color;import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import androidx.appcompat.widget.Toolbar; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setTitleTextColor(Color.RED); setSupportActionBar(toolbar); }}", "e": 28387, "s": 27885, "text": null }, { "code": "import android.graphics.Colorimport android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.appcompat.widget.Toolbar class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar: Toolbar = findViewById(R.id.toolbar) toolbar.setTitleTextColor(Color.RED) setSupportActionBar(toolbar) }}", "e": 28861, "s": 28387, "text": null }, { "code": null, "e": 28870, "s": 28861, "text": "Output: " }, { "code": null, "e": 28881, "s": 28870, "text": "namanjha10" }, { "code": null, "e": 28894, "s": 28881, "text": "Android-Bars" }, { "code": null, "e": 28902, "s": 28894, "text": "Android" }, { "code": null, "e": 28907, "s": 28902, "text": "Java" }, { "code": null, "e": 28912, "s": 28907, "text": "Java" }, { "code": null, "e": 28920, "s": 28912, "text": "Android" }, { "code": null, "e": 29018, "s": 28920, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29027, "s": 29018, "text": "Comments" }, { "code": null, "e": 29040, "s": 29027, "text": "Old Comments" }, { "code": null, "e": 29079, "s": 29040, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29121, "s": 29079, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29154, "s": 29121, "text": "GridView in Android with Example" }, { "code": null, "e": 29227, "s": 29154, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 29265, "s": 29227, "text": "Android Listview in Java with Example" }, { "code": null, "e": 29280, "s": 29265, "text": "Arrays in Java" }, { "code": null, "e": 29324, "s": 29280, "text": "Split() String method in Java with examples" }, { "code": null, "e": 29346, "s": 29324, "text": "For-each loop in Java" }, { "code": null, "e": 29382, "s": 29346, "text": "Arrays.sort() in Java with examples" } ]
Remove Leading Zeros From String in Java
There are many approaches to remove leading zeroes from a string in Java. Here we will use some basic functions of String and Arrays class which to remove leading zeroes from a string. So this approach proceed as first convert string to a character array so that evaluation of each character in string becomes simpler. Now it seems simple that compare each character and find first non zero characters. But here is a constraint that in Java that array doesn't have equals method to compare its value so here we will use valueOf() method of String class to compare each character. Now we get the position of first non zero digit in our String the only thing remaining is to trim our array upto first non zero digit position. For this use copyOfRange() method which takes three arguments one is original array second is from a position where a copy is to be started and third is to position upto which copy is to be done. public class RemoveLeadingZeroes { public static void main(String[] args) { String str = "00099898979"; int arrayLength = 0; char[] array = str.toCharArray(); arrayLength = array.length; int firstNonZeroAt = 0; for(int i=0; i<array.length; i++) { if(!String.valueOf(array[i]).equalsIgnoreCase("0")) { firstNonZeroAt = i; break; } } System.out.println("first non zero digit at : " +firstNonZeroAt); char [] newArray = Arrays.copyOfRange(array, firstNonZeroAt,arrayLength); String resultString = new String(newArray); System.out.println(resultString); } } myCSV.csv file created with following text first non zero digit at : 3 99898979
[ { "code": null, "e": 1247, "s": 1062, "text": "There are many approaches to remove leading zeroes from a string in Java. Here we will use some basic functions of String and Arrays class which to remove leading zeroes from a string." }, { "code": null, "e": 1642, "s": 1247, "text": "So this approach proceed as first convert string to a character array so that evaluation of each character in string becomes simpler. Now it seems simple that compare each character and find first non zero characters. But here is a constraint that in Java that array doesn't have equals method to compare its value so here we will use valueOf() method of String class to compare each character." }, { "code": null, "e": 1982, "s": 1642, "text": "Now we get the position of first non zero digit in our String the only thing remaining is to trim our array upto first non zero digit position. For this use copyOfRange() method which takes three arguments one is original array second is from a position where a copy is to be started and third is to position upto which copy is to be done." }, { "code": null, "e": 2650, "s": 1982, "text": "public class RemoveLeadingZeroes {\n public static void main(String[] args) {\n String str = \"00099898979\";\n int arrayLength = 0;\n char[] array = str.toCharArray();\n arrayLength = array.length;\n int firstNonZeroAt = 0;\n for(int i=0; i<array.length; i++) {\n if(!String.valueOf(array[i]).equalsIgnoreCase(\"0\")) {\n firstNonZeroAt = i;\n break;\n }\n }\n System.out.println(\"first non zero digit at : \" +firstNonZeroAt);\n char [] newArray = Arrays.copyOfRange(array, firstNonZeroAt,arrayLength);\n String resultString = new String(newArray);\n System.out.println(resultString);\n }\n}" }, { "code": null, "e": 2693, "s": 2650, "text": "myCSV.csv file created with following text" }, { "code": null, "e": 2730, "s": 2693, "text": "first non zero digit at : 3\n99898979" } ]
Python | Pandas dataframe.replace() - GeeksforGeeks
19 Feb, 2021 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.replace() function is used to replace a string, regex, list, dictionary, series, number etc. from a dataframe. This is a very rich function as it has many variations.The most powerful thing about this function is that it can work with Python regex (regular expressions). Syntax: DataFrame.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method=’pad’, axis=None) Parameters:to_replace : [str, regex, list, dict, Series, numeric, or None] pattern that we are trying to replace in dataframe.value : Value to use to fill holes (e.g. 0), alternately a dict of values specifying which value to use for each column (columns not in the dict will not be filled). Regular expressions, strings and lists or dicts of such objects are also allowed.inplace : If True, in place. Note: this will modify any other views on this object (e.g. a column from a DataFrame). Returns the caller if this is True.limit : Maximum size gap to forward or backward fillregex : Whether to interpret to_replace and/or value as regular expressions. If this is True then to_replace must be a string. Otherwise, to_replace must be None because this parameter will be interpreted as a regular expression or a list, dict, or array of regular expressions.method : Method to use when for replacement, when to_replace is a list. Returns: filled : NDFrame For link to CSV file Used in Code, click here Example #1: Replace team “Boston Celtics” with “Omega Warrior” in the nba.csv file # importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv("nba.csv") # Printing the first 10 rows of the data frame for visualizationdf[:10] Output: We are going to replace team “Boston Celtics” with “Omega Warrior” in the ‘df’ data frame # this will replace "Boston Celtics" with "Omega Warrior"df.replace(to_replace ="Boston Celtics", value ="Omega Warrior") Output: Example #2: Replacing more than one value at a time. Using python list as an argument We are going to replace team “Boston Celtics” and “Texas” with “Omega Warrior” in the ‘df’ dataframe. # importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv("nba.csv") # this will replace "Boston Celtics" and "Texas" with "Omega Warrior"df.replace(to_replace =["Boston Celtics", "Texas"], value ="Omega Warrior") Output:Notice the College column in the first row, “Texas” has been replaced with “Omega Warriors” Example #3: Replace the Nan value in the data frame with -99999 value. # importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv("nba.csv") # will replace Nan value in dataframe with value -99999 df.replace(to_replace = np.nan, value =-99999) Output:Notice all the Nan value in the data frame has been replaced by -99999. Though for practical purposes we should be careful with what value we are replacing nan value.YouTubeGeeksforGeeks501K subscribersPython | Pandas dataframe.replace() | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:09•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Z2dy-U9rKxk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Technical Scripter 2018 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Reading and Writing to text files in Python Create a Pandas DataFrame from Lists sum() function in Python *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe Convert integer to string in Python
[ { "code": null, "e": 24910, "s": 24882, "text": "\n19 Feb, 2021" }, { "code": null, "e": 25124, "s": 24910, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 25412, "s": 25124, "text": "Pandas dataframe.replace() function is used to replace a string, regex, list, dictionary, series, number etc. from a dataframe. This is a very rich function as it has many variations.The most powerful thing about this function is that it can work with Python regex (regular expressions)." }, { "code": null, "e": 25532, "s": 25412, "text": "Syntax: DataFrame.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method=’pad’, axis=None)" }, { "code": null, "e": 26459, "s": 25532, "text": "Parameters:to_replace : [str, regex, list, dict, Series, numeric, or None] pattern that we are trying to replace in dataframe.value : Value to use to fill holes (e.g. 0), alternately a dict of values specifying which value to use for each column (columns not in the dict will not be filled). Regular expressions, strings and lists or dicts of such objects are also allowed.inplace : If True, in place. Note: this will modify any other views on this object (e.g. a column from a DataFrame). Returns the caller if this is True.limit : Maximum size gap to forward or backward fillregex : Whether to interpret to_replace and/or value as regular expressions. If this is True then to_replace must be a string. Otherwise, to_replace must be None because this parameter will be interpreted as a regular expression or a list, dict, or array of regular expressions.method : Method to use when for replacement, when to_replace is a list." }, { "code": null, "e": 26485, "s": 26459, "text": "Returns: filled : NDFrame" }, { "code": null, "e": 26531, "s": 26485, "text": "For link to CSV file Used in Code, click here" }, { "code": null, "e": 26614, "s": 26531, "text": "Example #1: Replace team “Boston Celtics” with “Omega Warrior” in the nba.csv file" }, { "code": "# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv(\"nba.csv\") # Printing the first 10 rows of the data frame for visualizationdf[:10]", "e": 26797, "s": 26614, "text": null }, { "code": null, "e": 26805, "s": 26797, "text": "Output:" }, { "code": null, "e": 26895, "s": 26805, "text": "We are going to replace team “Boston Celtics” with “Omega Warrior” in the ‘df’ data frame" }, { "code": "# this will replace \"Boston Celtics\" with \"Omega Warrior\"df.replace(to_replace =\"Boston Celtics\", value =\"Omega Warrior\")", "e": 27033, "s": 26895, "text": null }, { "code": null, "e": 27041, "s": 27033, "text": "Output:" }, { "code": null, "e": 27129, "s": 27043, "text": "Example #2: Replacing more than one value at a time. Using python list as an argument" }, { "code": null, "e": 27231, "s": 27129, "text": "We are going to replace team “Boston Celtics” and “Texas” with “Omega Warrior” in the ‘df’ dataframe." }, { "code": "# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv(\"nba.csv\") # this will replace \"Boston Celtics\" and \"Texas\" with \"Omega Warrior\"df.replace(to_replace =[\"Boston Celtics\", \"Texas\"], value =\"Omega Warrior\")", "e": 27515, "s": 27231, "text": null }, { "code": null, "e": 27685, "s": 27515, "text": "Output:Notice the College column in the first row, “Texas” has been replaced with “Omega Warriors” Example #3: Replace the Nan value in the data frame with -99999 value." }, { "code": "# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv(\"nba.csv\") # will replace Nan value in dataframe with value -99999 df.replace(to_replace = np.nan, value =-99999)", "e": 27900, "s": 27685, "text": null }, { "code": null, "e": 28907, "s": 27900, "text": "Output:Notice all the Nan value in the data frame has been replaced by -99999. Though for practical purposes we should be careful with what value we are replacing nan value.YouTubeGeeksforGeeks501K subscribersPython | Pandas dataframe.replace() | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:09•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Z2dy-U9rKxk\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 28931, "s": 28907, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28963, "s": 28931, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 28977, "s": 28963, "text": "Python-pandas" }, { "code": null, "e": 29001, "s": 28977, "text": "Technical Scripter 2018" }, { "code": null, "e": 29008, "s": 29001, "text": "Python" }, { "code": null, "e": 29106, "s": 29008, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29115, "s": 29106, "text": "Comments" }, { "code": null, "e": 29128, "s": 29115, "text": "Old Comments" }, { "code": null, "e": 29146, "s": 29128, "text": "Python Dictionary" }, { "code": null, "e": 29168, "s": 29146, "text": "Enumerate() in Python" }, { "code": null, "e": 29200, "s": 29168, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29242, "s": 29200, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29286, "s": 29242, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29323, "s": 29286, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29348, "s": 29323, "text": "sum() function in Python" }, { "code": null, "e": 29377, "s": 29348, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29433, "s": 29377, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
Building an Automated Machine Learning Pipeline: Part Four | by Ceren Iyim | Towards Data Science
Part 1: Understand, clean, explore, process data Part 2: Set metric and baseline, select and tune model Part 3: Train, evaluate and interpret model Part 4: Automate your pipeline using Docker and Luigi (you are reading now) Disclaimer: This article series is not a tutorial about Docker and Luigi. It is the last article of an article series “Building an Automated Machine Learning Pipeline” that focuses on building end-to-end ML pipeline and showing how to automate it using certain elements of both tools. This article will make more sense to you if you read the previous ones from the links above. In this article series, we set our course to build a 9-step machine learning (ML) pipeline and automate it using Docker and Luigi. Understand & Clean & Format DataExploratory Data AnalysisFeature Engineering & Pre-processingSet Evaluation Metric & Establish BaselineSelect an ML Model based on the Evaluation MetricPerform Hyperparameter Tuning on the Selected ModelTrain and Evaluate the ModelInterpret Model PredictionsDraw Conclusions & Document Work Understand & Clean & Format Data Exploratory Data Analysis Feature Engineering & Pre-processing Set Evaluation Metric & Establish Baseline Select an ML Model based on the Evaluation Metric Perform Hyperparameter Tuning on the Selected Model Train and Evaluate the Model Interpret Model Predictions Draw Conclusions & Document Work As a result of this pipeline, we built our ML solution and called it, the wine rating predictor because we are trying to infer the quality of wine represented with the points using a sample dataset. We defined the requirements for our wine rating predictor in the first article as: - understandable because our audience will likely have limited knowledge of statistics and ML. - performant because the complete production dataset could have millions of rows. - automated in a way that it can run on any production system without requiring specialized configurations and setups. We have so far satisfied the understandability and addressed performance — to some extent: We have selected an understandable model, random forest regressor, as the underlying ML algorithm of the wine rating predictor. Moreover, we have explained how random forest regressor works as well as its hyperparameters in the second and third article. We have built a performant model by performing hyperparameter tuning on the random forest regressor. We still have room for it though. Today, we will wear a software engineer’s hat and address the last requirement — automation. We will take the steps below from the ML pipeline, run them on Docker Containers and connect them with Luigi Tasks. (Don’t worry we will elaborate on them throughout the article 🙂) If you have noticed we have two additional steps because a typical real-world ML pipeline starts with getting the data from a source. Also, we included the training-test dataset split and the rest is the known steps of the ML pipeline. To run the flow above, we will first look at Docker and Luigi and understand their use in the context of this article series. Therefore, we will start by explaining these tools and their necessary elements. Then, we will connect the dots using these tools. Eventually, we will put the pieces together and run the flow which will accomplish our mission of automation! What Is Docker and How It Is Used for the Wine Rating Predictor?What Is Luigi and Why It Is Selected as an Orchestration Tool?Put the Pieces of Docker and Luigi TogetherRun and Automate the Pipeline! What Is Docker and How It Is Used for the Wine Rating Predictor? What Is Luigi and Why It Is Selected as an Orchestration Tool? Put the Pieces of Docker and Luigi Together Run and Automate the Pipeline! You can find the GitHub Repository here: github.com One more disclaimer before we start: Disclaimer: Structure of the repository and download_data.py , util.py , docker-clean.sh and docker-compose.yml files are provided to me as the basis of the code challenge. Rest of the code is written by me. The official definition of Docker from Wikipedia is as follows: Docker is a set of platform as a service products that uses operating system-level virtualization to deliver software in packages called containers. I would define it as creating virtual environments for your application/software/data science/ML projects so that it can run seamlessly on any system that has Docker. Via containers. They are isolated virtual environments to run your applications, for our case, ML solutions. From images. They are templates that are used to create containers. They contain information about your underlying operating system, environment and libraries — with versions. By reading the instructions from a Dockerfile. It is a set of instructions and commands that a user could call on the command line to create an image. You can create a local image in your system with the docker build Dockerfile -t <image_name> command. Containers are the running instances of images. When you run an image you create a container that is an isolated environment. We used Docker to build virtual environments and manage the dependencies of the libraries so that we can run the flow seamlessly. The automation flow below is designed so that each box runs on a separate Docker container. I am sure you have noticed some directories and files in the repository that we haven’t mentioned yet. You can think of download_data, make_dataset, clean_data, extract_features, transform_data, impute_data, train_model and evaluate_model directories as the boundaries of the boxes in the automation flow that contains a Dockerfile and the source code as a Python file. Before looking at how to create a Dockerfile, let’s understand the use of base_docker here. Each step of the automation flow runs on a separate container. However, they are modules written in Python and the only difference between them are the libraries used. So, base_docker is used to specify the common environment variables and install the required Python version and the libraries. It also contributed to the performance of the wine rating predictor by installing required packages once rather than installing them every time on a separate container. When creating a Dockerfile start by the steps as if you are creating a local environment on your machine. Considering your aim is to deploy an ML solution with Python, you can build your image on top of an existing Python Image in the Docker Hub. An important point here is to select an existing Python Image that is suitable for your case since there are several versions and sizes are available. FROM python:3.7-slimENV LC_ALL=C.UTF-8ENV LANG=C.UTF-8ENV PYTHONPATH=/opt/orchestrator:$PYTHONPATHCOPY requirements.txt /opt/base_docker/RUN pip install -r /opt/base_docker/requirements.txtWORKDIR /opt/base_docker/ slim variant is chosen and Python version 3.7 is specified, same Python version as in my local system. ENV command is used to update the PATH environment variable for the underlying operating system (Python 3.7-slim for our case) that your container installs. Libraries with the versions mentioned in the requirements.txt are copied and installed with the pip_install. In addition to the aforementioned libraries of Python, click is also installed — more on the use of that later. As the last instruction, the working directory of a Docker Container is defined with the WORKDIR command. Now, our base_docker is ready, exploring any Dockerfile from the automation flow will be sufficient because all other Dockerfiles have been written with the same logic. Here is an example from clean_data: FROM code-challenge/base-dockerCOPY . /opt/clean_data/WORKDIR /opt/clean_data/ Now our base image become the base_docker. Every file in the clean_data directory is copied and a working directory of a Docker container is created. It is time to have a look at Spotify’s beloved Luigi! The official definition from the docs is as follows: Luigi is a Python package that helps you build complex pipelines of batch jobs. It handles dependency resolution, workflow management, visualization, handling failures, command line integration, and much more. It is basically an orchestration tool to stitch many tasks together in a directed acyclic graph (DAG) structure: When you build an ML solution and as the scale grows, this can easily become complex and messy. Luigi is a robust workflow management tool that can prevent chaos and complexity. There are two fundamental building blocks of Luigi: Task and Target The steps of a workflow are tasks, usually a single unit of work, where computations are done. A Luigi workflow is built on top of tasks. Each task is connected with a target. A target can be a file, a checkpoint in the workflow or any kind of output generated by the task. We are dumping outputs generated by each task in the data_root: In the flow, each task is dependent on the output of the previous task except the initial task download_data. Each file is passed as a Parameter so that it can be consumed by the latter step in the workflow. When designing a workflow, Luigi recommends the atomic structure: Each task should have a single file as output like in the download_data and train_model tasks. For the rest of the tasks, we imitate atomicity with the SUCCESS flag. When we perform computations on both training and test datasets, we create a SUCCESS flag as an output of the task, after dumping the output files in the directory. This way, the next task only checks whether a SUCCESS flag exists. Task dependencies are defined with the requires() method. Here is a task outline from Luigi documentation: For our case, task dependencies are obvious since we defined a linear automation flow. Unfortunately, Luigi does not come with a triggering mechanism. If you want to run a Luigi workflow you use the command line specifying the module name and the last task in the project directory: luigi --module <modul_name> <task_name> When a workflow is triggered, Luigi checks if the output of the last step exists. If not, then it checks backwards if the outputs of the predecessor steps exist. For our case, this would be train_model, impute_data, transform_data, extract_features, clean_data, make_dataset and download_data . If an output of a task from any step of the flow exists Luigi resumes the flow where it has left of. This is a very useful and important trait to prevent your ML pipeline from crashing when it contains partial data. Now we know the essential elements of Luigi and Docker we can move forward with completing the picture! We will put the pieces of Docker and Luigi in the docker-compose.yml and orchestrator directory. The utility functions provided by the awesome engineers of Data Revenue has enabled me to connect the pieces of Docker and Luigi. Functions and classes available in the util.py played an important role that connected Docker and Luigi for the wine rating predictor. For example, DockerTask — the object that we pass as a parameter between the tasks — is not available as a parameter in the Luigi normally. First, let’s have a look at task.py in the orchestrator directory where I built the automation flow using utilities. Then, let’s understand the purpose of docker-compose.yml. Luigi Parameter: Each task starts with a LuigiParameter object where we specify the input/output files and directories of the task. For example, the last task EvaluateModel where we evaluate the ML model with the test set takes the test_features,test_target and the trained model file (model.sav) as an input LuigiParameter. Since this task creates multiple files as output (PredictionsVSActuals.png and FeatureImportances.png) we also define a SUCCESS flag to mimic atomicity. Image: We define which Docker Image to use to create the container. Dependent Task: If there are any dependent tasks, define them here with the requires() method. The dependent task of the EvaluateModel is TrainModel. Command: The command to be executed by the container. Here command calls the source code available in the evaluate_model.py with the relevant parameters. Output: The output() method returns one or more Target objects (either the output file or a SUCCESS flag) Recall that source codes for each step of the flow is available in the respective directory as Python file. Let’s have a look at the source code of train_model : After defining the helper functions convert_features_to_array and convert_target_to_array, we defined necessary click commands. Click, as defined in the official documentation: It is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. We used Click to be able to pass the arguments to the python scripts from the command line. Finally, we train the model with the fine-tuned parameters that we have decided in the Perform Hyperparameter Tuning on the Selected Model step on the training dataset. Finally, we save the trained model in model.sav file as an output. The official definition for Docker Compose from the Docker Docs is as follows: Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration. This definition suits to our case since we run the automation flow on 9 containers including base_docker. You can read more about the use and commands of docker-compose here. The important part for us here the command to run Luigi tasks is written here, so when we run containers through docker-compose, it will trigger the automation flow with the luigi — module task EvaluateModel-scheduler-host luigiid command. This is the moment of truth! We are going to run the automation flow and automate the 9-Step ML Pipeline. It is the last of the last step, stick with it for one more minute 😉 For me this is: cd GitHub/Wine-Rating-Predictor-ML-Model Instead of building multiple Docker Containers one by one, we are going to use a shell script to build Docker Containers: build-task-images.sh ./build-task-images.sh 0.1 The below message shows that Containers are built successfully. So we are good to go for triggering automation flow. Successfully tagged code-challenge/evaluate-model:0.1 We will trigger the workflow with docker-compose up orchestrator Upon writing this command, Luigi checks whether each task is complete and outputs the following information: Checking if EvaluateModel( no_remove_finished=False, in_test_features_csv=/usr/share/data/interim/test_features.csv, in_test_target_csv=/usr/share/data/interim/test_target.csv, in_trained_model=/usr/share/data/output/model.sav, out_dir=/usr/share/data/output/, flag=.SUCCESS_EvaluateModel) is completeChecking if TrainModel( no_remove_finished=False, in_train_features_csv=/usr/share/data/interim/train_features.csv, in_train_target_csv=/usr/share/data/interim/train_target.csv, out_dir=/usr/share/data/output/) is completeChecking if ImputeData( no_remove_finished=False, in_train_csv=/usr/share/data/interim/train_transformed.csv, in_test_csv=/usr/share/data/interim/test_transformed.csv, out_dir=/usr/share/data/interim/, flag=.SUCCESS_ImputeData) is completeChecking if TransformData( no_remove_finished=False, in_train_csv=/usr/share/data/interim/train_features_extracted.csv, in_test_csv=/usr/share/data/interim/test_features_extracted.csv, out_dir=/usr/share/data/interim/, flag=.SUCCESS_TransformData) is completeChecking if ExtractFeatures( no_remove_finished=False, in_train_csv=/usr/share/data/interim/train_cleaned.csv, in_test_csv=/usr/share/data/interim/test_cleaned.csv, out_dir=/usr/share/data/interim/, flag=.SUCCESS_ExtractFeatures) is completeChecking if CleanData( no_remove_finished=False, in_train_csv=/usr/share/data/interim/train.csv, in_test_csv=/usr/share/data/interim/test.csv, out_dir=/usr/share/data/interim/, flag=.SUCCESS_CleanData) is completeChecking if MakeDatasets( no_remove_finished=False, in_csv=/usr/share/data/raw/wine_dataset.csv, out_dir=/usr/share/data/interim/, flag=.SUCCESS_MakeDatasets) is completeChecking if DownloadData( no_remove_finished=False, fname=wine_dataset, out_dir=/usr/share/data/raw/, url=https://github.com/datarevenue-berlin/code-challenge-2019/releases/download/0.1.0/dataset_sampled.csv) is complete Then runs the task in one by one. Another important information for us is: INFO:evaluate-model:Mean square error of the model is: 4.95 After a successful run you see a 🙂: Bonus Points: Let’s see how Luigi resumes the flow where it has left ofLet’s say you prepared training datasets and run the automation flow, then you will build the next steps afterwards starting with the training the model. Luigi won’t repeat successfully run previous steps and only runs TrainModel and EvaluateModel tasks in that case. I would say Wow! It was quite a journey spanning over 4 articles and a month ⛵️ We started from the very beginning and analyzed every step of the 9-step ML pipeline through the first, second and third article. towardsdatascience.com towardsdatascience.com towardsdatascience.com In this last article, we introduced the relevant elements of Docker and Luigi and explained their importance and use for the wine rating predictor. We completed the last missing piece of our comprehensive pipeline and did a dry run of an ML solution — just as if it runs on production systems. I think it is time to thank my significant other Serkan Durusoy. He has been the most precious mentor, editor and study buddy I had in my data science expedition! He helped me to overcome the ups and downs of changing a career. Also, I want to acknowledge his support to complete this article series as well as the grit he provided for me. Thank you, my dear ❤️ Thanks for reading 🙂 Please feel free to use this pipeline, the code and the repository for your own projects. For comments or constructive feedback, you can reach out to me on responses, Twitter or Linkedin! Before we go, I also want to share some of the useful resources that I used to prepare for this project. See you in the next article 👋 Scale Your Machine Learning Pipeline by Data Revenue Docker for Beginners: Full Course by KodeKloud Build a Docker Container with Your Machine Learning Model by Tina Bu Luigi Documentation Docker Documentation Building Data Science Pipelines With Luigi and Jupyter Notebooks by Mattia Ciollaro
[ { "code": null, "e": 220, "s": 171, "text": "Part 1: Understand, clean, explore, process data" }, { "code": null, "e": 275, "s": 220, "text": "Part 2: Set metric and baseline, select and tune model" }, { "code": null, "e": 319, "s": 275, "text": "Part 3: Train, evaluate and interpret model" }, { "code": null, "e": 395, "s": 319, "text": "Part 4: Automate your pipeline using Docker and Luigi (you are reading now)" }, { "code": null, "e": 773, "s": 395, "text": "Disclaimer: This article series is not a tutorial about Docker and Luigi. It is the last article of an article series “Building an Automated Machine Learning Pipeline” that focuses on building end-to-end ML pipeline and showing how to automate it using certain elements of both tools. This article will make more sense to you if you read the previous ones from the links above." }, { "code": null, "e": 904, "s": 773, "text": "In this article series, we set our course to build a 9-step machine learning (ML) pipeline and automate it using Docker and Luigi." }, { "code": null, "e": 1227, "s": 904, "text": "Understand & Clean & Format DataExploratory Data AnalysisFeature Engineering & Pre-processingSet Evaluation Metric & Establish BaselineSelect an ML Model based on the Evaluation MetricPerform Hyperparameter Tuning on the Selected ModelTrain and Evaluate the ModelInterpret Model PredictionsDraw Conclusions & Document Work" }, { "code": null, "e": 1260, "s": 1227, "text": "Understand & Clean & Format Data" }, { "code": null, "e": 1286, "s": 1260, "text": "Exploratory Data Analysis" }, { "code": null, "e": 1323, "s": 1286, "text": "Feature Engineering & Pre-processing" }, { "code": null, "e": 1366, "s": 1323, "text": "Set Evaluation Metric & Establish Baseline" }, { "code": null, "e": 1416, "s": 1366, "text": "Select an ML Model based on the Evaluation Metric" }, { "code": null, "e": 1468, "s": 1416, "text": "Perform Hyperparameter Tuning on the Selected Model" }, { "code": null, "e": 1497, "s": 1468, "text": "Train and Evaluate the Model" }, { "code": null, "e": 1525, "s": 1497, "text": "Interpret Model Predictions" }, { "code": null, "e": 1558, "s": 1525, "text": "Draw Conclusions & Document Work" }, { "code": null, "e": 1840, "s": 1558, "text": "As a result of this pipeline, we built our ML solution and called it, the wine rating predictor because we are trying to infer the quality of wine represented with the points using a sample dataset. We defined the requirements for our wine rating predictor in the first article as:" }, { "code": null, "e": 1935, "s": 1840, "text": "- understandable because our audience will likely have limited knowledge of statistics and ML." }, { "code": null, "e": 2017, "s": 1935, "text": "- performant because the complete production dataset could have millions of rows." }, { "code": null, "e": 2136, "s": 2017, "text": "- automated in a way that it can run on any production system without requiring specialized configurations and setups." }, { "code": null, "e": 2227, "s": 2136, "text": "We have so far satisfied the understandability and addressed performance — to some extent:" }, { "code": null, "e": 2481, "s": 2227, "text": "We have selected an understandable model, random forest regressor, as the underlying ML algorithm of the wine rating predictor. Moreover, we have explained how random forest regressor works as well as its hyperparameters in the second and third article." }, { "code": null, "e": 2616, "s": 2481, "text": "We have built a performant model by performing hyperparameter tuning on the random forest regressor. We still have room for it though." }, { "code": null, "e": 2890, "s": 2616, "text": "Today, we will wear a software engineer’s hat and address the last requirement — automation. We will take the steps below from the ML pipeline, run them on Docker Containers and connect them with Luigi Tasks. (Don’t worry we will elaborate on them throughout the article 🙂)" }, { "code": null, "e": 3126, "s": 2890, "text": "If you have noticed we have two additional steps because a typical real-world ML pipeline starts with getting the data from a source. Also, we included the training-test dataset split and the rest is the known steps of the ML pipeline." }, { "code": null, "e": 3333, "s": 3126, "text": "To run the flow above, we will first look at Docker and Luigi and understand their use in the context of this article series. Therefore, we will start by explaining these tools and their necessary elements." }, { "code": null, "e": 3493, "s": 3333, "text": "Then, we will connect the dots using these tools. Eventually, we will put the pieces together and run the flow which will accomplish our mission of automation!" }, { "code": null, "e": 3693, "s": 3493, "text": "What Is Docker and How It Is Used for the Wine Rating Predictor?What Is Luigi and Why It Is Selected as an Orchestration Tool?Put the Pieces of Docker and Luigi TogetherRun and Automate the Pipeline!" }, { "code": null, "e": 3758, "s": 3693, "text": "What Is Docker and How It Is Used for the Wine Rating Predictor?" }, { "code": null, "e": 3821, "s": 3758, "text": "What Is Luigi and Why It Is Selected as an Orchestration Tool?" }, { "code": null, "e": 3865, "s": 3821, "text": "Put the Pieces of Docker and Luigi Together" }, { "code": null, "e": 3896, "s": 3865, "text": "Run and Automate the Pipeline!" }, { "code": null, "e": 3937, "s": 3896, "text": "You can find the GitHub Repository here:" }, { "code": null, "e": 3948, "s": 3937, "text": "github.com" }, { "code": null, "e": 3985, "s": 3948, "text": "One more disclaimer before we start:" }, { "code": null, "e": 4193, "s": 3985, "text": "Disclaimer: Structure of the repository and download_data.py , util.py , docker-clean.sh and docker-compose.yml files are provided to me as the basis of the code challenge. Rest of the code is written by me." }, { "code": null, "e": 4257, "s": 4193, "text": "The official definition of Docker from Wikipedia is as follows:" }, { "code": null, "e": 4406, "s": 4257, "text": "Docker is a set of platform as a service products that uses operating system-level virtualization to deliver software in packages called containers." }, { "code": null, "e": 4573, "s": 4406, "text": "I would define it as creating virtual environments for your application/software/data science/ML projects so that it can run seamlessly on any system that has Docker." }, { "code": null, "e": 4682, "s": 4573, "text": "Via containers. They are isolated virtual environments to run your applications, for our case, ML solutions." }, { "code": null, "e": 4858, "s": 4682, "text": "From images. They are templates that are used to create containers. They contain information about your underlying operating system, environment and libraries — with versions." }, { "code": null, "e": 5111, "s": 4858, "text": "By reading the instructions from a Dockerfile. It is a set of instructions and commands that a user could call on the command line to create an image. You can create a local image in your system with the docker build Dockerfile -t <image_name> command." }, { "code": null, "e": 5237, "s": 5111, "text": "Containers are the running instances of images. When you run an image you create a container that is an isolated environment." }, { "code": null, "e": 5459, "s": 5237, "text": "We used Docker to build virtual environments and manage the dependencies of the libraries so that we can run the flow seamlessly. The automation flow below is designed so that each box runs on a separate Docker container." }, { "code": null, "e": 5829, "s": 5459, "text": "I am sure you have noticed some directories and files in the repository that we haven’t mentioned yet. You can think of download_data, make_dataset, clean_data, extract_features, transform_data, impute_data, train_model and evaluate_model directories as the boundaries of the boxes in the automation flow that contains a Dockerfile and the source code as a Python file." }, { "code": null, "e": 5921, "s": 5829, "text": "Before looking at how to create a Dockerfile, let’s understand the use of base_docker here." }, { "code": null, "e": 6385, "s": 5921, "text": "Each step of the automation flow runs on a separate container. However, they are modules written in Python and the only difference between them are the libraries used. So, base_docker is used to specify the common environment variables and install the required Python version and the libraries. It also contributed to the performance of the wine rating predictor by installing required packages once rather than installing them every time on a separate container." }, { "code": null, "e": 6783, "s": 6385, "text": "When creating a Dockerfile start by the steps as if you are creating a local environment on your machine. Considering your aim is to deploy an ML solution with Python, you can build your image on top of an existing Python Image in the Docker Hub. An important point here is to select an existing Python Image that is suitable for your case since there are several versions and sizes are available." }, { "code": null, "e": 6998, "s": 6783, "text": "FROM python:3.7-slimENV LC_ALL=C.UTF-8ENV LANG=C.UTF-8ENV PYTHONPATH=/opt/orchestrator:$PYTHONPATHCOPY requirements.txt /opt/base_docker/RUN pip install -r /opt/base_docker/requirements.txtWORKDIR /opt/base_docker/" }, { "code": null, "e": 7101, "s": 6998, "text": "slim variant is chosen and Python version 3.7 is specified, same Python version as in my local system." }, { "code": null, "e": 7258, "s": 7101, "text": "ENV command is used to update the PATH environment variable for the underlying operating system (Python 3.7-slim for our case) that your container installs." }, { "code": null, "e": 7479, "s": 7258, "text": "Libraries with the versions mentioned in the requirements.txt are copied and installed with the pip_install. In addition to the aforementioned libraries of Python, click is also installed — more on the use of that later." }, { "code": null, "e": 7585, "s": 7479, "text": "As the last instruction, the working directory of a Docker Container is defined with the WORKDIR command." }, { "code": null, "e": 7790, "s": 7585, "text": "Now, our base_docker is ready, exploring any Dockerfile from the automation flow will be sufficient because all other Dockerfiles have been written with the same logic. Here is an example from clean_data:" }, { "code": null, "e": 7869, "s": 7790, "text": "FROM code-challenge/base-dockerCOPY . /opt/clean_data/WORKDIR /opt/clean_data/" }, { "code": null, "e": 8019, "s": 7869, "text": "Now our base image become the base_docker. Every file in the clean_data directory is copied and a working directory of a Docker container is created." }, { "code": null, "e": 8073, "s": 8019, "text": "It is time to have a look at Spotify’s beloved Luigi!" }, { "code": null, "e": 8126, "s": 8073, "text": "The official definition from the docs is as follows:" }, { "code": null, "e": 8336, "s": 8126, "text": "Luigi is a Python package that helps you build complex pipelines of batch jobs. It handles dependency resolution, workflow management, visualization, handling failures, command line integration, and much more." }, { "code": null, "e": 8449, "s": 8336, "text": "It is basically an orchestration tool to stitch many tasks together in a directed acyclic graph (DAG) structure:" }, { "code": null, "e": 8627, "s": 8449, "text": "When you build an ML solution and as the scale grows, this can easily become complex and messy. Luigi is a robust workflow management tool that can prevent chaos and complexity." }, { "code": null, "e": 8695, "s": 8627, "text": "There are two fundamental building blocks of Luigi: Task and Target" }, { "code": null, "e": 8833, "s": 8695, "text": "The steps of a workflow are tasks, usually a single unit of work, where computations are done. A Luigi workflow is built on top of tasks." }, { "code": null, "e": 8969, "s": 8833, "text": "Each task is connected with a target. A target can be a file, a checkpoint in the workflow or any kind of output generated by the task." }, { "code": null, "e": 9033, "s": 8969, "text": "We are dumping outputs generated by each task in the data_root:" }, { "code": null, "e": 9241, "s": 9033, "text": "In the flow, each task is dependent on the output of the previous task except the initial task download_data. Each file is passed as a Parameter so that it can be consumed by the latter step in the workflow." }, { "code": null, "e": 9402, "s": 9241, "text": "When designing a workflow, Luigi recommends the atomic structure: Each task should have a single file as output like in the download_data and train_model tasks." }, { "code": null, "e": 9705, "s": 9402, "text": "For the rest of the tasks, we imitate atomicity with the SUCCESS flag. When we perform computations on both training and test datasets, we create a SUCCESS flag as an output of the task, after dumping the output files in the directory. This way, the next task only checks whether a SUCCESS flag exists." }, { "code": null, "e": 9812, "s": 9705, "text": "Task dependencies are defined with the requires() method. Here is a task outline from Luigi documentation:" }, { "code": null, "e": 9899, "s": 9812, "text": "For our case, task dependencies are obvious since we defined a linear automation flow." }, { "code": null, "e": 10095, "s": 9899, "text": "Unfortunately, Luigi does not come with a triggering mechanism. If you want to run a Luigi workflow you use the command line specifying the module name and the last task in the project directory:" }, { "code": null, "e": 10136, "s": 10095, "text": "luigi --module <modul_name> <task_name> " }, { "code": null, "e": 10431, "s": 10136, "text": "When a workflow is triggered, Luigi checks if the output of the last step exists. If not, then it checks backwards if the outputs of the predecessor steps exist. For our case, this would be train_model, impute_data, transform_data, extract_features, clean_data, make_dataset and download_data ." }, { "code": null, "e": 10647, "s": 10431, "text": "If an output of a task from any step of the flow exists Luigi resumes the flow where it has left of. This is a very useful and important trait to prevent your ML pipeline from crashing when it contains partial data." }, { "code": null, "e": 10751, "s": 10647, "text": "Now we know the essential elements of Luigi and Docker we can move forward with completing the picture!" }, { "code": null, "e": 10848, "s": 10751, "text": "We will put the pieces of Docker and Luigi in the docker-compose.yml and orchestrator directory." }, { "code": null, "e": 11253, "s": 10848, "text": "The utility functions provided by the awesome engineers of Data Revenue has enabled me to connect the pieces of Docker and Luigi. Functions and classes available in the util.py played an important role that connected Docker and Luigi for the wine rating predictor. For example, DockerTask — the object that we pass as a parameter between the tasks — is not available as a parameter in the Luigi normally." }, { "code": null, "e": 11428, "s": 11253, "text": "First, let’s have a look at task.py in the orchestrator directory where I built the automation flow using utilities. Then, let’s understand the purpose of docker-compose.yml." }, { "code": null, "e": 11906, "s": 11428, "text": "Luigi Parameter: Each task starts with a LuigiParameter object where we specify the input/output files and directories of the task. For example, the last task EvaluateModel where we evaluate the ML model with the test set takes the test_features,test_target and the trained model file (model.sav) as an input LuigiParameter. Since this task creates multiple files as output (PredictionsVSActuals.png and FeatureImportances.png) we also define a SUCCESS flag to mimic atomicity." }, { "code": null, "e": 11974, "s": 11906, "text": "Image: We define which Docker Image to use to create the container." }, { "code": null, "e": 12124, "s": 11974, "text": "Dependent Task: If there are any dependent tasks, define them here with the requires() method. The dependent task of the EvaluateModel is TrainModel." }, { "code": null, "e": 12278, "s": 12124, "text": "Command: The command to be executed by the container. Here command calls the source code available in the evaluate_model.py with the relevant parameters." }, { "code": null, "e": 12384, "s": 12278, "text": "Output: The output() method returns one or more Target objects (either the output file or a SUCCESS flag)" }, { "code": null, "e": 12546, "s": 12384, "text": "Recall that source codes for each step of the flow is available in the respective directory as Python file. Let’s have a look at the source code of train_model :" }, { "code": null, "e": 12674, "s": 12546, "text": "After defining the helper functions convert_features_to_array and convert_target_to_array, we defined necessary click commands." }, { "code": null, "e": 12723, "s": 12674, "text": "Click, as defined in the official documentation:" }, { "code": null, "e": 12847, "s": 12723, "text": "It is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary." }, { "code": null, "e": 13175, "s": 12847, "text": "We used Click to be able to pass the arguments to the python scripts from the command line. Finally, we train the model with the fine-tuned parameters that we have decided in the Perform Hyperparameter Tuning on the Selected Model step on the training dataset. Finally, we save the trained model in model.sav file as an output." }, { "code": null, "e": 13254, "s": 13175, "text": "The official definition for Docker Compose from the Docker Docs is as follows:" }, { "code": null, "e": 13502, "s": 13254, "text": "Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration." }, { "code": null, "e": 13677, "s": 13502, "text": "This definition suits to our case since we run the automation flow on 9 containers including base_docker. You can read more about the use and commands of docker-compose here." }, { "code": null, "e": 13917, "s": 13677, "text": "The important part for us here the command to run Luigi tasks is written here, so when we run containers through docker-compose, it will trigger the automation flow with the luigi — module task EvaluateModel-scheduler-host luigiid command." }, { "code": null, "e": 14092, "s": 13917, "text": "This is the moment of truth! We are going to run the automation flow and automate the 9-Step ML Pipeline. It is the last of the last step, stick with it for one more minute 😉" }, { "code": null, "e": 14108, "s": 14092, "text": "For me this is:" }, { "code": null, "e": 14149, "s": 14108, "text": "cd GitHub/Wine-Rating-Predictor-ML-Model" }, { "code": null, "e": 14292, "s": 14149, "text": "Instead of building multiple Docker Containers one by one, we are going to use a shell script to build Docker Containers: build-task-images.sh" }, { "code": null, "e": 14319, "s": 14292, "text": "./build-task-images.sh 0.1" }, { "code": null, "e": 14436, "s": 14319, "text": "The below message shows that Containers are built successfully. So we are good to go for triggering automation flow." }, { "code": null, "e": 14490, "s": 14436, "text": "Successfully tagged code-challenge/evaluate-model:0.1" }, { "code": null, "e": 14524, "s": 14490, "text": "We will trigger the workflow with" }, { "code": null, "e": 14555, "s": 14524, "text": "docker-compose up orchestrator" }, { "code": null, "e": 14664, "s": 14555, "text": "Upon writing this command, Luigi checks whether each task is complete and outputs the following information:" }, { "code": null, "e": 16639, "s": 14664, "text": "Checking if EvaluateModel( no_remove_finished=False, in_test_features_csv=/usr/share/data/interim/test_features.csv, in_test_target_csv=/usr/share/data/interim/test_target.csv, in_trained_model=/usr/share/data/output/model.sav, out_dir=/usr/share/data/output/, flag=.SUCCESS_EvaluateModel) is completeChecking if TrainModel( no_remove_finished=False, in_train_features_csv=/usr/share/data/interim/train_features.csv, in_train_target_csv=/usr/share/data/interim/train_target.csv, out_dir=/usr/share/data/output/) is completeChecking if ImputeData( no_remove_finished=False, in_train_csv=/usr/share/data/interim/train_transformed.csv, in_test_csv=/usr/share/data/interim/test_transformed.csv, out_dir=/usr/share/data/interim/, flag=.SUCCESS_ImputeData) is completeChecking if TransformData( no_remove_finished=False, in_train_csv=/usr/share/data/interim/train_features_extracted.csv, in_test_csv=/usr/share/data/interim/test_features_extracted.csv, out_dir=/usr/share/data/interim/, flag=.SUCCESS_TransformData) is completeChecking if ExtractFeatures( no_remove_finished=False, in_train_csv=/usr/share/data/interim/train_cleaned.csv, in_test_csv=/usr/share/data/interim/test_cleaned.csv, out_dir=/usr/share/data/interim/, flag=.SUCCESS_ExtractFeatures) is completeChecking if CleanData( no_remove_finished=False, in_train_csv=/usr/share/data/interim/train.csv, in_test_csv=/usr/share/data/interim/test.csv, out_dir=/usr/share/data/interim/, flag=.SUCCESS_CleanData) is completeChecking if MakeDatasets( no_remove_finished=False, in_csv=/usr/share/data/raw/wine_dataset.csv, out_dir=/usr/share/data/interim/, flag=.SUCCESS_MakeDatasets) is completeChecking if DownloadData( no_remove_finished=False, fname=wine_dataset, out_dir=/usr/share/data/raw/, url=https://github.com/datarevenue-berlin/code-challenge-2019/releases/download/0.1.0/dataset_sampled.csv) is complete" }, { "code": null, "e": 16714, "s": 16639, "text": "Then runs the task in one by one. Another important information for us is:" }, { "code": null, "e": 16774, "s": 16714, "text": "INFO:evaluate-model:Mean square error of the model is: 4.95" }, { "code": null, "e": 16810, "s": 16774, "text": "After a successful run you see a 🙂:" }, { "code": null, "e": 17149, "s": 16810, "text": "Bonus Points: Let’s see how Luigi resumes the flow where it has left ofLet’s say you prepared training datasets and run the automation flow, then you will build the next steps afterwards starting with the training the model. Luigi won’t repeat successfully run previous steps and only runs TrainModel and EvaluateModel tasks in that case." }, { "code": null, "e": 17166, "s": 17149, "text": "I would say Wow!" }, { "code": null, "e": 17229, "s": 17166, "text": "It was quite a journey spanning over 4 articles and a month ⛵️" }, { "code": null, "e": 17359, "s": 17229, "text": "We started from the very beginning and analyzed every step of the 9-step ML pipeline through the first, second and third article." }, { "code": null, "e": 17382, "s": 17359, "text": "towardsdatascience.com" }, { "code": null, "e": 17405, "s": 17382, "text": "towardsdatascience.com" }, { "code": null, "e": 17428, "s": 17405, "text": "towardsdatascience.com" }, { "code": null, "e": 17722, "s": 17428, "text": "In this last article, we introduced the relevant elements of Docker and Luigi and explained their importance and use for the wine rating predictor. We completed the last missing piece of our comprehensive pipeline and did a dry run of an ML solution — just as if it runs on production systems." }, { "code": null, "e": 17885, "s": 17722, "text": "I think it is time to thank my significant other Serkan Durusoy. He has been the most precious mentor, editor and study buddy I had in my data science expedition!" }, { "code": null, "e": 18084, "s": 17885, "text": "He helped me to overcome the ups and downs of changing a career. Also, I want to acknowledge his support to complete this article series as well as the grit he provided for me. Thank you, my dear ❤️" }, { "code": null, "e": 18195, "s": 18084, "text": "Thanks for reading 🙂 Please feel free to use this pipeline, the code and the repository for your own projects." }, { "code": null, "e": 18293, "s": 18195, "text": "For comments or constructive feedback, you can reach out to me on responses, Twitter or Linkedin!" }, { "code": null, "e": 18428, "s": 18293, "text": "Before we go, I also want to share some of the useful resources that I used to prepare for this project. See you in the next article 👋" }, { "code": null, "e": 18481, "s": 18428, "text": "Scale Your Machine Learning Pipeline by Data Revenue" }, { "code": null, "e": 18528, "s": 18481, "text": "Docker for Beginners: Full Course by KodeKloud" }, { "code": null, "e": 18597, "s": 18528, "text": "Build a Docker Container with Your Machine Learning Model by Tina Bu" }, { "code": null, "e": 18617, "s": 18597, "text": "Luigi Documentation" }, { "code": null, "e": 18638, "s": 18617, "text": "Docker Documentation" } ]
How to set the left padding of an element with JavaScript?
Use the paddingLeft property in JavaScript to set the left padding. You can try to run the following code to return the left padding of an element with JavaScript − <!DOCTYPE html> <html> <head> <style> #box { border: 2px solid #FF0000; width: 150px; height: 70px; } </style> </head> <body> <div id = "box">This is demo text.</div> <br><br> <button type = "button" onclick = "display()">Left padding</button> <script> function display() { document.getElementById("box").style.paddingLeft = "100px"; } </script> </body> </html>
[ { "code": null, "e": 1227, "s": 1062, "text": "Use the paddingLeft property in JavaScript to set the left padding. You can try to run the following code to return the left padding of an element with JavaScript −" }, { "code": null, "e": 1728, "s": 1227, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n #box {\n border: 2px solid #FF0000;\n width: 150px;\n height: 70px;\n }\n </style>\n </head>\n\n <body>\n <div id = \"box\">This is demo text.</div>\n <br><br>\n <button type = \"button\" onclick = \"display()\">Left padding</button>\n <script>\n function display() {\n document.getElementById(\"box\").style.paddingLeft = \"100px\";\n }\n </script>\n </body>\n</html>" } ]
Java Examples - Use Enumeration to display HashTable
How to use enumeration to display contents of HashTable ? Following example uses hasMoreElements & nestElement Methods of Enumeration Class to display the contents of the HashTable. import java.util.Enumeration; import java.util.Hashtable; public class Main { public static void main(String[] args) { Hashtable ht = new Hashtable(); ht.put("1", "One"); ht.put("2", "Two"); ht.put("3", "Three"); Enumeration e = ht.elements(); while(e.hasMoreElements()) { System.out.println(e.nextElement()); } } } The above code sample will produce the following result. Three Two One Print Add Notes Bookmark this page
[ { "code": null, "e": 2126, "s": 2068, "text": "How to use enumeration to display contents of HashTable ?" }, { "code": null, "e": 2250, "s": 2126, "text": "Following example uses hasMoreElements & nestElement Methods of Enumeration Class to display the contents of the HashTable." }, { "code": null, "e": 2631, "s": 2250, "text": "import java.util.Enumeration;\nimport java.util.Hashtable;\n\npublic class Main {\n public static void main(String[] args) {\n Hashtable ht = new Hashtable();\n ht.put(\"1\", \"One\");\n ht.put(\"2\", \"Two\");\n ht.put(\"3\", \"Three\");\n Enumeration e = ht.elements();\n \n while(e.hasMoreElements()) {\n System.out.println(e.nextElement());\n }\n }\n}" }, { "code": null, "e": 2688, "s": 2631, "text": "The above code sample will produce the following result." }, { "code": null, "e": 2703, "s": 2688, "text": "Three\nTwo\nOne\n" }, { "code": null, "e": 2710, "s": 2703, "text": " Print" }, { "code": null, "e": 2721, "s": 2710, "text": " Add Notes" } ]
Scala Collections - HashSet
Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duplicate elements. HashSet implements immutable sets and uses hash table. Elements insertion order is not preserved. The following is the syntax for declaring an HashSet variable. var z : HashSet[String] = HashSet("Zara","Nuha","Ayan") Here, z is declared as an hash-set of Strings which has three members. Values can be added by using commands like the following − var myList1: HashSet[String] = myList + "Naira"; Below is an example program of showing how to create, initialize and process HashSet − import scala.collection.immutable.HashSet object Demo { def main(args: Array[String]) = { var mySet: HashSet[String] = HashSet("Zara","Nuha","Ayan"); // Add an element var mySet1: HashSet[String] = mySet + "Naira"; // Remove an element var mySet2: HashSet[String] = mySet - "Nuha"; // Create empty set var mySet3: HashSet[String] = HashSet.empty[String]; println(mySet); println(mySet1); println(mySet2); println(mySet3); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo HashSet(Zara, Nuha, Ayan) HashSet(Zara, Nuha, Ayan, Naira) HashSet(Zara, Ayan) HashSet() 82 Lectures 7 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 52 Lectures 1.5 hours Bigdata Engineer 76 Lectures 5.5 hours Bigdata Engineer 69 Lectures 7.5 hours Bigdata Engineer 46 Lectures 4.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 3130, "s": 2882, "text": "Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duplicate elements. HashSet implements immutable sets and uses hash table. Elements insertion order is not preserved." }, { "code": null, "e": 3193, "s": 3130, "text": "The following is the syntax for declaring an HashSet variable." }, { "code": null, "e": 3250, "s": 3193, "text": "var z : HashSet[String] = HashSet(\"Zara\",\"Nuha\",\"Ayan\")\n" }, { "code": null, "e": 3380, "s": 3250, "text": "Here, z is declared as an hash-set of Strings which has three members. Values can be added by using commands like the following −" }, { "code": null, "e": 3430, "s": 3380, "text": "var myList1: HashSet[String] = myList + \"Naira\";\n" }, { "code": null, "e": 3517, "s": 3430, "text": "Below is an example program of showing how to create, initialize and process HashSet −" }, { "code": null, "e": 4018, "s": 3517, "text": "import scala.collection.immutable.HashSet\nobject Demo {\n def main(args: Array[String]) = {\n var mySet: HashSet[String] = HashSet(\"Zara\",\"Nuha\",\"Ayan\");\n // Add an element\n var mySet1: HashSet[String] = mySet + \"Naira\";\n // Remove an element\n var mySet2: HashSet[String] = mySet - \"Nuha\";\n // Create empty set\n var mySet3: HashSet[String] = HashSet.empty[String];\n println(mySet);\n println(mySet1);\n println(mySet2);\n println(mySet3);\t \n }\n}" }, { "code": null, "e": 4125, "s": 4018, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 4159, "s": 4125, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 4249, "s": 4159, "text": "HashSet(Zara, Nuha, Ayan)\nHashSet(Zara, Nuha, Ayan, Naira)\nHashSet(Zara, Ayan)\nHashSet()\n" }, { "code": null, "e": 4282, "s": 4249, "text": "\n 82 Lectures \n 7 hours \n" }, { "code": null, "e": 4301, "s": 4282, "text": " Arnab Chakraborty" }, { "code": null, "e": 4336, "s": 4301, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4357, "s": 4336, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 4392, "s": 4357, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4410, "s": 4392, "text": " Bigdata Engineer" }, { "code": null, "e": 4445, "s": 4410, "text": "\n 76 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4463, "s": 4445, "text": " Bigdata Engineer" }, { "code": null, "e": 4498, "s": 4463, "text": "\n 69 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4516, "s": 4498, "text": " Bigdata Engineer" }, { "code": null, "e": 4551, "s": 4516, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4574, "s": 4551, "text": " Stone River ELearning" }, { "code": null, "e": 4581, "s": 4574, "text": " Print" }, { "code": null, "e": 4592, "s": 4581, "text": " Add Notes" } ]
How to Install Scikit-Learn in Windows? - GeeksforGeeks
21 Sep, 2021 Scikit Learn is an open-source Python library that implements a range of machine learning, preprocessing, cross-validation, and visualization algorithms using a unified interface. In this article, we will look into how to install the Scikit-Learn library in Windows. The only thing that you need for installing the Twisted framework on Windows are: Python PIP or conda (Depending upon user preference) If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command: conda install -c conda-forge scikit-learn Type y for yes when prompted. You will get a similar message once the installation is complete: Make sure you follow the best practices for installation using conda as: Use an environment for installation rather than in the base environment using the below command: conda create -n my-env conda activate my-env Note: If your preferred method of installation is conda-forge, use the below command: conda config --env --add channels conda-forge Users who prefer to use pip can use the below command to install the Scikit-Learn library on Windows: pip install scikit-learn You will get a similar message once the installation is complete: To verify if Scikit learn library has been successfully installed in your system run the below command: python -m pip show scikit-learn If the installation is successful, you’ll get the following message: Blogathon-2021 how-to-install Picked Python scikit-module Blogathon How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Import JSON Data into SQL Server? How to Create a Table With Multiple Foreign Keys in SQL? How to Install Tkinter in Windows? SQL Query to Create Table With a Primary Key SQL Query to Convert Datetime to Date How to Install PIP on Windows ? How to Find the Wi-Fi Password Using CMD in Windows? How to install Jupyter Notebook on Windows? How to Align Text in HTML? How to Install OpenCV for Python on Windows?
[ { "code": null, "e": 24812, "s": 24784, "text": "\n21 Sep, 2021" }, { "code": null, "e": 24992, "s": 24812, "text": "Scikit Learn is an open-source Python library that implements a range of machine learning, preprocessing, cross-validation, and visualization algorithms using a unified interface." }, { "code": null, "e": 25079, "s": 24992, "text": "In this article, we will look into how to install the Scikit-Learn library in Windows." }, { "code": null, "e": 25161, "s": 25079, "text": "The only thing that you need for installing the Twisted framework on Windows are:" }, { "code": null, "e": 25168, "s": 25161, "text": "Python" }, { "code": null, "e": 25214, "s": 25168, "text": "PIP or conda (Depending upon user preference)" }, { "code": null, "e": 25336, "s": 25214, "text": "If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command:" }, { "code": null, "e": 25379, "s": 25336, "text": "conda install -c conda-forge scikit-learn " }, { "code": null, "e": 25409, "s": 25379, "text": "Type y for yes when prompted." }, { "code": null, "e": 25475, "s": 25409, "text": "You will get a similar message once the installation is complete:" }, { "code": null, "e": 25548, "s": 25475, "text": "Make sure you follow the best practices for installation using conda as:" }, { "code": null, "e": 25645, "s": 25548, "text": "Use an environment for installation rather than in the base environment using the below command:" }, { "code": null, "e": 25690, "s": 25645, "text": "conda create -n my-env\nconda activate my-env" }, { "code": null, "e": 25776, "s": 25690, "text": "Note: If your preferred method of installation is conda-forge, use the below command:" }, { "code": null, "e": 25822, "s": 25776, "text": "conda config --env --add channels conda-forge" }, { "code": null, "e": 25924, "s": 25822, "text": "Users who prefer to use pip can use the below command to install the Scikit-Learn library on Windows:" }, { "code": null, "e": 25949, "s": 25924, "text": "pip install scikit-learn" }, { "code": null, "e": 26015, "s": 25949, "text": "You will get a similar message once the installation is complete:" }, { "code": null, "e": 26119, "s": 26015, "text": "To verify if Scikit learn library has been successfully installed in your system run the below command:" }, { "code": null, "e": 26151, "s": 26119, "text": "python -m pip show scikit-learn" }, { "code": null, "e": 26220, "s": 26151, "text": "If the installation is successful, you’ll get the following message:" }, { "code": null, "e": 26235, "s": 26220, "text": "Blogathon-2021" }, { "code": null, "e": 26250, "s": 26235, "text": "how-to-install" }, { "code": null, "e": 26257, "s": 26250, "text": "Picked" }, { "code": null, "e": 26278, "s": 26257, "text": "Python scikit-module" }, { "code": null, "e": 26288, "s": 26278, "text": "Blogathon" }, { "code": null, "e": 26295, "s": 26288, "text": "How To" }, { "code": null, "e": 26314, "s": 26295, "text": "Installation Guide" }, { "code": null, "e": 26412, "s": 26314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26453, "s": 26412, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 26510, "s": 26453, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 26545, "s": 26510, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 26590, "s": 26545, "text": "SQL Query to Create Table With a Primary Key" }, { "code": null, "e": 26628, "s": 26590, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 26660, "s": 26628, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26713, "s": 26660, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 26757, "s": 26713, "text": "How to install Jupyter Notebook on Windows?" }, { "code": null, "e": 26784, "s": 26757, "text": "How to Align Text in HTML?" } ]
C library function - log()
The C library function double log(double x) returns the natural logarithm (base-e logarithm) of x. Following is the declaration for log() function. double log(double x) x − This is the floating point value. x − This is the floating point value. This function returns natural logarithm of x. The following example shows the usage of log() function. #include <stdio.h> #include <math.h> int main () { double x, ret; x = 2.7; /* finding log(2.7) */ ret = log(x); printf("log(%lf) = %lf", x, ret); return(0); } Let us compile and run the above program that will produce the following result − log(2.700000) = 0.993252 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2106, "s": 2007, "text": "The C library function double log(double x) returns the natural logarithm (base-e logarithm) of x." }, { "code": null, "e": 2155, "s": 2106, "text": "Following is the declaration for log() function." }, { "code": null, "e": 2176, "s": 2155, "text": "double log(double x)" }, { "code": null, "e": 2214, "s": 2176, "text": "x − This is the floating point value." }, { "code": null, "e": 2252, "s": 2214, "text": "x − This is the floating point value." }, { "code": null, "e": 2298, "s": 2252, "text": "This function returns natural logarithm of x." }, { "code": null, "e": 2355, "s": 2298, "text": "The following example shows the usage of log() function." }, { "code": null, "e": 2538, "s": 2355, "text": "#include <stdio.h>\n#include <math.h>\n\nint main () {\n double x, ret;\n x = 2.7;\n\n /* finding log(2.7) */\n ret = log(x);\n printf(\"log(%lf) = %lf\", x, ret);\n \n return(0);\n}" }, { "code": null, "e": 2620, "s": 2538, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 2646, "s": 2620, "text": "log(2.700000) = 0.993252\n" }, { "code": null, "e": 2679, "s": 2646, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2694, "s": 2679, "text": " Nishant Malik" }, { "code": null, "e": 2729, "s": 2694, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2744, "s": 2729, "text": " Nishant Malik" }, { "code": null, "e": 2779, "s": 2744, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 2793, "s": 2779, "text": " Asif Hussain" }, { "code": null, "e": 2826, "s": 2793, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2844, "s": 2826, "text": " Richa Maheshwari" }, { "code": null, "e": 2879, "s": 2844, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2898, "s": 2879, "text": " Vandana Annavaram" }, { "code": null, "e": 2931, "s": 2898, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 2943, "s": 2931, "text": " Amit Diwan" }, { "code": null, "e": 2950, "s": 2943, "text": " Print" }, { "code": null, "e": 2961, "s": 2950, "text": " Add Notes" } ]
Spring Batch - Environment
In this chapter, we will explain how to set Spring Batch environment in Eclipse IDE. Before proceeding with the installation, ensure that you have installed Eclipse in your system. If not, download and install Eclipse in your system. For more information on Eclipse, please refer our Eclipse Tutorial. Follow the steps given below to set Spring Batch environment on Eclipse. Step 1 − Install Eclipse and open a New Project as shown in the following screenshot. Step 2 − Create a Sample Spring Batch project as shown below. Step 3 − Right-click on the project and convert it into a Maven project as shown below. Once you convert it into Maven project, it will give you a Pom.xml where you need to mention the required dependencies. Thereafter, the jar files of those will be automatically downloaded into your project. Step 4 − Now, in the pom.xml of the project, copy and paste the following content (dependencies for spring batch application) and refresh the project. <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>SpringBatchSample</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>SpringBatchExample</name> <url>http://maven.apache.org</url> <properties> <jdk.version>1.8</jdk.version> <spring.version>5.3.14</spring.version> <spring.batch.version>4.3.4</spring.batch.version> <mysql.driver.version>5.1.25</mysql.driver.version> <junit.version>4.11</junit.version> </properties> <dependencies> <!-- Spring Core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring jdbc, for database --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring XML to/back object --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <!-- MySQL database driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.driver.version}</version> </dependency> <!-- Spring Batch dependencies --> <dependency> <groupId>org.springframework.batch</groupId> <artifactId>spring-batch-core</artifactId> <version>${spring.batch.version}</version> </dependency> <dependency> <groupId>org.springframework.batch</groupId> <artifactId>spring-batch-infrastructure</artifactId> <version>${spring.batch.version}</version> </dependency> <!-- Spring Batch unit test --> <dependency> <groupId>org.springframework.batch</groupId> <artifactId>spring-batch-test</artifactId> <version>${spring.batch.version}</version> </dependency> <!-- Junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>spring-batch</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <downloadSources>true</downloadSources> <downloadJavadocs>false</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> </configuration> </plugin> </plugins> </build> </project> 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": 2162, "s": 1928, "text": "In this chapter, we will explain how to set Spring Batch environment in Eclipse IDE. Before proceeding with the installation, ensure that you have installed Eclipse in your system. If not, download and install Eclipse in your system." }, { "code": null, "e": 2230, "s": 2162, "text": "For more information on Eclipse, please refer our Eclipse Tutorial." }, { "code": null, "e": 2303, "s": 2230, "text": "Follow the steps given below to set Spring Batch environment on Eclipse." }, { "code": null, "e": 2389, "s": 2303, "text": "Step 1 − Install Eclipse and open a New Project as shown in the following screenshot." }, { "code": null, "e": 2451, "s": 2389, "text": "Step 2 − Create a Sample Spring Batch project as shown below." }, { "code": null, "e": 2746, "s": 2451, "text": "Step 3 − Right-click on the project and convert it into a Maven project as shown below. Once you convert it into Maven project, it will give you a Pom.xml where you need to mention the required dependencies. Thereafter, the jar files of those will be automatically downloaded into your project." }, { "code": null, "e": 2897, "s": 2746, "text": "Step 4 − Now, in the pom.xml of the project, copy and paste the following content (dependencies for spring batch application) and refresh the project." }, { "code": null, "e": 6356, "s": 2897, "text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/maven-v4_0_0.xsd\"> \n <modelVersion>4.0.0</modelVersion> \n <groupId>com.tutorialspoint</groupId> \n <artifactId>SpringBatchSample</artifactId> \n <packaging>jar</packaging> \n <version>1.0-SNAPSHOT</version> \n <name>SpringBatchExample</name>\n <url>http://maven.apache.org</url> \n\n <properties> \n <jdk.version>1.8</jdk.version> \n <spring.version>5.3.14</spring.version> \n <spring.batch.version>4.3.4</spring.batch.version> \n <mysql.driver.version>5.1.25</mysql.driver.version> \n <junit.version>4.11</junit.version> \n </properties> \n\n <dependencies> \n <!-- Spring Core --> \n <dependency> \n <groupId>org.springframework</groupId> \n <artifactId>spring-core</artifactId> \n <version>${spring.version}</version> \n </dependency> \n\n <!-- Spring jdbc, for database --> \n <dependency> \n <groupId>org.springframework</groupId> \n <artifactId>spring-jdbc</artifactId> \n <version>${spring.version}</version> \n </dependency> \n\n <!-- Spring XML to/back object --> \n <dependency> \n <groupId>org.springframework</groupId> \n <artifactId>spring-oxm</artifactId> \n <version>${spring.version}</version> \n </dependency> \n\n <!-- MySQL database driver --> \n <dependency> \n <groupId>mysql</groupId> \n <artifactId>mysql-connector-java</artifactId>\n <version>${mysql.driver.version}</version> \n </dependency> \n\n <!-- Spring Batch dependencies --> \n <dependency> \n <groupId>org.springframework.batch</groupId> \n <artifactId>spring-batch-core</artifactId> \n <version>${spring.batch.version}</version> \n </dependency> \n\n <dependency> \n <groupId>org.springframework.batch</groupId> \n <artifactId>spring-batch-infrastructure</artifactId> \n <version>${spring.batch.version}</version> \n </dependency> \n\n <!-- Spring Batch unit test --> \n <dependency> \n <groupId>org.springframework.batch</groupId> \n <artifactId>spring-batch-test</artifactId> \n <version>${spring.batch.version}</version> \n </dependency> \n\n <!-- Junit --> \n <dependency> \n <groupId>junit</groupId> \n <artifactId>junit</artifactId> \n <version>${junit.version}</version> \n <scope>test</scope> \n </dependency> \n </dependencies> \n\n <build> \n <finalName>spring-batch</finalName> \n <plugins> \n <plugin> \n <groupId>org.apache.maven.plugins</groupId> \n <artifactId>maven-eclipse-plugin</artifactId>\n <version>2.9</version> \n <configuration> \n <downloadSources>true</downloadSources> \n <downloadJavadocs>false</downloadJavadocs> \n </configuration> \n </plugin> \n \n <plugin> \n <groupId>org.apache.maven.plugins</groupId> \n <artifactId>maven-compiler-plugin</artifactId> \n <version>2.3.2</version> \n <configuration> \n <source>${jdk.version}</source> \n <target>${jdk.version}</target> \n </configuration> \n </plugin> \n </plugins> \n </build> \n</project> " }, { "code": null, "e": 6390, "s": 6356, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 6404, "s": 6390, "text": " Karthikeya T" }, { "code": null, "e": 6437, "s": 6404, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 6452, "s": 6437, "text": " Chaand Sheikh" }, { "code": null, "e": 6487, "s": 6452, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6499, "s": 6487, "text": " Senol Atac" }, { "code": null, "e": 6534, "s": 6499, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6546, "s": 6534, "text": " Senol Atac" }, { "code": null, "e": 6581, "s": 6546, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6593, "s": 6581, "text": " Senol Atac" }, { "code": null, "e": 6626, "s": 6593, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 6638, "s": 6626, "text": " Senol Atac" }, { "code": null, "e": 6645, "s": 6638, "text": " Print" }, { "code": null, "e": 6656, "s": 6645, "text": " Add Notes" } ]
How to integrate Quickbooks with Python | by hotglue | Towards Data Science
If you’re a B2B developer building a product, one of the earliest product development phases is creating a data integration pipeline to import customer data. In this article, I’ll show you how to leverage Singer’s tap-quickbooks to extract data from Quickbooks. From there I’ll walk you through how to parse the JSON output data from Singer using target-csv and standardize it using a simple Python script. The code for these examples is available publicly on GitHub here, along with descriptions that mirror the information I’ll walk you through. These samples rely on a few open source Python packages: tap-quickbooks: a Singer tap to extract data from Quickbooks. More info on GitHub. We’ll be using the hotglue fork because it has version compatibility with target-csv. target-csv: a Singer target which converts input JSON data to CSV files. More info on GitHub. We’ll use the hotglue fork which uses updated dependencies. singer-discover: an open source utility to select streams from a Singer catalog. More info on GitHub. pandas: a widely used open source data analysis and manipulation tool. More info on their site and PyPi. gluestick: a small open source Python package containing util functions for ETL maintained by the hotglue team. More info on PyPi and GitHub. Without further ado, let’s dive in! Singer taps tend to have a lot of dependency conflicts with each other — to avoid dependency hell, I highly recommend running through this example in a virtual environment. # Install JupyterLab if you don't have it already$ pip3 install jupyterlab# Create the virtual env$ python3 -m venv ~/env/tap-quickbooks# Activate the virtual env$ source ~/env/tap-quickbooks/bin/activate# Install the dependencies$ pip install git+https://github.com/hotgluexyz/tap-quickbooks.git git+https://github.com/hotgluexyz/target-csv.git gluestick pandas ipykernel singer-python==5.3.1 requests==2.20.0 xmltodict==0.11.0 jsonpath-ng==1.4.3 pytz==2018.4 attrs==20.2.0# Make our venv available to JupyterLab$ python -m ipykernel install --user --name=tap-quickbooks# Create a workspace for this$ mkdir quickbooks-integration# Enter the directory$ cd quickbooks-integration These commands may vary depending on your OS and Python version. For more info on venvs with Jupyter, check out this TowardsDataScience article. First off, you’re going to need Quickbooks OAuth credentials. This process is already well-documented by Quickbooks, so I’ll assume you can follow that guide. Now we have to create a Singer config. This will specify our OAuth credentials and some Singer specific settings. Their example config is of the following format: { "client_id": "secret_client_id", "client_secret": "secret_client_secret", "refresh_token": "abc123", "start_date": "2017-11-02T00:00:00Z", "api_type": "BULK", "select_fields_by_default": true, "sandbox": true, "realmId": "123456789"} Fill in your credentials, and save this to a file called config.json in the local directory. The first step of getting data from Quickbooks is to figure out what data is actually available. Singer taps offer a discover command which prints a JSON object describing all of this. Let’s run it now: # Do the Singer discover and save to catalog.json$ tap-quickbooks --config config.json --discover > catalog.json If this worked successfully, your catalog.json should resemble this: # Check discover output$ less catalog.json{ "streams": [ { "stream": "Invoice", "tap_stream_id": "Invoice", "schema": { "type": "object", "additionalProperties": false, "properties": { "AllowIPNPayment": { "type": [ "boolean", "null" ] },... From here, we want to select what objects we actually want to sync. We’ll use the singer-discover utility we downloaded earlier for this. # Switch singer-python version to meet singer-discover dep$ pip install https://github.com/chrisgoddard/singer-discover/archive/master.zip singer-python==5.4.1 prompt_toolkit==1.0.14# Build our selected catalog$ singer-discover --input catalog.json --output properties.json This will launch an interactive utility to select what streams (objects) you want from Quickbooks. I am going to select Invoice (space) and press enter. This will prompt you the option to select specific fields. I’ll accept the default and press enter. This should give you the following output INFO Catalog configuration starting...? Select Streams [Invoice]? Select fields from stream: `Invoice` done (18 selections)INFO Catalog configuration saved. We can now finally get the data from Quickbooks using the files we’ve generated, using the following command: # Switch singer-python version to meet tap-quickbooks dep$ pip install singer-python==5.3.1# Get Invoice data from Quickbooks and save as a CSV$ tap-quickbooks --config config.json --properties properties.json | target-csv > state.json This will output two files: the CSV containing the data from Quickbooks (something like Invoice-20210128T125258.csv) a JSON file state.jsontelling tap-quickbookswhat it last synced. This can be fed back to the tap-quickbooks in the future to avoid syncing the same data again. Finally! We’ve pulled our data from Quickbooks! Not too bad, right? If you wanted to use this in production, you’d have to automate the process of creating the properties.json and likely stick all of this into a Docker container (very similar to how hotglue and Airbyte work). You can follow along with this part directly in the Jupyter Notebook (feel free to clone and try your own transformations). github.com Let’s take a peek at what tap-quickbooks gave us. Not too bad, right? Let’s load the data into a Jupyter Notebook and clean the data up a bit. For this article, I’ll keep it very simple but if you’d like to learn about other ETL operations check out my TowardsDataScience article. Let’s launch Jupyter # You may have some issues in Jupyter if you don't do this$ pip install prompt-toolkit==3.0.14# Deactivate the virtualenv$ deactivate# Start Jupyter Lab$ jupyter lab This should start Jupyter in the current directory and open the browser. If all the setup commands worked, you should see tap-quickbooks available under the Notebook sections. Let’s create a new Notebook with the tap-quickbooks kernel. I am going to name mine quickbooks.ipynb Let’s use the gluestick and pandas libraries to load the data and take a look. Our goal here is to be able to easily manipulate the output from tap-quickbooks. Now that we have the data in a Panda’s dataframe, you can transform it however you like. Of course, you’re not limited to use Pandas — you could use Spark, or any other Python based data transformation tool you like. This is really just a starting point for a data integration pipeline. If you’re looking to take this further (orchestrating this on the cloud, connecting it to your product) it’s worth taking a look at developer focused tools like hotglue and Meltano, both of which aim to make data integration easier for developers. I recently published an article on TowardsDataScience about the pros and cons of building off Singer. I would recommend checking out Airbyte before resolving to build your pipeline off Singer. Feel free to check out the open source hotglue recipes for more samples in the future. Thanks for reading! I’d love to answer any comments or questions below.
[ { "code": null, "e": 329, "s": 171, "text": "If you’re a B2B developer building a product, one of the earliest product development phases is creating a data integration pipeline to import customer data." }, { "code": null, "e": 578, "s": 329, "text": "In this article, I’ll show you how to leverage Singer’s tap-quickbooks to extract data from Quickbooks. From there I’ll walk you through how to parse the JSON output data from Singer using target-csv and standardize it using a simple Python script." }, { "code": null, "e": 719, "s": 578, "text": "The code for these examples is available publicly on GitHub here, along with descriptions that mirror the information I’ll walk you through." }, { "code": null, "e": 776, "s": 719, "text": "These samples rely on a few open source Python packages:" }, { "code": null, "e": 945, "s": 776, "text": "tap-quickbooks: a Singer tap to extract data from Quickbooks. More info on GitHub. We’ll be using the hotglue fork because it has version compatibility with target-csv." }, { "code": null, "e": 1099, "s": 945, "text": "target-csv: a Singer target which converts input JSON data to CSV files. More info on GitHub. We’ll use the hotglue fork which uses updated dependencies." }, { "code": null, "e": 1201, "s": 1099, "text": "singer-discover: an open source utility to select streams from a Singer catalog. More info on GitHub." }, { "code": null, "e": 1306, "s": 1201, "text": "pandas: a widely used open source data analysis and manipulation tool. More info on their site and PyPi." }, { "code": null, "e": 1448, "s": 1306, "text": "gluestick: a small open source Python package containing util functions for ETL maintained by the hotglue team. More info on PyPi and GitHub." }, { "code": null, "e": 1484, "s": 1448, "text": "Without further ado, let’s dive in!" }, { "code": null, "e": 1657, "s": 1484, "text": "Singer taps tend to have a lot of dependency conflicts with each other — to avoid dependency hell, I highly recommend running through this example in a virtual environment." }, { "code": null, "e": 2336, "s": 1657, "text": "# Install JupyterLab if you don't have it already$ pip3 install jupyterlab# Create the virtual env$ python3 -m venv ~/env/tap-quickbooks# Activate the virtual env$ source ~/env/tap-quickbooks/bin/activate# Install the dependencies$ pip install git+https://github.com/hotgluexyz/tap-quickbooks.git git+https://github.com/hotgluexyz/target-csv.git gluestick pandas ipykernel singer-python==5.3.1 requests==2.20.0 xmltodict==0.11.0 jsonpath-ng==1.4.3 pytz==2018.4 attrs==20.2.0# Make our venv available to JupyterLab$ python -m ipykernel install --user --name=tap-quickbooks# Create a workspace for this$ mkdir quickbooks-integration# Enter the directory$ cd quickbooks-integration" }, { "code": null, "e": 2481, "s": 2336, "text": "These commands may vary depending on your OS and Python version. For more info on venvs with Jupyter, check out this TowardsDataScience article." }, { "code": null, "e": 2640, "s": 2481, "text": "First off, you’re going to need Quickbooks OAuth credentials. This process is already well-documented by Quickbooks, so I’ll assume you can follow that guide." }, { "code": null, "e": 2803, "s": 2640, "text": "Now we have to create a Singer config. This will specify our OAuth credentials and some Singer specific settings. Their example config is of the following format:" }, { "code": null, "e": 3047, "s": 2803, "text": "{ \"client_id\": \"secret_client_id\", \"client_secret\": \"secret_client_secret\", \"refresh_token\": \"abc123\", \"start_date\": \"2017-11-02T00:00:00Z\", \"api_type\": \"BULK\", \"select_fields_by_default\": true, \"sandbox\": true, \"realmId\": \"123456789\"}" }, { "code": null, "e": 3140, "s": 3047, "text": "Fill in your credentials, and save this to a file called config.json in the local directory." }, { "code": null, "e": 3343, "s": 3140, "text": "The first step of getting data from Quickbooks is to figure out what data is actually available. Singer taps offer a discover command which prints a JSON object describing all of this. Let’s run it now:" }, { "code": null, "e": 3456, "s": 3343, "text": "# Do the Singer discover and save to catalog.json$ tap-quickbooks --config config.json --discover > catalog.json" }, { "code": null, "e": 3525, "s": 3456, "text": "If this worked successfully, your catalog.json should resemble this:" }, { "code": null, "e": 3993, "s": 3525, "text": "# Check discover output$ less catalog.json{ \"streams\": [ { \"stream\": \"Invoice\", \"tap_stream_id\": \"Invoice\", \"schema\": { \"type\": \"object\", \"additionalProperties\": false, \"properties\": { \"AllowIPNPayment\": { \"type\": [ \"boolean\", \"null\" ] },..." }, { "code": null, "e": 4131, "s": 3993, "text": "From here, we want to select what objects we actually want to sync. We’ll use the singer-discover utility we downloaded earlier for this." }, { "code": null, "e": 4405, "s": 4131, "text": "# Switch singer-python version to meet singer-discover dep$ pip install https://github.com/chrisgoddard/singer-discover/archive/master.zip singer-python==5.4.1 prompt_toolkit==1.0.14# Build our selected catalog$ singer-discover --input catalog.json --output properties.json" }, { "code": null, "e": 4658, "s": 4405, "text": "This will launch an interactive utility to select what streams (objects) you want from Quickbooks. I am going to select Invoice (space) and press enter. This will prompt you the option to select specific fields. I’ll accept the default and press enter." }, { "code": null, "e": 4700, "s": 4658, "text": "This should give you the following output" }, { "code": null, "e": 4859, "s": 4700, "text": "INFO Catalog configuration starting...? Select Streams [Invoice]? Select fields from stream: `Invoice` done (18 selections)INFO Catalog configuration saved." }, { "code": null, "e": 4969, "s": 4859, "text": "We can now finally get the data from Quickbooks using the files we’ve generated, using the following command:" }, { "code": null, "e": 5206, "s": 4969, "text": "# Switch singer-python version to meet tap-quickbooks dep$ pip install singer-python==5.3.1# Get Invoice data from Quickbooks and save as a CSV$ tap-quickbooks --config config.json --properties properties.json | target-csv > state.json" }, { "code": null, "e": 5234, "s": 5206, "text": "This will output two files:" }, { "code": null, "e": 5323, "s": 5234, "text": "the CSV containing the data from Quickbooks (something like Invoice-20210128T125258.csv)" }, { "code": null, "e": 5483, "s": 5323, "text": "a JSON file state.jsontelling tap-quickbookswhat it last synced. This can be fed back to the tap-quickbooks in the future to avoid syncing the same data again." }, { "code": null, "e": 5760, "s": 5483, "text": "Finally! We’ve pulled our data from Quickbooks! Not too bad, right? If you wanted to use this in production, you’d have to automate the process of creating the properties.json and likely stick all of this into a Docker container (very similar to how hotglue and Airbyte work)." }, { "code": null, "e": 5884, "s": 5760, "text": "You can follow along with this part directly in the Jupyter Notebook (feel free to clone and try your own transformations)." }, { "code": null, "e": 5895, "s": 5884, "text": "github.com" }, { "code": null, "e": 5945, "s": 5895, "text": "Let’s take a peek at what tap-quickbooks gave us." }, { "code": null, "e": 6176, "s": 5945, "text": "Not too bad, right? Let’s load the data into a Jupyter Notebook and clean the data up a bit. For this article, I’ll keep it very simple but if you’d like to learn about other ETL operations check out my TowardsDataScience article." }, { "code": null, "e": 6197, "s": 6176, "text": "Let’s launch Jupyter" }, { "code": null, "e": 6363, "s": 6197, "text": "# You may have some issues in Jupyter if you don't do this$ pip install prompt-toolkit==3.0.14# Deactivate the virtualenv$ deactivate# Start Jupyter Lab$ jupyter lab" }, { "code": null, "e": 6436, "s": 6363, "text": "This should start Jupyter in the current directory and open the browser." }, { "code": null, "e": 6640, "s": 6436, "text": "If all the setup commands worked, you should see tap-quickbooks available under the Notebook sections. Let’s create a new Notebook with the tap-quickbooks kernel. I am going to name mine quickbooks.ipynb" }, { "code": null, "e": 6800, "s": 6640, "text": "Let’s use the gluestick and pandas libraries to load the data and take a look. Our goal here is to be able to easily manipulate the output from tap-quickbooks." }, { "code": null, "e": 7017, "s": 6800, "text": "Now that we have the data in a Panda’s dataframe, you can transform it however you like. Of course, you’re not limited to use Pandas — you could use Spark, or any other Python based data transformation tool you like." }, { "code": null, "e": 7335, "s": 7017, "text": "This is really just a starting point for a data integration pipeline. If you’re looking to take this further (orchestrating this on the cloud, connecting it to your product) it’s worth taking a look at developer focused tools like hotglue and Meltano, both of which aim to make data integration easier for developers." }, { "code": null, "e": 7528, "s": 7335, "text": "I recently published an article on TowardsDataScience about the pros and cons of building off Singer. I would recommend checking out Airbyte before resolving to build your pipeline off Singer." } ]
BabylonJS - Create ScreenShot
To capture the screen on which you are presently working, it is not possible to take screenshot with high resolution using the print screen keypress. BabylonJS provides createscreenshot APIwhich helps to do so. It saves the file as png format and the quality of the image is not sacrified. To take screenshot of the screen we need to provide engine, camera and the size as shown below. BABYLON.Tools.CreateScreenshot(engine, camera, { width: 1024, height: 300 }, function (data) { var img = document.createElement("img"); img.src = data; document.body.appendChild(img); }); A button that calls the screenshot API, when a user clicks it, is put. Changes are made to the engine which is passed to the screenshot api. var engine = new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true }); It requires options like preserveDrawingBuffer and stencil set to true. Button is added as follows − ssButton = document.createElement("input"); document.body.appendChild (ssButton); Click event is added to the button above and the createscreenshot is called. It will update the screenshot at the end of the screen. The data used for image src has the screenshot url created. <!doctype html> <html> <head> <meta charset = "utf-8"> <title>BabylonJs - Basic Element-Creating Scene</title> <script src = "babylon.js"></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = "renderCanvas"></canvas> <script type = "text/javascript"> var canvas = document.getElementById("renderCanvas"); var engine = new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true }); var createScene = function() { var scene = new BABYLON.Scene(engine); // Setup environment var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(1, 0.5, 0), scene); var camera = new BABYLON.ArcRotateCamera("ArcRotateCamera", 1, 0.8, 20, new BABYLON.Vector3(0, 0, 0), scene); camera.attachControl(canvas, true); var gmat = new BABYLON.StandardMaterial("mat1", scene); gmat.alpha = 1.0; //gmat.diffuseColor = new BABYLON.Color3(1, 0, 0); var texture = new BABYLON.Texture("images/mat.jpg", scene); gmat.diffuseTexture = texture; var ground = BABYLON.MeshBuilder.CreateGround("ground", {width: 150, height:15}, scene); ground.material = gmat; var mat = new BABYLON.StandardMaterial("mat1", scene); mat.alpha = 1.0; mat.diffuseColor = new BABYLON.Color3(1, 0, 0); var texture = new BABYLON.Texture("images/rugby.jpg", scene); mat.diffuseTexture = texture; var sphere = BABYLON.MeshBuilder.CreateSphere("sphere", {diameter: 2, diameterX: 3}, scene); sphere.position= new BABYLON.Vector3(15,1,0); sphere.material = mat; var faceColors = new Array(); faceColors[1] = new BABYLON.Color4(0,1,0,1); // green front var matcone = new BABYLON.StandardMaterial("mat1", scene); matcone.alpha = 1.0; matcone.diffuseColor = new BABYLON.Color3(0.9, 0, 2); var texture = new BABYLON.Texture("images/cone.jpg", scene); matcone.diffuseTexture = texture; var cone = BABYLON.MeshBuilder.CreateCylinder("cone", {diameterTop: 0, tessellation: 4}, scene); cone.position= new BABYLON.Vector3(12,1,0); cone.material = matcone; var matplane = new BABYLON.StandardMaterial("matplane", scene); matplane.alpha = 1.0; matplane.diffuseColor = new BABYLON.Color3(0.9, 0, 2); var texture = new BABYLON.Texture("images/board.jpg", scene); matplane.diffuseTexture = texture; var plane = BABYLON.MeshBuilder.CreatePlane("plane", {width: 5, height : 5}, scene); plane.position= new BABYLON.Vector3(9,2.5,0); plane.material = matplane; var disc = BABYLON.MeshBuilder.CreateDisc("disc", {tessellation: 3}, scene); disc.position= new BABYLON.Vector3(5,1,0); var mattorus = new BABYLON.StandardMaterial("matoct", scene); mattorus.alpha = 1.0; var texture = new BABYLON.Texture("images/ring.jpg", scene); mattorus.diffuseTexture = texture; var torus = BABYLON.MeshBuilder.CreateTorus("torus", {thickness: 0.5}, scene); torus.position= new BABYLON.Vector3(3,1,0); torus.material = mattorus; var matoct = new BABYLON.StandardMaterial("matoct", scene); matoct.alpha = 1.0; var texture = new BABYLON.Texture("images/d1.png", scene); matoct.diffuseTexture = texture; var octahedron = BABYLON.MeshBuilder.CreatePolyhedron("oct", {type: 1, size: 3}, scene); octahedron.position= new BABYLON.Vector3(-2,5,0); octahedron.material = matoct; var matico = new BABYLON.StandardMaterial("matico", scene); matico.alpha = 1.0; var texture = new BABYLON.Texture("images/diamond.jpg", scene); matico.diffuseTexture = texture; var icosphere = BABYLON.MeshBuilder.CreateIcoSphere("ico", {radius: 5, radiusY: 3, subdivisions: 2}, scene); icosphere.position= new BABYLON.Vector3(-13,3,0); icosphere.material = matico; //add screenshot button var ssButton = document.getElementById("takescreenshot"); if (ssButton == null) { ssButton = document.createElement("input"); document.body.appendChild(ssButton); } ssButton.id = "takescreenshot"; ssButton.type = "button"; ssButton.style.position = "fixed"; ssButton.style.right = "0px"; ssButton.style.top = "100px"; ssButton.value = "create screenshot"; ssButton.onclick = function () { BABYLON.Tools.CreateScreenshot(engine, camera, { width: 1024, height: 300 }, function (data) { var img = document.createElement("img"); img.src = data; document.body.appendChild(img); }); }; return scene; } var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> The above line of code generates the following output − In this demo, we have used images mat.jpg, rugby.jpg, cone.jpg, board.jpg, ring.jpg, d1.png, diamond.jpg. The images are stored in the images/ folder locally and are also pasted below for reference. You can download any image of your choice and use in the demo link. Print Add Notes Bookmark this page
[ { "code": null, "e": 2473, "s": 2183, "text": "To capture the screen on which you are presently working, it is not possible to take screenshot with high resolution using the print screen keypress. BabylonJS provides createscreenshot APIwhich helps to do so. It saves the file as png format and the quality of the image is not sacrified." }, { "code": null, "e": 2569, "s": 2473, "text": "To take screenshot of the screen we need to provide engine, camera and the size as shown below." }, { "code": null, "e": 2768, "s": 2569, "text": "BABYLON.Tools.CreateScreenshot(engine, camera, { width: 1024, height: 300 }, function (data) {\n var img = document.createElement(\"img\");\n img.src = data;\n document.body.appendChild(img);\t\n});\n" }, { "code": null, "e": 2839, "s": 2768, "text": "A button that calls the screenshot API, when a user clicks it, is put." }, { "code": null, "e": 2909, "s": 2839, "text": "Changes are made to the engine which is passed to the screenshot api." }, { "code": null, "e": 3011, "s": 2909, "text": "var engine = new BABYLON.Engine(canvas, true, { \n preserveDrawingBuffer: true, stencil: true \n});\t\n" }, { "code": null, "e": 3083, "s": 3011, "text": "It requires options like preserveDrawingBuffer and stencil set to true." }, { "code": null, "e": 3112, "s": 3083, "text": "Button is added as follows −" }, { "code": null, "e": 3195, "s": 3112, "text": "ssButton = document.createElement(\"input\");\ndocument.body.appendChild (ssButton);\n" }, { "code": null, "e": 3388, "s": 3195, "text": "Click event is added to the button above and the createscreenshot is called. It will update the screenshot at the end of the screen. The data used for image src has the screenshot url created." }, { "code": null, "e": 9022, "s": 3388, "text": "<!doctype html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <title>BabylonJs - Basic Element-Creating Scene</title>\n <script src = \"babylon.js\"></script>\n <style>\n canvas {width: 100%; height: 100%;}\n </style>\n </head>\n\n <body>\n <canvas id = \"renderCanvas\"></canvas>\n <script type = \"text/javascript\">\n var canvas = document.getElementById(\"renderCanvas\");\n var engine = new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });\t\n var createScene = function() {\n var scene = new BABYLON.Scene(engine);\n \n // Setup environment\n var light = new BABYLON.HemisphericLight(\"light1\", new BABYLON.Vector3(1, 0.5, 0), scene);\n \n var camera = new BABYLON.ArcRotateCamera(\"ArcRotateCamera\", 1, 0.8, 20, new BABYLON.Vector3(0, 0, 0), scene);\n camera.attachControl(canvas, true);\n\n var gmat = new BABYLON.StandardMaterial(\"mat1\", scene);\n gmat.alpha = 1.0;\n \n //gmat.diffuseColor = new BABYLON.Color3(1, 0, 0);\n var texture = new BABYLON.Texture(\"images/mat.jpg\", scene);\n gmat.diffuseTexture = texture;\n\n var ground = BABYLON.MeshBuilder.CreateGround(\"ground\", {width: 150, height:15}, scene);\n ground.material = gmat;\n\n var mat = new BABYLON.StandardMaterial(\"mat1\", scene);\n mat.alpha = 1.0;\n mat.diffuseColor = new BABYLON.Color3(1, 0, 0);\n \n var texture = new BABYLON.Texture(\"images/rugby.jpg\", scene);\n mat.diffuseTexture = texture;\n\n var sphere = BABYLON.MeshBuilder.CreateSphere(\"sphere\", {diameter: 2, diameterX: 3}, scene);\n sphere.position= new BABYLON.Vector3(15,1,0);\n sphere.material = mat;\n\n var faceColors = new Array();\n faceColors[1] = new BABYLON.Color4(0,1,0,1); // green front\n\n var matcone = new BABYLON.StandardMaterial(\"mat1\", scene);\n matcone.alpha = 1.0;\n matcone.diffuseColor = new BABYLON.Color3(0.9, 0, 2);\n \n var texture = new BABYLON.Texture(\"images/cone.jpg\", scene);\n matcone.diffuseTexture = texture;\n\n var cone = BABYLON.MeshBuilder.CreateCylinder(\"cone\", {diameterTop: 0, tessellation: 4}, scene);\n cone.position= new BABYLON.Vector3(12,1,0);\n cone.material = matcone;\n\n var matplane = new BABYLON.StandardMaterial(\"matplane\", scene);\n matplane.alpha = 1.0;\n matplane.diffuseColor = new BABYLON.Color3(0.9, 0, 2);\n \n var texture = new BABYLON.Texture(\"images/board.jpg\", scene);\n matplane.diffuseTexture = texture;\n var plane = BABYLON.MeshBuilder.CreatePlane(\"plane\", {width: 5, height : 5}, scene);\n plane.position= new BABYLON.Vector3(9,2.5,0);\n plane.material = matplane;\t\t\n \n var disc = BABYLON.MeshBuilder.CreateDisc(\"disc\", {tessellation: 3}, scene);\n disc.position= new BABYLON.Vector3(5,1,0);\t\t\n\n var mattorus = new BABYLON.StandardMaterial(\"matoct\", scene);\n mattorus.alpha = 1.0;\n \n var texture = new BABYLON.Texture(\"images/ring.jpg\", scene);\n mattorus.diffuseTexture = texture;\n \n var torus = BABYLON.MeshBuilder.CreateTorus(\"torus\", {thickness: 0.5}, scene);\t\t\n torus.position= new BABYLON.Vector3(3,1,0);\n torus.material = mattorus;\n\n var matoct = new BABYLON.StandardMaterial(\"matoct\", scene);\n matoct.alpha = 1.0;\n \n var texture = new BABYLON.Texture(\"images/d1.png\", scene);\n matoct.diffuseTexture = texture;\n var octahedron = BABYLON.MeshBuilder.CreatePolyhedron(\"oct\", {type: 1, size: 3}, scene);\n \n octahedron.position= new BABYLON.Vector3(-2,5,0);\n octahedron.material = matoct;\t\n\n var matico = new BABYLON.StandardMaterial(\"matico\", scene);\n matico.alpha = 1.0;\n \n var texture = new BABYLON.Texture(\"images/diamond.jpg\", scene);\n matico.diffuseTexture = texture;\t\t\n \n var icosphere = BABYLON.MeshBuilder.CreateIcoSphere(\"ico\", {radius: 5, radiusY: 3, subdivisions: 2}, scene);\n icosphere.position= new BABYLON.Vector3(-13,3,0);\t\t\n icosphere.material = matico;\t\t\n \n //add screenshot button\n var ssButton = document.getElementById(\"takescreenshot\");\n if (ssButton == null) {\n ssButton = document.createElement(\"input\");\n document.body.appendChild(ssButton);\n }\n \n ssButton.id = \"takescreenshot\";\n ssButton.type = \"button\";\n ssButton.style.position = \"fixed\";\n ssButton.style.right = \"0px\";\n ssButton.style.top = \"100px\";\n ssButton.value = \"create screenshot\";\n \n ssButton.onclick = function () {\n BABYLON.Tools.CreateScreenshot(engine, camera, { width: 1024, height: 300 },\n function (data) {\n var img = document.createElement(\"img\");\n img.src = data;\n document.body.appendChild(img);\n });\n };\t\t\t\n return scene;\n }\n var scene = createScene();\n engine.runRenderLoop(function() {\n scene.render();\n });\t\n </script>\n </body>\n</html>" }, { "code": null, "e": 9078, "s": 9022, "text": "The above line of code generates the following output −" }, { "code": null, "e": 9345, "s": 9078, "text": "In this demo, we have used images mat.jpg, rugby.jpg, cone.jpg, board.jpg, ring.jpg, d1.png, diamond.jpg. The images are stored in the images/ folder locally and are also pasted below for reference. You can download any image of your choice and use in the demo link." }, { "code": null, "e": 9352, "s": 9345, "text": " Print" }, { "code": null, "e": 9363, "s": 9352, "text": " Add Notes" } ]
C Program for Iterative Merge Sort - GeeksforGeeks
06 Dec, 2018 Following is a typical recursive implementation of Merge Sort that uses last element as pivot. /* Recursive C program for merge sort */#include <stdio.h>#include <stdlib.h> /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */void merge(int arr[], int l, int m, int r); /* l is for left index and r is right index of the sub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { int m = l + (r - l) / 2; // Same as (l+r)/2 but avoids overflow for large l & h mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */void merge(int arr[], int l, int m, int r){ int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; }} /* Function to print an array */void printArray(int A[], int size){ int i; for (i = 0; i < size; i++) printf("%d ", A[i]); printf("\n");} /* Driver program to test above functions */int main(){ int arr[] = { 12, 11, 13, 5, 6, 7 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printf("Given array is \n"); printArray(arr, arr_size); mergeSort(arr, 0, arr_size - 1); printf("\nSorted array is \n"); printArray(arr, arr_size); return 0;} Given array is 12 11 13 5 6 7 Sorted array is 5 6 7 11 12 13 Please refer complete article on Iterative Merge Sort for more details! Merge Sort C Programs Sorting Sorting Merge Sort Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Difference between break and continue statement in C
[ { "code": null, "e": 24617, "s": 24589, "text": "\n06 Dec, 2018" }, { "code": null, "e": 24712, "s": 24617, "text": "Following is a typical recursive implementation of Merge Sort that uses last element as pivot." }, { "code": "/* Recursive C program for merge sort */#include <stdio.h>#include <stdlib.h> /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */void merge(int arr[], int l, int m, int r); /* l is for left index and r is right index of the sub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { int m = l + (r - l) / 2; // Same as (l+r)/2 but avoids overflow for large l & h mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */void merge(int arr[], int l, int m, int r){ int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; }} /* Function to print an array */void printArray(int A[], int size){ int i; for (i = 0; i < size; i++) printf(\"%d \", A[i]); printf(\"\\n\");} /* Driver program to test above functions */int main(){ int arr[] = { 12, 11, 13, 5, 6, 7 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printf(\"Given array is \\n\"); printArray(arr, arr_size); mergeSort(arr, 0, arr_size - 1); printf(\"\\nSorted array is \\n\"); printArray(arr, arr_size); return 0;}", "e": 26656, "s": 24712, "text": null }, { "code": null, "e": 26722, "s": 26656, "text": "Given array is \n12 11 13 5 6 7 \n\nSorted array is \n5 6 7 11 12 13\n" }, { "code": null, "e": 26794, "s": 26722, "text": "Please refer complete article on Iterative Merge Sort for more details!" }, { "code": null, "e": 26805, "s": 26794, "text": "Merge Sort" }, { "code": null, "e": 26816, "s": 26805, "text": "C Programs" }, { "code": null, "e": 26824, "s": 26816, "text": "Sorting" }, { "code": null, "e": 26832, "s": 26824, "text": "Sorting" }, { "code": null, "e": 26843, "s": 26832, "text": "Merge Sort" }, { "code": null, "e": 26941, "s": 26843, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26950, "s": 26941, "text": "Comments" }, { "code": null, "e": 26963, "s": 26950, "text": "Old Comments" }, { "code": null, "e": 27004, "s": 26963, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 27035, "s": 27004, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 27076, "s": 27035, "text": "C program to find the length of a string" }, { "code": null, "e": 27110, "s": 27076, "text": "Exit codes in C/C++ with Examples" } ]
D3.js timer.restart() Function - GeeksforGeeks
29 Jul, 2020 The timer.restart() function in D3.js is used to restart a timer with the given function and delay. The timer.restart() function is used when one wants to reset the timer and start again. Syntax: timer.restart(callback, delay); Parameters: It takes two parameters as mentioned above and described below: callback: It is the function to be stopped or start after a particular delay. delay: It is the time after which the function will be executed or stop Example 1: When no delay is given. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"></head> <body> <!-- Fetching from CDN of D3.js --> <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"> </script> <script> count = 0; let func = function (e) { console.log(e) if (e > 40) { console.log("Timer stopped after 40ms") if (e > 40) { count++; // Restarting the timer again console.log("Timer restarts") timer.restart(func) } if (count > 2) { timer.stop(); console.log( "count > 2 so timer is stopped") } } } var timer = d3.timer(func); </script></body> </html> Output: Example 2: When a delay is given. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"></head> <body> <!-- Fetching from CDN of D3.js --> <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"> </script> <script> count = 0; let func = function (e) { console.log(e) if (e > 10) { console.log("Timer stopped after 10ms") if (e > 10) { count++; // Restarting the timer again console.log("Timer restarts") timer.restart(func) } if (count > 4) { timer.stop(); console.log( "count > 4 so timer is stopped") } } } // A delay of 2000ms var timer = d3.timer(func, 2000); </script></body> </html> Output: 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 Set the value of an input field in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Form validation using HTML and JavaScript Express.js express.Router() Function Installation of Node.js on Linux Convert a string to an integer in JavaScript How to set the default value for an HTML <select> element ? Top 10 Angular Libraries For Web Developers
[ { "code": null, "e": 24533, "s": 24505, "text": "\n29 Jul, 2020" }, { "code": null, "e": 24721, "s": 24533, "text": "The timer.restart() function in D3.js is used to restart a timer with the given function and delay. The timer.restart() function is used when one wants to reset the timer and start again." }, { "code": null, "e": 24729, "s": 24721, "text": "Syntax:" }, { "code": null, "e": 24762, "s": 24729, "text": "timer.restart(callback, delay);\n" }, { "code": null, "e": 24838, "s": 24762, "text": "Parameters: It takes two parameters as mentioned above and described below:" }, { "code": null, "e": 24916, "s": 24838, "text": "callback: It is the function to be stopped or start after a particular delay." }, { "code": null, "e": 24988, "s": 24916, "text": "delay: It is the time after which the function will be executed or stop" }, { "code": null, "e": 25023, "s": 24988, "text": "Example 1: When no delay is given." }, { "code": null, "e": 25028, "s": 25023, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"></head> <body> <!-- Fetching from CDN of D3.js --> <script type=\"text/javascript\" src=\"https://d3js.org/d3.v4.min.js\"> </script> <script> count = 0; let func = function (e) { console.log(e) if (e > 40) { console.log(\"Timer stopped after 40ms\") if (e > 40) { count++; // Restarting the timer again console.log(\"Timer restarts\") timer.restart(func) } if (count > 2) { timer.stop(); console.log( \"count > 2 so timer is stopped\") } } } var timer = d3.timer(func); </script></body> </html>", "e": 25966, "s": 25028, "text": null }, { "code": null, "e": 25974, "s": 25966, "text": "Output:" }, { "code": null, "e": 26008, "s": 25974, "text": "Example 2: When a delay is given." }, { "code": null, "e": 26013, "s": 26008, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"></head> <body> <!-- Fetching from CDN of D3.js --> <script type=\"text/javascript\" src=\"https://d3js.org/d3.v4.min.js\"> </script> <script> count = 0; let func = function (e) { console.log(e) if (e > 10) { console.log(\"Timer stopped after 10ms\") if (e > 10) { count++; // Restarting the timer again console.log(\"Timer restarts\") timer.restart(func) } if (count > 4) { timer.stop(); console.log( \"count > 4 so timer is stopped\") } } } // A delay of 2000ms var timer = d3.timer(func, 2000); </script></body> </html>", "e": 26981, "s": 26013, "text": null }, { "code": null, "e": 26989, "s": 26981, "text": "Output:" }, { "code": null, "e": 26995, "s": 26989, "text": "D3.js" }, { "code": null, "e": 27006, "s": 26995, "text": "JavaScript" }, { "code": null, "e": 27023, "s": 27006, "text": "Web Technologies" }, { "code": null, "e": 27121, "s": 27023, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27130, "s": 27121, "text": "Comments" }, { "code": null, "e": 27143, "s": 27130, "text": "Old Comments" }, { "code": null, "e": 27188, "s": 27143, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27234, "s": 27188, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 27306, "s": 27234, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27352, "s": 27306, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 27394, "s": 27352, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 27431, "s": 27394, "text": "Express.js express.Router() Function" }, { "code": null, "e": 27464, "s": 27431, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27509, "s": 27464, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27569, "s": 27509, "text": "How to set the default value for an HTML <select> element ?" } ]
How Address Resolution Protocol (ARP) works? - GeeksforGeeks
22 Oct, 2021 Most of the computer programs/applications use logical address (IP address) to send/receive messages, however, the actual communication happens over the physical address (MAC address) i.e from layer 2 of the OSI model. So our mission is to get the destination MAC address which helps in communicating with other devices. This is where ARP comes into the picture, its functionality is to translate IP address to physical addresses. The acronym ARP stands for Address Resolution Protocol which is one of the most important protocols of the Network layer in the OSI model. Note: ARP finds the hardware address, also known as Media Access Control (MAC) address, of a host from its known IP address. Let’s look at how ARP works. Imagine a device that wants to communicate with the other over the internet. What ARP does? Is it broadcast a packet to all the devices of the source network. The devices of the network peel the header of the data link layer from the protocol data unit (PDU) called frame and transfer the packet to the network layer (layer 3 of OSI) where the network ID of the packet is validated with the destination IP’s network ID of the packet and if it’s equal then it responds to the source with the MAC address of the destination, else the packet reaches the gateway of the network and broadcasts packet to the devices it is connected with and validates their network ID The above process continues till the second last network device in the path reaches the destination where it gets validated and ARP, in turn, responds with the destination MAC address. ARP: ARP stands for (Address Resolution Protocol) it is responsible to find the hardware address of a host from a know IP address there are three basic ARP terms.The important terms associated with ARP are: (i) Reverse ARP (ii) Proxy ARP (iii) Inverse ARP ARP Cache: After resolving the MAC address, the ARP sends it to the source where it is stored in a table for future reference. The subsequent communications can use the MAC address from the tableARP Cache Timeout: It indicates the time for which the MAC address in the ARP cache can resideARP request: This is nothing but broadcasting a packet over the network to validate whether we came across the destination MAC address or not. The physical address of the sender.The IP address of the sender.The physical address of the receiver is FF:FF:FF:FF:FF:FF or 1’s.The IP address of the receiverARP response/reply: It is the MAC address response that the source receives from the destination which aids in further communication of the data. ARP Cache: After resolving the MAC address, the ARP sends it to the source where it is stored in a table for future reference. The subsequent communications can use the MAC address from the table ARP Cache Timeout: It indicates the time for which the MAC address in the ARP cache can reside ARP request: This is nothing but broadcasting a packet over the network to validate whether we came across the destination MAC address or not. The physical address of the sender.The IP address of the sender.The physical address of the receiver is FF:FF:FF:FF:FF:FF or 1’s.The IP address of the receiver The physical address of the sender.The IP address of the sender.The physical address of the receiver is FF:FF:FF:FF:FF:FF or 1’s.The IP address of the receiver The physical address of the sender. The IP address of the sender. The physical address of the receiver is FF:FF:FF:FF:FF:FF or 1’s. The IP address of the receiver ARP response/reply: It is the MAC address response that the source receives from the destination which aids in further communication of the data. CASE-1: The sender is a host and wants to send a packet to another host on the same network.Use ARP to find another host’s physical address Use ARP to find another host’s physical address CASE-2: The sender is a host and wants to send a packet to another host on another network. The sender looks at its routing table.Find the IP address of the next-hop (router) for this destination.Use ARP to find the router’s physical address The sender looks at its routing table. Find the IP address of the next-hop (router) for this destination. Use ARP to find the router’s physical address CASE-3: the sender is a router and received a datagram destined for a host on another network. The router checks its routing table.Find the IP address of the next router.Use ARP to find the next router’s physical address. The router checks its routing table. Find the IP address of the next router. Use ARP to find the next router’s physical address. CASE-4: The sender is a router that has received a datagram destined for a host in the same network. Use ARP to find this host’s physical address. Use ARP to find this host’s physical address. NOTE: An ARP request is a broadcast, and an ARP response is a Unicast. Test Yourself : Connect two PC, say A and B with a cross cable. Now you can see the working of ARP by typing these commands: 1. A > arp -a There will be no entry at the table because they never communicated with each other. 2. A > ping 192.168.1.2 IP address of destination is 192.168.1.2 Reply comes from destination but one packet is lost because of ARP processing. Now, entries of the ARP table can be seen by typing the command. This is how ARP table looks like: This article is contributed by Vivek Reddy. 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. VaibhavRai3 priteshverma ahmedmalick79 akshaysingh98088 marcosarcticseal Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Socket Programming in Python Caesar Cipher in Cryptography UDP Server-Client implementation in C Differences between IPv4 and IPv6 Socket Programming in Java ACID Properties in DBMS Page Replacement Algorithms in Operating Systems Types of Operating Systems Normal Forms in DBMS Semaphores in Process Synchronization
[ { "code": null, "e": 36592, "s": 36564, "text": "\n22 Oct, 2021" }, { "code": null, "e": 37025, "s": 36592, "text": "Most of the computer programs/applications use logical address (IP address) to send/receive messages, however, the actual communication happens over the physical address (MAC address) i.e from layer 2 of the OSI model. So our mission is to get the destination MAC address which helps in communicating with other devices. This is where ARP comes into the picture, its functionality is to translate IP address to physical addresses. " }, { "code": null, "e": 37291, "s": 37025, "text": "The acronym ARP stands for Address Resolution Protocol which is one of the most important protocols of the Network layer in the OSI model. Note: ARP finds the hardware address, also known as Media Access Control (MAC) address, of a host from its known IP address. " }, { "code": null, "e": 37323, "s": 37293, "text": "Let’s look at how ARP works. " }, { "code": null, "e": 37987, "s": 37323, "text": "Imagine a device that wants to communicate with the other over the internet. What ARP does? Is it broadcast a packet to all the devices of the source network. The devices of the network peel the header of the data link layer from the protocol data unit (PDU) called frame and transfer the packet to the network layer (layer 3 of OSI) where the network ID of the packet is validated with the destination IP’s network ID of the packet and if it’s equal then it responds to the source with the MAC address of the destination, else the packet reaches the gateway of the network and broadcasts packet to the devices it is connected with and validates their network ID " }, { "code": null, "e": 38174, "s": 37987, "text": "The above process continues till the second last network device in the path reaches the destination where it gets validated and ARP, in turn, responds with the destination MAC address. " }, { "code": null, "e": 38382, "s": 38174, "text": "ARP: ARP stands for (Address Resolution Protocol) it is responsible to find the hardware address of a host from a know IP address there are three basic ARP terms.The important terms associated with ARP are: " }, { "code": null, "e": 38398, "s": 38382, "text": "(i) Reverse ARP" }, { "code": null, "e": 38413, "s": 38398, "text": "(ii) Proxy ARP" }, { "code": null, "e": 38432, "s": 38413, "text": "(iii) Inverse ARP " }, { "code": null, "e": 39171, "s": 38432, "text": "ARP Cache: After resolving the MAC address, the ARP sends it to the source where it is stored in a table for future reference. The subsequent communications can use the MAC address from the tableARP Cache Timeout: It indicates the time for which the MAC address in the ARP cache can resideARP request: This is nothing but broadcasting a packet over the network to validate whether we came across the destination MAC address or not. The physical address of the sender.The IP address of the sender.The physical address of the receiver is FF:FF:FF:FF:FF:FF or 1’s.The IP address of the receiverARP response/reply: It is the MAC address response that the source receives from the destination which aids in further communication of the data. " }, { "code": null, "e": 39367, "s": 39171, "text": "ARP Cache: After resolving the MAC address, the ARP sends it to the source where it is stored in a table for future reference. The subsequent communications can use the MAC address from the table" }, { "code": null, "e": 39462, "s": 39367, "text": "ARP Cache Timeout: It indicates the time for which the MAC address in the ARP cache can reside" }, { "code": null, "e": 39765, "s": 39462, "text": "ARP request: This is nothing but broadcasting a packet over the network to validate whether we came across the destination MAC address or not. The physical address of the sender.The IP address of the sender.The physical address of the receiver is FF:FF:FF:FF:FF:FF or 1’s.The IP address of the receiver" }, { "code": null, "e": 39925, "s": 39765, "text": "The physical address of the sender.The IP address of the sender.The physical address of the receiver is FF:FF:FF:FF:FF:FF or 1’s.The IP address of the receiver" }, { "code": null, "e": 39961, "s": 39925, "text": "The physical address of the sender." }, { "code": null, "e": 39991, "s": 39961, "text": "The IP address of the sender." }, { "code": null, "e": 40057, "s": 39991, "text": "The physical address of the receiver is FF:FF:FF:FF:FF:FF or 1’s." }, { "code": null, "e": 40088, "s": 40057, "text": "The IP address of the receiver" }, { "code": null, "e": 40236, "s": 40088, "text": "ARP response/reply: It is the MAC address response that the source receives from the destination which aids in further communication of the data. " }, { "code": null, "e": 40380, "s": 40240, "text": "CASE-1: The sender is a host and wants to send a packet to another host on the same network.Use ARP to find another host’s physical address" }, { "code": null, "e": 40428, "s": 40380, "text": "Use ARP to find another host’s physical address" }, { "code": null, "e": 40670, "s": 40428, "text": "CASE-2: The sender is a host and wants to send a packet to another host on another network. The sender looks at its routing table.Find the IP address of the next-hop (router) for this destination.Use ARP to find the router’s physical address" }, { "code": null, "e": 40709, "s": 40670, "text": "The sender looks at its routing table." }, { "code": null, "e": 40776, "s": 40709, "text": "Find the IP address of the next-hop (router) for this destination." }, { "code": null, "e": 40822, "s": 40776, "text": "Use ARP to find the router’s physical address" }, { "code": null, "e": 41044, "s": 40822, "text": "CASE-3: the sender is a router and received a datagram destined for a host on another network. The router checks its routing table.Find the IP address of the next router.Use ARP to find the next router’s physical address." }, { "code": null, "e": 41081, "s": 41044, "text": "The router checks its routing table." }, { "code": null, "e": 41121, "s": 41081, "text": "Find the IP address of the next router." }, { "code": null, "e": 41173, "s": 41121, "text": "Use ARP to find the next router’s physical address." }, { "code": null, "e": 41320, "s": 41173, "text": "CASE-4: The sender is a router that has received a datagram destined for a host in the same network. Use ARP to find this host’s physical address." }, { "code": null, "e": 41366, "s": 41320, "text": "Use ARP to find this host’s physical address." }, { "code": null, "e": 41438, "s": 41366, "text": "NOTE: An ARP request is a broadcast, and an ARP response is a Unicast. " }, { "code": null, "e": 41455, "s": 41438, "text": "Test Yourself : " }, { "code": null, "e": 41568, "s": 41457, "text": "Connect two PC, say A and B with a cross cable. Now you can see the working of ARP by typing these commands: " }, { "code": null, "e": 41582, "s": 41568, "text": "1. A > arp -a" }, { "code": null, "e": 41669, "s": 41582, "text": "There will be no entry at the table because they never communicated with each other. " }, { "code": null, "e": 41816, "s": 41671, "text": "2. A > ping 192.168.1.2\n\nIP address of destination is 192.168.1.2\nReply comes from destination but one packet is lost because of ARP processing." }, { "code": null, "e": 41919, "s": 41818, "text": "Now, entries of the ARP table can be seen by typing the command. This is how ARP table looks like: " }, { "code": null, "e": 42215, "s": 41919, "text": "This article is contributed by Vivek Reddy. 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. " }, { "code": null, "e": 42341, "s": 42215, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 42353, "s": 42341, "text": "VaibhavRai3" }, { "code": null, "e": 42366, "s": 42353, "text": "priteshverma" }, { "code": null, "e": 42380, "s": 42366, "text": "ahmedmalick79" }, { "code": null, "e": 42397, "s": 42380, "text": "akshaysingh98088" }, { "code": null, "e": 42414, "s": 42397, "text": "marcosarcticseal" }, { "code": null, "e": 42432, "s": 42414, "text": "Computer Networks" }, { "code": null, "e": 42440, "s": 42432, "text": "GATE CS" }, { "code": null, "e": 42458, "s": 42440, "text": "Computer Networks" }, { "code": null, "e": 42556, "s": 42458, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42585, "s": 42556, "text": "Socket Programming in Python" }, { "code": null, "e": 42615, "s": 42585, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 42653, "s": 42615, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 42687, "s": 42653, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 42714, "s": 42687, "text": "Socket Programming in Java" }, { "code": null, "e": 42738, "s": 42714, "text": "ACID Properties in DBMS" }, { "code": null, "e": 42787, "s": 42738, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 42814, "s": 42787, "text": "Types of Operating Systems" }, { "code": null, "e": 42835, "s": 42814, "text": "Normal Forms in DBMS" } ]
Tryit Editor v3.7
Tryit: Video autoplay and muted
[]
Lazy loading of images in table view using Swift
To load an image in table view cell we’ll go through a series of steps. Create a table view, table view cell and add an Image view to it. Assign a custom class to the cell we created. In the cell for row at method write the following lines of code. let cell = tblView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell return cell To download the image we’ll create a function and embed that into an extension. func setImageFromUrl(ImageURL :String) { URLSession.shared.dataTask( with: NSURL(string:ImageURL)! as URL, completionHandler: { (data, response, error) -> Void in DispatchQueue.main.async { if let data = data { self.image = UIImage(data: data) } } }).resume() } Now embed the same function into an extension of UIImageView to use with any image. In Cell for row at method the following function, where img is the outlet in custom Class. cell.img.setImageFromUrl(ImageURL: url) In this example I’ve used an image from open source "https://homepages.cae.wisc.edu/~ece533/images/boat.png” When we run the same code on an iPhone 7+ simulator, below is the result −
[ { "code": null, "e": 1134, "s": 1062, "text": "To load an image in table view cell we’ll go through a series of steps." }, { "code": null, "e": 1200, "s": 1134, "text": "Create a table view, table view cell and add an Image view to it." }, { "code": null, "e": 1246, "s": 1200, "text": "Assign a custom class to the cell we created." }, { "code": null, "e": 1311, "s": 1246, "text": "In the cell for row at method write the following lines of code." }, { "code": null, "e": 1407, "s": 1311, "text": "let cell = tblView.dequeueReusableCell(withIdentifier: \"CustomCell\") as! CustomCell\nreturn cell" }, { "code": null, "e": 1487, "s": 1407, "text": "To download the image we’ll create a function and embed that into an extension." }, { "code": null, "e": 1804, "s": 1487, "text": "func setImageFromUrl(ImageURL :String) {\n URLSession.shared.dataTask( with: NSURL(string:ImageURL)! as URL, completionHandler: {\n (data, response, error) -> Void in\n DispatchQueue.main.async {\n if let data = data {\n self.image = UIImage(data: data) \n }\n }\n }).resume()\n}" }, { "code": null, "e": 1888, "s": 1804, "text": "Now embed the same function into an extension of UIImageView to use with any image." }, { "code": null, "e": 1979, "s": 1888, "text": "In Cell for row at method the following function, where img is the outlet in custom Class." }, { "code": null, "e": 2019, "s": 1979, "text": "cell.img.setImageFromUrl(ImageURL: url)" }, { "code": null, "e": 2128, "s": 2019, "text": "In this example I’ve used an image from open source \"https://homepages.cae.wisc.edu/~ece533/images/boat.png”" }, { "code": null, "e": 2203, "s": 2128, "text": "When we run the same code on an iPhone 7+ simulator, below is the result −" } ]
C++ Relational and Equality Operators
In C Programming, the values hold on in 2 variables will be compared exploitation following operators and relation between them will be determined. These operators are called relational operators. Various C++ relational operators available are- You can use these operators for checking the relationship between the operands. These operators are mostly used in conditional statements and loops to find a relation between 2 operands and act accordingly. For example, #include<iostream> using namespace std; int main() { int a = 3, b = 2; if(a < b) { cout<< a << " is less than " << b; } else if(a > b) { cout<< a << " is greater than " << b; } return 0; } This will give the output − 3 is greater than 2 The equality operators in C++ are is equal to(==) and is not equal to(!=). They do the task as they are named. The binary equality operators compare their operands for strict equality or inequality. The equality operators, equal to (==) and not equal to (!=), have lower precedence than the relational operators, but they behave similarly. The result type for these operators is bool.The equal-to operator (==) returns true (1) if both operands have the same value; otherwise, it returns false (0). The not-equal-to operator (!=) returns true if the operands do not have the same value; otherwise, it returns false. #include <iostream> using namespace std; int main() { cout << boolalpha // For printing true and false as true and false in case of a bool result << "The true expression 3 != 2 yields: " << (3 != 2) << endl << "The false expression 20 == 10 yields: " << (20 == 10) << endl; } This gives the output − The true expression 3 != 2 yields: true The false expression 20 == 10 yields: false
[ { "code": null, "e": 1307, "s": 1062, "text": "In C Programming, the values hold on in 2 variables will be compared exploitation following operators and relation between them will be determined. These operators are called relational operators. Various C++ relational operators available are-" }, { "code": null, "e": 1527, "s": 1307, "text": "You can use these operators for checking the relationship between the operands. These operators are mostly used in conditional statements and loops to find a relation between 2 operands and act accordingly. For example," }, { "code": null, "e": 1748, "s": 1527, "text": "#include<iostream>\nusing namespace std;\n\nint main() {\n int a = 3, b = 2;\n\n if(a < b) {\n cout<< a << \" is less than \" << b;\n }\n else if(a > b) {\n cout<< a << \" is greater than \" << b;\n }\n return 0;\n}" }, { "code": null, "e": 1776, "s": 1748, "text": "This will give the output −" }, { "code": null, "e": 1796, "s": 1776, "text": "3 is greater than 2" }, { "code": null, "e": 2412, "s": 1796, "text": "The equality operators in C++ are is equal to(==) and is not equal to(!=). They do the task as they are named. The binary equality operators compare their operands for strict equality or inequality. The equality operators, equal to (==) and not equal to (!=), have lower precedence than the relational operators, but they behave similarly. The result type for these operators is bool.The equal-to operator (==) returns true (1) if both operands have the same value; otherwise, it returns false (0). The not-equal-to operator (!=) returns true if the operands do not have the same value; otherwise, it returns false." }, { "code": null, "e": 2720, "s": 2412, "text": "#include <iostream> \nusing namespace std; \n\nint main() { \n cout << boolalpha // For printing true and false as true and false in case of a bool result\n << \"The true expression 3 != 2 yields: \" \n << (3 != 2) << endl \n << \"The false expression 20 == 10 yields: \" \n << (20 == 10) << endl; \n}" }, { "code": null, "e": 2744, "s": 2720, "text": "This gives the output −" }, { "code": null, "e": 2828, "s": 2744, "text": "The true expression 3 != 2 yields: true\nThe false expression 20 == 10 yields: false" } ]
PL/SQL - Date & Time
In this chapter, we will discuss the Date and Time in PL/SQL. There are two classes of date and time related data types in PL/SQL − Datetime data types Interval data types The Datetime data types are − DATE TIMESTAMP TIMESTAMP WITH TIME ZONE TIMESTAMP WITH LOCAL TIME ZONE The Interval data types are − INTERVAL YEAR TO MONTH INTERVAL DAY TO SECOND Both datetime and interval data types consist of fields. The values of these fields determine the value of the data type. The following table lists the fields and their possible values for datetimes and intervals. 00 to 59.9(n), where 9(n) is the precision of time fractional seconds The 9(n) portion is not applicable for DATE. -12 to 14 (range accommodates daylight savings time changes) Not applicable for DATE or TIMESTAMP. 00 to 59 Not applicable for DATE or TIMESTAMP. Following are the Datetime data types − It stores date and time information in both character and number datatypes. It is made of information on century, year, month, date, hour, minute, and second. It is specified as − It is an extension of the DATE data type. It stores the year, month, and day of the DATE datatype, along with hour, minute, and second values. It is useful for storing precise time values. It is a variant of TIMESTAMP that includes a time zone region name or a time zone offset in its value. The time zone offset is the difference (in hours and minutes) between local time and UTC. This data type is useful for collecting and evaluating date information across geographic regions. It is another variant of TIMESTAMP that includes a time zone offset in its value. Following table provides the Datetime functions (where, x has the datetime value) − ADD_MONTHS(x, y); Adds y months to x. LAST_DAY(x); Returns the last day of the month. MONTHS_BETWEEN(x, y); Returns the number of months between x and y. NEXT_DAY(x, day); Returns the datetime of the next day after x. NEW_TIME; Returns the time/day value from a time zone specified by the user. ROUND(x [, unit]); Rounds x. SYSDATE(); Returns the current datetime. TRUNC(x [, unit]); Truncates x. Timestamp functions (where, x has a timestamp value) − CURRENT_TIMESTAMP(); Returns a TIMESTAMP WITH TIME ZONE containing the current session time along with the session time zone. EXTRACT({ YEAR | MONTH | DAY | HOUR | MINUTE | SECOND } | { TIMEZONE_HOUR | TIMEZONE_MINUTE } | { TIMEZONE_REGION | } TIMEZONE_ABBR ) FROM x) Extracts and returns a year, month, day, hour, minute, second, or time zone from x. FROM_TZ(x, time_zone); Converts the TIMESTAMP x and the time zone specified by time_zone to a TIMESTAMP WITH TIMEZONE. LOCALTIMESTAMP(); Returns a TIMESTAMP containing the local time in the session time zone. SYSTIMESTAMP(); Returns a TIMESTAMP WITH TIME ZONE containing the current database time along with the database time zone. SYS_EXTRACT_UTC(x); Converts the TIMESTAMP WITH TIMEZONE x to a TIMESTAMP containing the date and time in UTC. TO_TIMESTAMP(x, [format]); Converts the string x to a TIMESTAMP. TO_TIMESTAMP_TZ(x, [format]); Converts the string x to a TIMESTAMP WITH TIMEZONE. The following code snippets illustrate the use of the above functions − Example 1 SELECT SYSDATE FROM DUAL; Output − 08/31/2012 5:25:34 PM Example 2 SELECT TO_CHAR(CURRENT_DATE, 'DD-MM-YYYY HH:MI:SS') FROM DUAL; Output − 31-08-2012 05:26:14 Example 3 SELECT ADD_MONTHS(SYSDATE, 5) FROM DUAL; Output − 01/31/2013 5:26:31 PM Example 4 SELECT LOCALTIMESTAMP FROM DUAL; Output − 8/31/2012 5:26:55.347000 PM Following are the Interval data types − IINTERVAL YEAR TO MONTH − It stores a period of time using the YEAR and MONTH datetime fields. IINTERVAL YEAR TO MONTH − It stores a period of time using the YEAR and MONTH datetime fields. INTERVAL DAY TO SECOND − It stores a period of time in terms of days, hours, minutes, and seconds. INTERVAL DAY TO SECOND − It stores a period of time in terms of days, hours, minutes, and seconds. NUMTODSINTERVAL(x, interval_unit); Converts the number x to an INTERVAL DAY TO SECOND. NUMTOYMINTERVAL(x, interval_unit); Converts the number x to an INTERVAL YEAR TO MONTH. TO_DSINTERVAL(x); Converts the string x to an INTERVAL DAY TO SECOND. TO_YMINTERVAL(x); Converts the string x to an INTERVAL YEAR TO MONTH. Print Add Notes Bookmark this page
[ { "code": null, "e": 2197, "s": 2065, "text": "In this chapter, we will discuss the Date and Time in PL/SQL. There are two classes of date and time related data types in PL/SQL −" }, { "code": null, "e": 2217, "s": 2197, "text": "Datetime data types" }, { "code": null, "e": 2237, "s": 2217, "text": "Interval data types" }, { "code": null, "e": 2267, "s": 2237, "text": "The Datetime data types are −" }, { "code": null, "e": 2272, "s": 2267, "text": "DATE" }, { "code": null, "e": 2282, "s": 2272, "text": "TIMESTAMP" }, { "code": null, "e": 2307, "s": 2282, "text": "TIMESTAMP WITH TIME ZONE" }, { "code": null, "e": 2338, "s": 2307, "text": "TIMESTAMP WITH LOCAL TIME ZONE" }, { "code": null, "e": 2368, "s": 2338, "text": "The Interval data types are −" }, { "code": null, "e": 2391, "s": 2368, "text": "INTERVAL YEAR TO MONTH" }, { "code": null, "e": 2414, "s": 2391, "text": "INTERVAL DAY TO SECOND" }, { "code": null, "e": 2628, "s": 2414, "text": "Both datetime and interval data types consist of fields. The values of these fields determine the value of the data type. The following table lists the fields and their possible values for datetimes and intervals." }, { "code": null, "e": 2698, "s": 2628, "text": "00 to 59.9(n), where 9(n) is the precision of time fractional seconds" }, { "code": null, "e": 2743, "s": 2698, "text": "The 9(n) portion is not applicable for DATE." }, { "code": null, "e": 2804, "s": 2743, "text": "-12 to 14 (range accommodates daylight savings time changes)" }, { "code": null, "e": 2842, "s": 2804, "text": "Not applicable for DATE or TIMESTAMP." }, { "code": null, "e": 2851, "s": 2842, "text": "00 to 59" }, { "code": null, "e": 2889, "s": 2851, "text": "Not applicable for DATE or TIMESTAMP." }, { "code": null, "e": 2929, "s": 2889, "text": "Following are the Datetime data types −" }, { "code": null, "e": 3109, "s": 2929, "text": "It stores date and time information in both character and number datatypes. It is made of information on century, year, month, date, hour, minute, and second. It is specified as −" }, { "code": null, "e": 3298, "s": 3109, "text": "It is an extension of the DATE data type. It stores the year, month, and day of the DATE datatype, along with hour, minute, and second values. It is useful for storing precise time values." }, { "code": null, "e": 3590, "s": 3298, "text": "It is a variant of TIMESTAMP that includes a time zone region name or a time zone offset in its value. The time zone offset is the difference (in hours and minutes) between local time and UTC. This data type is useful for collecting and evaluating date information across geographic regions." }, { "code": null, "e": 3672, "s": 3590, "text": "It is another variant of TIMESTAMP that includes a time zone offset in its value." }, { "code": null, "e": 3756, "s": 3672, "text": "Following table provides the Datetime functions (where, x has the datetime value) −" }, { "code": null, "e": 3774, "s": 3756, "text": "ADD_MONTHS(x, y);" }, { "code": null, "e": 3794, "s": 3774, "text": "Adds y months to x." }, { "code": null, "e": 3807, "s": 3794, "text": "LAST_DAY(x);" }, { "code": null, "e": 3842, "s": 3807, "text": "Returns the last day of the month." }, { "code": null, "e": 3864, "s": 3842, "text": "MONTHS_BETWEEN(x, y);" }, { "code": null, "e": 3910, "s": 3864, "text": "Returns the number of months between x and y." }, { "code": null, "e": 3928, "s": 3910, "text": "NEXT_DAY(x, day);" }, { "code": null, "e": 3974, "s": 3928, "text": "Returns the datetime of the next day after x." }, { "code": null, "e": 3984, "s": 3974, "text": "NEW_TIME;" }, { "code": null, "e": 4051, "s": 3984, "text": "Returns the time/day value from a time zone specified by the user." }, { "code": null, "e": 4070, "s": 4051, "text": "ROUND(x [, unit]);" }, { "code": null, "e": 4080, "s": 4070, "text": "Rounds x." }, { "code": null, "e": 4091, "s": 4080, "text": "SYSDATE();" }, { "code": null, "e": 4121, "s": 4091, "text": "Returns the current datetime." }, { "code": null, "e": 4140, "s": 4121, "text": "TRUNC(x [, unit]);" }, { "code": null, "e": 4153, "s": 4140, "text": "Truncates x." }, { "code": null, "e": 4208, "s": 4153, "text": "Timestamp functions (where, x has a timestamp value) −" }, { "code": null, "e": 4229, "s": 4208, "text": "CURRENT_TIMESTAMP();" }, { "code": null, "e": 4334, "s": 4229, "text": "Returns a TIMESTAMP WITH TIME ZONE containing the current session time along with the session time zone." }, { "code": null, "e": 4476, "s": 4334, "text": "EXTRACT({ YEAR | MONTH | DAY | HOUR | MINUTE | SECOND } | { TIMEZONE_HOUR | TIMEZONE_MINUTE } | { TIMEZONE_REGION | } TIMEZONE_ABBR ) FROM x)" }, { "code": null, "e": 4560, "s": 4476, "text": "Extracts and returns a year, month, day, hour, minute, second, or time zone from x." }, { "code": null, "e": 4583, "s": 4560, "text": "FROM_TZ(x, time_zone);" }, { "code": null, "e": 4679, "s": 4583, "text": "Converts the TIMESTAMP x and the time zone specified by time_zone to a TIMESTAMP WITH TIMEZONE." }, { "code": null, "e": 4697, "s": 4679, "text": "LOCALTIMESTAMP();" }, { "code": null, "e": 4769, "s": 4697, "text": "Returns a TIMESTAMP containing the local time in the session time zone." }, { "code": null, "e": 4785, "s": 4769, "text": "SYSTIMESTAMP();" }, { "code": null, "e": 4892, "s": 4785, "text": "Returns a TIMESTAMP WITH TIME ZONE containing the current database time along with the database time zone." }, { "code": null, "e": 4912, "s": 4892, "text": "SYS_EXTRACT_UTC(x);" }, { "code": null, "e": 5003, "s": 4912, "text": "Converts the TIMESTAMP WITH TIMEZONE x to a TIMESTAMP containing the date and time in UTC." }, { "code": null, "e": 5030, "s": 5003, "text": "TO_TIMESTAMP(x, [format]);" }, { "code": null, "e": 5068, "s": 5030, "text": "Converts the string x to a TIMESTAMP." }, { "code": null, "e": 5098, "s": 5068, "text": "TO_TIMESTAMP_TZ(x, [format]);" }, { "code": null, "e": 5150, "s": 5098, "text": "Converts the string x to a TIMESTAMP WITH TIMEZONE." }, { "code": null, "e": 5222, "s": 5150, "text": "The following code snippets illustrate the use of the above functions −" }, { "code": null, "e": 5232, "s": 5222, "text": "Example 1" }, { "code": null, "e": 5259, "s": 5232, "text": "SELECT SYSDATE FROM DUAL; " }, { "code": null, "e": 5268, "s": 5259, "text": "Output −" }, { "code": null, "e": 5292, "s": 5268, "text": "08/31/2012 5:25:34 PM \n" }, { "code": null, "e": 5302, "s": 5292, "text": "Example 2" }, { "code": null, "e": 5366, "s": 5302, "text": "SELECT TO_CHAR(CURRENT_DATE, 'DD-MM-YYYY HH:MI:SS') FROM DUAL; " }, { "code": null, "e": 5375, "s": 5366, "text": "Output −" }, { "code": null, "e": 5396, "s": 5375, "text": "31-08-2012 05:26:14\n" }, { "code": null, "e": 5406, "s": 5396, "text": "Example 3" }, { "code": null, "e": 5447, "s": 5406, "text": "SELECT ADD_MONTHS(SYSDATE, 5) FROM DUAL;" }, { "code": null, "e": 5456, "s": 5447, "text": "Output −" }, { "code": null, "e": 5480, "s": 5456, "text": "01/31/2013 5:26:31 PM \n" }, { "code": null, "e": 5490, "s": 5480, "text": "Example 4" }, { "code": null, "e": 5524, "s": 5490, "text": "SELECT LOCALTIMESTAMP FROM DUAL; " }, { "code": null, "e": 5533, "s": 5524, "text": "Output −" }, { "code": null, "e": 5563, "s": 5533, "text": "8/31/2012 5:26:55.347000 PM \n" }, { "code": null, "e": 5603, "s": 5563, "text": "Following are the Interval data types −" }, { "code": null, "e": 5698, "s": 5603, "text": "IINTERVAL YEAR TO MONTH − It stores a period of time using the YEAR and MONTH datetime fields." }, { "code": null, "e": 5793, "s": 5698, "text": "IINTERVAL YEAR TO MONTH − It stores a period of time using the YEAR and MONTH datetime fields." }, { "code": null, "e": 5893, "s": 5793, "text": "INTERVAL DAY TO SECOND − It stores a period of time in terms of days, hours, minutes, and seconds. " }, { "code": null, "e": 5993, "s": 5893, "text": "INTERVAL DAY TO SECOND − It stores a period of time in terms of days, hours, minutes, and seconds. " }, { "code": null, "e": 6028, "s": 5993, "text": "NUMTODSINTERVAL(x, interval_unit);" }, { "code": null, "e": 6080, "s": 6028, "text": "Converts the number x to an INTERVAL DAY TO SECOND." }, { "code": null, "e": 6115, "s": 6080, "text": "NUMTOYMINTERVAL(x, interval_unit);" }, { "code": null, "e": 6167, "s": 6115, "text": "Converts the number x to an INTERVAL YEAR TO MONTH." }, { "code": null, "e": 6185, "s": 6167, "text": "TO_DSINTERVAL(x);" }, { "code": null, "e": 6237, "s": 6185, "text": "Converts the string x to an INTERVAL DAY TO SECOND." }, { "code": null, "e": 6255, "s": 6237, "text": "TO_YMINTERVAL(x);" }, { "code": null, "e": 6307, "s": 6255, "text": "Converts the string x to an INTERVAL YEAR TO MONTH." }, { "code": null, "e": 6314, "s": 6307, "text": " Print" }, { "code": null, "e": 6325, "s": 6314, "text": " Add Notes" } ]
Apex - Interfaces
An interface is like an Apex class in which none of the methods have been implemented. It only contains the method signatures, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface. Interfaces are used mainly for providing the abstraction layer for your code. They separate the implementation from declaration of the method. Let's take an example of our Chemical Company. Suppose that we need to provide the discount to Premium and Ordinary customers and discounts for both will be different. We will create an Interface called the DiscountProcessor. // Interface public interface DiscountProcessor { Double percentageDiscountTobeApplied(); // method signature only } // Premium Customer Class public class PremiumCustomer implements DiscountProcessor { //Method Call public Double percentageDiscountTobeApplied () { // For Premium customer, discount should be 30% return 0.30; } } // Normal Customer Class public class NormalCustomer implements DiscountProcessor { // Method Call public Double percentageDiscountTobeApplied () { // For Premium customer, discount should be 10% return 0.10; } } When you implement the Interface then it is mandatory to implement the method of that Interface. If you do not implement the Interface methods, it will throw an error. You should use Interfaces when you want to make the method implementation mandatory for the developer. SFDC do have standard interfaces like Database.Batchable, Schedulable, etc. For example, if you implement the Database.Batchable Interface, then you must implement the three methods defined in the Interface – Start, Execute and Finish. Below is an example for Standard Salesforce provided Database.Batchable Interface which sends out emails to users with the Batch Status. This interface has 3 methods, Start, Execute and Finish. Using this interface, we can implement the Batchable functionality and it also provides the BatchableContext variable which we can use to get more information about the Batch which is executing and to perform other functionalities. global class CustomerProessingBatch implements Database.Batchable<sobject7>, Schedulable { // Add here your email address global String [] email = new String[] {'test@test.com'}; // Start Method global Database.Querylocator start (Database.BatchableContext BC) { // This is the Query which will determine the scope of Records and fetching the same return Database.getQueryLocator('Select id, Name, APEX_Customer_Status__c, APEX_Customer_Decscription__c From APEX_Customer__c WHERE createdDate = today && APEX_Active__c = true'); } // Execute method global void execute (Database.BatchableContext BC, List<sobject> scope) { List<apex_customer__c> customerList = new List<apex_customer__c>(); List<apex_customer__c> updtaedCustomerList = new List<apex_customer__c>(); for (sObject objScope: scope) { // type casting from generic sOject to APEX_Customer__c APEX_Customer__c newObjScope = (APEX_Customer__c)objScope ; newObjScope.APEX_Customer_Decscription__c = 'Updated Via Batch Job'; newObjScope.APEX_Customer_Status__c = 'Processed'; // Add records to the List updtaedCustomerList.add(newObjScope); } // Check if List is empty or not if (updtaedCustomerList != null && updtaedCustomerList.size()>0) { // Update the Records Database.update(updtaedCustomerList); System.debug('List Size '+updtaedCustomerList.size()); } } // Finish Method global void finish(Database.BatchableContext BC) { Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // get the job Id AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors, a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById, a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()]; System.debug('$$$ Jobid is'+BC.getJobId()); // below code will send an email to User about the status mail.setToAddresses(email); // Add here your email address mail.setReplyTo('test@test.com'); mail.setSenderDisplayName('Apex Batch Processing Module'); mail.setSubject('Batch Processing '+a.Status); mail.setPlainTextBody('The Batch Apex job processed '+a.TotalJobItems+'batches with '+a.NumberOfErrors+'failures'+'Job Item processed are'+a.JobItemsProcessed); Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail}); } // Scheduler Method to scedule the class global void execute(SchedulableContext sc) { CustomerProessingBatch conInstance = new CustomerProessingBatch(); database.executebatch(conInstance,100); } } To execute this class, you have to run the below code in the Developer Console. CustomerProessingBatch objBatch = new CustomerProessingBatch (); Database.executeBatch(objBatch); 14 Lectures 2 hours Vijay Thapa 7 Lectures 2 hours Uplatz 29 Lectures 6 hours Ramnarayan Ramakrishnan 49 Lectures 3 hours Ali Saleh Ali 10 Lectures 4 hours Soham Ghosh 48 Lectures 4.5 hours GUHARAJANM Print Add Notes Bookmark this page
[ { "code": null, "e": 2341, "s": 2052, "text": "An interface is like an Apex class in which none of the methods have been implemented. It only contains the method signatures, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface." }, { "code": null, "e": 2484, "s": 2341, "text": "Interfaces are used mainly for providing the abstraction layer for your code. They separate the implementation from declaration of the method." }, { "code": null, "e": 2652, "s": 2484, "text": "Let's take an example of our Chemical Company. Suppose that we need to provide the discount to Premium and Ordinary customers and discounts for both will be different." }, { "code": null, "e": 2710, "s": 2652, "text": "We will create an Interface called the DiscountProcessor." }, { "code": null, "e": 3323, "s": 2710, "text": "// Interface\npublic interface DiscountProcessor {\n Double percentageDiscountTobeApplied(); // method signature only\n}\n\n// Premium Customer Class\npublic class PremiumCustomer implements DiscountProcessor {\n \n //Method Call\n public Double percentageDiscountTobeApplied () {\n \n // For Premium customer, discount should be 30%\n return 0.30;\n }\n}\n\n// Normal Customer Class\npublic class NormalCustomer implements DiscountProcessor {\n \n // Method Call\n public Double percentageDiscountTobeApplied () {\n \n // For Premium customer, discount should be 10%\n return 0.10;\n }\n}" }, { "code": null, "e": 3594, "s": 3323, "text": "When you implement the Interface then it is mandatory to implement the method of that Interface. If you do not implement the Interface methods, it will throw an error. You should use Interfaces when you want to make the method implementation mandatory for the developer." }, { "code": null, "e": 3830, "s": 3594, "text": "SFDC do have standard interfaces like Database.Batchable, Schedulable, etc. For example, if you implement the Database.Batchable Interface, then you must implement the three methods defined in the Interface – Start, Execute and Finish." }, { "code": null, "e": 4256, "s": 3830, "text": "Below is an example for Standard Salesforce provided Database.Batchable Interface which sends out emails to users with the Batch Status. This interface has 3 methods, Start, Execute and Finish. Using this interface, we can implement the Batchable functionality and it also provides the BatchableContext variable which we can use to get more information about the Batch which is executing and to perform other functionalities." }, { "code": null, "e": 7030, "s": 4256, "text": "global class CustomerProessingBatch implements Database.Batchable<sobject7>,\nSchedulable {\n // Add here your email address\n global String [] email = new String[] {'test@test.com'};\n\n // Start Method\n global Database.Querylocator start (Database.BatchableContext BC) {\n \n // This is the Query which will determine the scope of Records and fetching the same\n return Database.getQueryLocator('Select id, Name, APEX_Customer_Status__c,\n APEX_Customer_Decscription__c From APEX_Customer__c WHERE createdDate = today\n && APEX_Active__c = true');\n }\n\n // Execute method\n global void execute (Database.BatchableContext BC, List<sobject> scope) {\n List<apex_customer__c> customerList = new List<apex_customer__c>();\n List<apex_customer__c> updtaedCustomerList = new List<apex_customer__c>();\n \n for (sObject objScope: scope) {\n // type casting from generic sOject to APEX_Customer__c\n APEX_Customer__c newObjScope = (APEX_Customer__c)objScope ;\n newObjScope.APEX_Customer_Decscription__c = 'Updated Via Batch Job';\n newObjScope.APEX_Customer_Status__c = 'Processed';\n \n // Add records to the List\n updtaedCustomerList.add(newObjScope);\n }\n\n // Check if List is empty or not\n if (updtaedCustomerList != null && updtaedCustomerList.size()>0) {\n \n // Update the Records\n Database.update(updtaedCustomerList); System.debug('List Size\n '+updtaedCustomerList.size());\n }\n }\n\n // Finish Method\n global void finish(Database.BatchableContext BC) {\n Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();\n \n // get the job Id\n AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors,\n a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById,\n a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];\n System.debug('$$$ Jobid is'+BC.getJobId());\n \n // below code will send an email to User about the status\n mail.setToAddresses(email);\n \n // Add here your email address\n mail.setReplyTo('test@test.com');\n mail.setSenderDisplayName('Apex Batch Processing Module');\n mail.setSubject('Batch Processing '+a.Status);\n mail.setPlainTextBody('The Batch Apex job processed\n '+a.TotalJobItems+'batches with '+a.NumberOfErrors+'failures'+'Job Item\n processed are'+a.JobItemsProcessed);\n Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail});\n }\n\n // Scheduler Method to scedule the class\n global void execute(SchedulableContext sc) {\n CustomerProessingBatch conInstance = new CustomerProessingBatch();\n database.executebatch(conInstance,100);\n }\n}" }, { "code": null, "e": 7110, "s": 7030, "text": "To execute this class, you have to run the below code in the Developer Console." }, { "code": null, "e": 7208, "s": 7110, "text": "CustomerProessingBatch objBatch = new CustomerProessingBatch ();\nDatabase.executeBatch(objBatch);" }, { "code": null, "e": 7241, "s": 7208, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 7254, "s": 7241, "text": " Vijay Thapa" }, { "code": null, "e": 7286, "s": 7254, "text": "\n 7 Lectures \n 2 hours \n" }, { "code": null, "e": 7294, "s": 7286, "text": " Uplatz" }, { "code": null, "e": 7327, "s": 7294, "text": "\n 29 Lectures \n 6 hours \n" }, { "code": null, "e": 7352, "s": 7327, "text": " Ramnarayan Ramakrishnan" }, { "code": null, "e": 7385, "s": 7352, "text": "\n 49 Lectures \n 3 hours \n" }, { "code": null, "e": 7400, "s": 7385, "text": " Ali Saleh Ali" }, { "code": null, "e": 7433, "s": 7400, "text": "\n 10 Lectures \n 4 hours \n" }, { "code": null, "e": 7446, "s": 7433, "text": " Soham Ghosh" }, { "code": null, "e": 7481, "s": 7446, "text": "\n 48 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7493, "s": 7481, "text": " GUHARAJANM" }, { "code": null, "e": 7500, "s": 7493, "text": " Print" }, { "code": null, "e": 7511, "s": 7500, "text": " Add Notes" } ]
Data Visualization Using Chartjs and Django - GeeksforGeeks
23 Jan, 2020 Prerequisite : django installationWith the growth of data, data visualization in become a import part here we will implement chart for our data in our web apps using chartjs with django. Django is a high-level Python Web framework based web framework and chartjs is an easy way to include animated, interactive graphs. Modules required : django : install django djangorestframework$ pip install djangorestframework $ pip install djangorestframework basic setup : Start a project by the following command – $ django-admin startproject charts Change directory to charts – $ cd charts Start the server- Start the server by typing following command in terminal – $ python manage.py runserver To check whether the server is running or not go to a web browser and enter http://127.0.0.1:8000/ as URL. Now stop the server by pressing ctrl+C Let’s create an app now. $ python manage.py startapp chartjs Goto chartjs/ folder by doing: $ cd chartjs and create a folder with index.html file: templates/chartjs/index.html $ mkdir -p templates/chartjs && cd templates/chartjs && touch index.html Open the project folder using a text editor. The directory structure should look like this : Now add chartjs app and rest_framework in your charts in settings.py. Edit urls.py file in charts : from django.contrib import adminfrom django.urls import pathfrom chartjs import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.HomeView.as_view()), # path('test-api', views.get_data), path('api', views.ChartData.as_view()),] Edit views.py in chartjs : # from django.http import JsonResponse from django.shortcuts import renderfrom django.views.generic import View from rest_framework.views import APIViewfrom rest_framework.response import Response class HomeView(View): def get(self, request, *args, **kwargs): return render(request, 'chartjs/index.html') #################################################### ## if you don't want to user rest_framework # def get_data(request, *args, **kwargs):## data ={# "sales" : 100,# "person": 10000,# }## return JsonResponse(data) # http response ####################################################### ## using rest_framework classes class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format = None): labels = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July' ] chartLabel = "my data" chartdata = [0, 10, 5, 2, 20, 30, 45] data ={ "labels":labels, "chartLabel":chartLabel, "chartdata":chartdata, } return Response(data) Navigate to templates/chartjs/index.html and edit it. <!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>chatsjs</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body class="container-fluid"> <center class="row"> <h1>implementation of <b>chartJS</b> using <b>django</b></h1> </center> <hr /> <div class="row"> <div class="col-md-6"> <canvas id="myChartline"></canvas> </div> <div class="col-md-6"> <canvas id="myChartBar"></canvas> </div> </div> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script> <script> var endpoint = '/api'; $.ajax({ method: "GET", url: endpoint, success: function(data) { drawLineGraph(data, 'myChartline'); drawBarGraph(data, 'myChartBar'); console.log("drawing"); }, error: function(error_data) { console.log(error_data); } }) function drawLineGraph(data, id) { var labels = data.labels; var chartLabel = data.chartLabel; var chartdata = data.chartdata; var ctx = document.getElementById(id).getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'line', // The data for our dataset data: { labels: labels, datasets: [{ label: chartLabel, backgroundColor: 'rgb(255, 100, 200)', borderColor: 'rgb(55, 99, 132)', data: chartdata, }] }, // Configuration options go here options: { scales: { xAxes: [{ display: true }], yAxes: [{ ticks: { beginAtZero: true } }] } } }); } function drawBarGraph(data, id) { var labels = data.labels; var chartLabel = data.chartLabel; var chartdata = data.chartdata; var ctx = document.getElementById(id).getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: chartLabel, data: chartdata, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); } </script></body> </html> Make migrations and migrate it : $ python manage.py makemigrations $ python manage.py migrate Now you can run the server to see your app : $ python manage.py runserver Technical Scripter 2019 Articles GBlog Python Technical Scripter TechTips Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Time Complexity and Space Complexity Docker - COPY Instruction Time complexities of different data structures SQL | Date functions Difference between Class and Object Roadmap to Become a Web Developer in 2022 Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Socket Programming in C/C++ DSA Sheet by Love Babbar Must Do Coding Questions for Product Based Companies
[ { "code": null, "e": 24344, "s": 24316, "text": "\n23 Jan, 2020" }, { "code": null, "e": 24663, "s": 24344, "text": "Prerequisite : django installationWith the growth of data, data visualization in become a import part here we will implement chart for our data in our web apps using chartjs with django. Django is a high-level Python Web framework based web framework and chartjs is an easy way to include animated, interactive graphs." }, { "code": null, "e": 24682, "s": 24663, "text": "Modules required :" }, { "code": null, "e": 24706, "s": 24682, "text": "django : install django" }, { "code": null, "e": 24759, "s": 24706, "text": "djangorestframework$ pip install djangorestframework" }, { "code": null, "e": 24793, "s": 24759, "text": "$ pip install djangorestframework" }, { "code": null, "e": 24807, "s": 24793, "text": "basic setup :" }, { "code": null, "e": 24850, "s": 24807, "text": "Start a project by the following command –" }, { "code": null, "e": 24885, "s": 24850, "text": "$ django-admin startproject charts" }, { "code": null, "e": 24914, "s": 24885, "text": "Change directory to charts –" }, { "code": null, "e": 24926, "s": 24914, "text": "$ cd charts" }, { "code": null, "e": 25003, "s": 24926, "text": "Start the server- Start the server by typing following command in terminal –" }, { "code": null, "e": 25032, "s": 25003, "text": "$ python manage.py runserver" }, { "code": null, "e": 25139, "s": 25032, "text": "To check whether the server is running or not go to a web browser and enter http://127.0.0.1:8000/ as URL." }, { "code": null, "e": 25178, "s": 25139, "text": "Now stop the server by pressing ctrl+C" }, { "code": null, "e": 25203, "s": 25178, "text": "Let’s create an app now." }, { "code": null, "e": 25239, "s": 25203, "text": "$ python manage.py startapp chartjs" }, { "code": null, "e": 25270, "s": 25239, "text": "Goto chartjs/ folder by doing:" }, { "code": null, "e": 25283, "s": 25270, "text": "$ cd chartjs" }, { "code": null, "e": 25354, "s": 25283, "text": "and create a folder with index.html file: templates/chartjs/index.html" }, { "code": null, "e": 25427, "s": 25354, "text": "$ mkdir -p templates/chartjs && cd templates/chartjs && touch index.html" }, { "code": null, "e": 25520, "s": 25427, "text": "Open the project folder using a text editor. The directory structure should look like this :" }, { "code": null, "e": 25590, "s": 25520, "text": "Now add chartjs app and rest_framework in your charts in settings.py." }, { "code": null, "e": 25620, "s": 25590, "text": "Edit urls.py file in charts :" }, { "code": "from django.contrib import adminfrom django.urls import pathfrom chartjs import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.HomeView.as_view()), # path('test-api', views.get_data), path('api', views.ChartData.as_view()),]", "e": 25881, "s": 25620, "text": null }, { "code": null, "e": 25908, "s": 25881, "text": "Edit views.py in chartjs :" }, { "code": "# from django.http import JsonResponse from django.shortcuts import renderfrom django.views.generic import View from rest_framework.views import APIViewfrom rest_framework.response import Response class HomeView(View): def get(self, request, *args, **kwargs): return render(request, 'chartjs/index.html') #################################################### ## if you don't want to user rest_framework # def get_data(request, *args, **kwargs):## data ={# \"sales\" : 100,# \"person\": 10000,# }## return JsonResponse(data) # http response ####################################################### ## using rest_framework classes class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format = None): labels = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July' ] chartLabel = \"my data\" chartdata = [0, 10, 5, 2, 20, 30, 45] data ={ \"labels\":labels, \"chartLabel\":chartLabel, \"chartdata\":chartdata, } return Response(data)", "e": 27156, "s": 25908, "text": null }, { "code": null, "e": 27210, "s": 27156, "text": "Navigate to templates/chartjs/index.html and edit it." }, { "code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title>chatsjs</title> <!-- Latest compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <!-- jQuery library --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"></script> <!-- Latest compiled JavaScript --> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"></script> </head> <body class=\"container-fluid\"> <center class=\"row\"> <h1>implementation of <b>chartJS</b> using <b>django</b></h1> </center> <hr /> <div class=\"row\"> <div class=\"col-md-6\"> <canvas id=\"myChartline\"></canvas> </div> <div class=\"col-md-6\"> <canvas id=\"myChartBar\"></canvas> </div> </div> <script src=\"https://cdn.jsdelivr.net/npm/chart.js@2.8.0\"></script> <script> var endpoint = '/api'; $.ajax({ method: \"GET\", url: endpoint, success: function(data) { drawLineGraph(data, 'myChartline'); drawBarGraph(data, 'myChartBar'); console.log(\"drawing\"); }, error: function(error_data) { console.log(error_data); } }) function drawLineGraph(data, id) { var labels = data.labels; var chartLabel = data.chartLabel; var chartdata = data.chartdata; var ctx = document.getElementById(id).getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'line', // The data for our dataset data: { labels: labels, datasets: [{ label: chartLabel, backgroundColor: 'rgb(255, 100, 200)', borderColor: 'rgb(55, 99, 132)', data: chartdata, }] }, // Configuration options go here options: { scales: { xAxes: [{ display: true }], yAxes: [{ ticks: { beginAtZero: true } }] } } }); } function drawBarGraph(data, id) { var labels = data.labels; var chartLabel = data.chartLabel; var chartdata = data.chartdata; var ctx = document.getElementById(id).getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: chartLabel, data: chartdata, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); } </script></body> </html>", "e": 30481, "s": 27210, "text": null }, { "code": null, "e": 30514, "s": 30481, "text": "Make migrations and migrate it :" }, { "code": null, "e": 30576, "s": 30514, "text": "$ python manage.py makemigrations\n$ python manage.py migrate\n" }, { "code": null, "e": 30621, "s": 30576, "text": "Now you can run the server to see your app :" }, { "code": null, "e": 30650, "s": 30621, "text": "$ python manage.py runserver" }, { "code": null, "e": 30674, "s": 30650, "text": "Technical Scripter 2019" }, { "code": null, "e": 30683, "s": 30674, "text": "Articles" }, { "code": null, "e": 30689, "s": 30683, "text": "GBlog" }, { "code": null, "e": 30696, "s": 30689, "text": "Python" }, { "code": null, "e": 30715, "s": 30696, "text": "Technical Scripter" }, { "code": null, "e": 30724, "s": 30715, "text": "TechTips" }, { "code": null, "e": 30741, "s": 30724, "text": "Web Technologies" }, { "code": null, "e": 30839, "s": 30741, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30848, "s": 30839, "text": "Comments" }, { "code": null, "e": 30861, "s": 30848, "text": "Old Comments" }, { "code": null, "e": 30898, "s": 30861, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 30924, "s": 30898, "text": "Docker - COPY Instruction" }, { "code": null, "e": 30971, "s": 30924, "text": "Time complexities of different data structures" }, { "code": null, "e": 30992, "s": 30971, "text": "SQL | Date functions" }, { "code": null, "e": 31028, "s": 30992, "text": "Difference between Class and Object" }, { "code": null, "e": 31070, "s": 31028, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 31144, "s": 31070, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 31172, "s": 31144, "text": "Socket Programming in C/C++" }, { "code": null, "e": 31197, "s": 31172, "text": "DSA Sheet by Love Babbar" } ]
Python Pandas - Get the week of the year on the given Period
To get the week of the year on the given Period, use the period.weekofyear property. At first, import the required libraries − import pandas as pd The pandas.Period represents a period of time. Creating two Period objects period1 = pd.Period("2020-09-23") period2 = pd.Period(freq="D", year = 2021, month = 4, day = 16, hour = 2, minute = 35) Display the Period objects print("Period1...\n", period1) print("Period2...\n", period2) Get the week of the year from two Period objects res1 = period1.weekofyear res2 = period2.weekofyear Following is the code import pandas as pd # The pandas.Period represents a period of time # creating two Period objects period1 = pd.Period("2020-09-23") period2 = pd.Period(freq="D", year = 2021, month = 4, day = 16, hour = 2, minute = 35) # display the Period objects print("Period1...\n", period1) print("Period2...\n", period2) # get the week of the year from two Period objects res1 = period1.weekofyear res2 = period2.weekofyear # Return the week of the year from the two Period objects print("\nWeek of the year from the 1st Period object ...\n", res1) print("\nWeek of the year from the 2nd Period object...\n", res2) This will produce the following code Period1... 2020-09-23 Period2... 2021-04-16 Week of the year from the 1st Period object ... 39 Week of the year from the 2nd Period object... 15
[ { "code": null, "e": 1189, "s": 1062, "text": "To get the week of the year on the given Period, use the period.weekofyear property. At first, import the required libraries −" }, { "code": null, "e": 1209, "s": 1189, "text": "import pandas as pd" }, { "code": null, "e": 1284, "s": 1209, "text": "The pandas.Period represents a period of time. Creating two Period objects" }, { "code": null, "e": 1405, "s": 1284, "text": "period1 = pd.Period(\"2020-09-23\")\nperiod2 = pd.Period(freq=\"D\", year = 2021, month = 4, day = 16, hour = 2, minute = 35)" }, { "code": null, "e": 1432, "s": 1405, "text": "Display the Period objects" }, { "code": null, "e": 1494, "s": 1432, "text": "print(\"Period1...\\n\", period1)\nprint(\"Period2...\\n\", period2)" }, { "code": null, "e": 1543, "s": 1494, "text": "Get the week of the year from two Period objects" }, { "code": null, "e": 1595, "s": 1543, "text": "res1 = period1.weekofyear\nres2 = period2.weekofyear" }, { "code": null, "e": 1617, "s": 1595, "text": "Following is the code" }, { "code": null, "e": 2225, "s": 1617, "text": "import pandas as pd\n\n# The pandas.Period represents a period of time\n# creating two Period objects\nperiod1 = pd.Period(\"2020-09-23\")\nperiod2 = pd.Period(freq=\"D\", year = 2021, month = 4, day = 16, hour = 2, minute = 35)\n\n# display the Period objects\nprint(\"Period1...\\n\", period1)\nprint(\"Period2...\\n\", period2)\n\n# get the week of the year from two Period objects\nres1 = period1.weekofyear\nres2 = period2.weekofyear\n\n# Return the week of the year from the two Period objects\nprint(\"\\nWeek of the year from the 1st Period object ...\\n\", res1)\nprint(\"\\nWeek of the year from the 2nd Period object...\\n\", res2)" }, { "code": null, "e": 2262, "s": 2225, "text": "This will produce the following code" }, { "code": null, "e": 2409, "s": 2262, "text": "Period1...\n2020-09-23\nPeriod2...\n2021-04-16\n\nWeek of the year from the 1st Period object ...\n39\n\nWeek of the year from the 2nd Period object...\n15" } ]
Demystify Mortgage Loan By Building a Python Simulator | by Bee Guan Teo | Towards Data Science
A mortgage loan is more than just a monthly repayment based on an agreed amount within a stipulated payment tenure. A mortgage loan can easily jeopardize our finance if without a good understanding of its repayment mechanism and its potential risks. Here we are going to walk through a step by step practical guide to develop a Python simulator that can simulate mortgage loan repayment in a long term. The simulator will also enable us to visualize the loan amortization and the future growth of our home equity. You might be surprised to see a seemingly slightly higher loan interest rate can affect home equity heavily. Before starting the development process, we will need to ensure the following libraries are available in our machine: Streamlit — https://www.streamlit.io/Plotly — https://plotly.com/python/Numpy — https://numpy.org/ Streamlit — https://www.streamlit.io/ Plotly — https://plotly.com/python/ Numpy — https://numpy.org/ If you wish to use my codes to follow the article, you can get the full source codes at my Github Repo. You may also run my code obtained from my GitHub repo (MortgageSimulator.py) to preview the app. Ensure that you have set up the Streamlit properly in your machine. You may refer to Streamlit website for further information. Firstly, we import all the required libraries in our program. Here we are going to start using Streamlit to build our simulator. Streamlit is an open-source Python framework to develop a data app. Firstly, let us set our page title for our browser tab and the main page. Line 1: Use page_title inside the Streamlit set_page_config to define a title for our browser tab. Line 2: Create the main title of our simulator. At this point, we can try to run the Streamlit app to visualize the output. To do so, we type the following command in our terminal/command prompt. streamlit run YourPythonFileName.py (Note: Ensure that you have navigated to your directory where you keep your script file before running the app.) We should see the output as follows: In order to simulate mortgage payment, we need four pieces of information and they are home value, down payment percentage, loan interest rate and payment period. In this section, we will build four numerical input fields using Streamlit to get user input on the four pieces of information stated above. Line 1: Create a header. Line 2: Define two columns to place our input fields. Line 4–9: In the first column, create relevant subheaders and use Streamlit number_input method to create the numerical input fields for home value and interest rate. We set the minimum value to zero and the input format to decimal number. Line 11–16: In the second column, repeat the similar process above to create relevant subheaders and numerical input fields for the down payment percentage and payment period in years. With the four pieces of information ready, we can now proceed to calculate the monthly instalments. This will give us a crude idea of our monthly commitment to mortgage repayment. Line 1–4: Calculate loan amount by deducting the down payment from home value. Multiply payment years by twelves to get the total number of payment months. Convert interest rate to a decimal. Line 5–6: Based on the input interest rate, we calculate the periodic interest rate using the formula Periodic interest rate is the annual interest rate expressed over a shorter period (e.g. 1 month). Since the mortgage repayment is on monthly basis, here our aim is to obtain monthly periodic interest and therefore the N=12. At last, use Numpy pmt method to compute the monthly instalment amount based on the periodic interest rate, the total number of payment months, and the loan amount. Numpy pmt method will encapsulate the calculation logic and automatically result in a monthly instalment amount. Line 8–10: Display down payment, loan amount and the monthly instalment to our simulator. Let us try to input a sample set of values on those numerical input fields of the mortgage details: Home Value — 500000 Down Payment Percent — 10 Loan Interest Rate — 4.5 Target Payment Period in years— 30 The simulator processes our sample input and results in a monthly instalment of $2256.02. At this stage, our simulator is able to estimate a monthly instalment amount based on the input values of the mortgage details given by us. However, the monthly instalment amount alone doesn’t give us an idea about how much of our payment contributed to the loan principal and loan interest, respectively. Although the monthly instalment is the same amount in total for each month, the amount fraction that covers the loan principal and loan interest will differ over time. In this section, we will generate an amortization schedule for the mortgage loan. The amortization schedule is a table that shows the amount of loan principal and loan interest that comprise each monthly instalment until the loan is totally paid off. Besides, we will also plot a chart to project a visualization of the monthly changes of loan principal and loan interest that comprise our monthly instalments. Line 4–6: Create three Numpy series to hold the values of the remaining principal, the principal paid and the interest paid every month. Initialize each of the Numpy series with zeros. Line 8–23: Create a loop to iteratively calculate the principal and interest payments that comprise the current month instalment. The current interest payment is computed based on the multiplication of the periodic interest rate with the previous remaining principal (Line 15). Subtract the resulting interest payment from the monthly instalment will result in the principal payment for that particular month (Line 16). Store the current interest payment, principal payment and the remaining principal to the three Numpy series created earlier (Line 21–23). Line 31–37: Use the Python Plotly make_subplots method to create a composite figure that entails a table and a chart. Line 39–49: Use Plotly go.Table object to create a table that shows the monthly principal payment, the interest payment and the remaining principal. Plug in the Numpy series created earlier into the values of the cells (Line 44–46). Use add_trace method to add the table into the composite figure object. Line 51–58: Use Plotly go.Scatter object to create a line plot for the principal payment over months. Set the Numpy series of principal payment as the y-axis value. Use the add_trace method again to add the plot to the composite figure object. Line 60–67: In a similar way, use Plotly go.Scatter object to create a line plot for the interest payment over months. For this time, we use append_trace method to add the line plot so that it will be overlaid with the line plot for the principal payment in the same chart. Line 69–81: Configure the layout for the composite figure by setting the relevant title, dimension and legends. Line 83: Use Streamlit plotly_chart method to render the composite figure. From the amortization table and the line plots above, we can observe the majority of our monthly instalment is used to cover the loan interest at the early stage of our payment schedule. Only a small fraction of our instalment contribute to the principal payment in the first few years. However, this trend is changed over time. Since the interest payment is calculated based on the periodic interest rate of the previous remaining principal, a consistent repayment will result in a steady decrease of the interest payment from one month to another month. At the later stage of the amortization schedule, we will find the majority of the monthly instalment is used to cover our loan principal. A consistent repayment of the mortgage loan does not only reduce our interest payment from time to time but also keep increasing our home equity. Basically, home equity is the portion of a home’s current value that we actually possess at any given time. Let’s say we purchase a property at a $500,000 market price and our down payment is 10%. This means our initial home equity is equivalent to our down payment which is $50,000. When we start our mortgage repayment, our home equity will be accumulated whenever an instalment is made. For example, if we have made three months instalment which covers a total of $2700 cumulative principal payment, our latest home equity is $50,000 + $2700 = $52700. By presuming the market value of the house remains constant throughout our repayment period, our home equity will be equivalent to the $500,000 market price at the end of our mortgage tenure. Let us add a plot to our simulator to show a clearer picture. Line 4–5: Use Numpy cumsum method to obtain the cumulative sum of the principal payment and the interest payment series. The cumulative sum of the principal payment is equivalent to cumulative home equity (presuming that the market value of the property remains unchanged). Line 7: Create a Plotly Fig object to show the line plots. Line 8–14: Use Plotly go.Scatter object to create a line plot to show cumulative home equity over months. Use add_trace method to add the line plot to the fig object. Line 16–22: In a similar way, use Plotly go.Scatter object to create another line plot to show the cumulative interest paid over months and add it to the fig object. Line 24–36: Configure the layout by setting the title name, x-axis & y-axis title, dimension and legends of the chart figure. From the line chart above, we can see our cumulative home equity keep increasing from month to month until it reaches its peak at the end of the repayment period. Besides, we can also observe that our cumulative home equity will only overtake cumulative interest payment roughly after Month-314 (approaching the end of the repayment period). Let’s say if we adjust our loan annual interest rate in our simulator and lower it from 4.5 to 4. Once a value is changed, our plot will be updated automatically as below. With a 0.5% lower annual interest rate, we can observe that the final cumulative interest paid is reduced significantly. Our cumulative home equity will overtake the cumulative interest roughly after Month-278. This is the reason we always look for a financial institution that can offer us the best interest rate for our mortgage. Now, what if we adjust our payment period from 30 years to 25 years? Let see how will it affect our cumulative home equity over time. With a shorter loan repayment tenure, the cumulative interest paid is reduced drastically. Our cumulative home equity will be higher than the cumulative interest paid roughly right after the midterm of our mortgage tenure. This shows that while we can pay for a lower monthly instalment with a longer tenure, we bear a hefty cost of interest in the long run. There should be a balance in controlling our current financial commitment and the profit in the longer term. At last, let us add a growth forecast feature to our mortgage simulator. In the previous section, the evolvement of our home equity is solely based on our principal payment through the entire loan tenure without considering the growth of the home market value. What will happen to our home equity if the market value of our home has been changed from year to year (which always happen). This is important to note that the growth is not necessarily positive. There can be negative growth as well. Here we add another input field to get user input on the forecast growth rate in our simulator and also create a line chart to show the forecast home value and forecast home equity over time. Line 4–5: Create a relevant subheader and a new numerical input field for the home market value growth rate per year. Line 7–8: Convert the annual forecast growth rate into monthly growth. Create a growth array and populate it with the monthly growth rate using Numpy full method. Line 9–10: Use Numpy cumprod method to compute the cumulative product of the growth rate over the months. Multiply the resulting cumulative growth with the original home value. This will result in a forecast home value series. Line 11–12: Compute the cumulative percentage of home ownership over the months. Multiply this cumulative percentage with the forecast home value series and this will result in a forecast home equity series. Line 14–51: Repeat the similar step presented in the earlier section to create the line plots to show the forecast home value over the months, forecast home equity over the months and the principal remaining over the months. The three line plots are added to the same chart figure using the Plotly add_trace method. Configure the chart figure layout by setting a relevant title, x-axis & y-axis title, dimension and legends. Line 53: Render the chart figure. By setting a 3% growth rate per year, we will see our home market value will be doubled after 300 months (25 years). While we are still serving our mortgage with the same monthly instalment, our home equity has exceeded the original home value ($500,000) after 202 months. At the end of our repayment period, our home equity is equivalent to the forecast home value which is 200% of the original home value. Such increment of home equity can provide us with a chance to apply for a home equity loan that can convert our equity into cash. Now, let try to tweak the growth rate again with a negative value, -5 and see how it affects our home equity over the times. From the line plots above, we can observe that the home value is heavily depreciated to around 30% of the original market value after 300 months (25 years). This also means our home equity will also be depreciated as well at the end of our mortgage tenure. We suffer a great loss from a depreciated property. Besides, there is quite a long period of time (around Month-57 to Month-169), our home value falls under the remaining principal amount. Such a situation is known as an underwater mortgage. During this period, we will not have any equity available for credit and may even prevent us from selling the home unless we have sufficient cash to pay the loss. Underwater mortgages were a common problem during the Financial Crisis of 2008. Home investment can be very rewarding but it is a long term process which is full of risk. It requires careful market analysis and good self-control in our own financial planning. Hopefully, the Python simulator presented here will give you some vivid ideas about mortgage loan. Any investment would never be a random guess activity but will require some solid projection of future scenario which will help us to make a more decent decision. I wish you enjoy reading this article.
[ { "code": null, "e": 422, "s": 172, "text": "A mortgage loan is more than just a monthly repayment based on an agreed amount within a stipulated payment tenure. A mortgage loan can easily jeopardize our finance if without a good understanding of its repayment mechanism and its potential risks." }, { "code": null, "e": 795, "s": 422, "text": "Here we are going to walk through a step by step practical guide to develop a Python simulator that can simulate mortgage loan repayment in a long term. The simulator will also enable us to visualize the loan amortization and the future growth of our home equity. You might be surprised to see a seemingly slightly higher loan interest rate can affect home equity heavily." }, { "code": null, "e": 913, "s": 795, "text": "Before starting the development process, we will need to ensure the following libraries are available in our machine:" }, { "code": null, "e": 1012, "s": 913, "text": "Streamlit — https://www.streamlit.io/Plotly — https://plotly.com/python/Numpy — https://numpy.org/" }, { "code": null, "e": 1050, "s": 1012, "text": "Streamlit — https://www.streamlit.io/" }, { "code": null, "e": 1086, "s": 1050, "text": "Plotly — https://plotly.com/python/" }, { "code": null, "e": 1113, "s": 1086, "text": "Numpy — https://numpy.org/" }, { "code": null, "e": 1217, "s": 1113, "text": "If you wish to use my codes to follow the article, you can get the full source codes at my Github Repo." }, { "code": null, "e": 1442, "s": 1217, "text": "You may also run my code obtained from my GitHub repo (MortgageSimulator.py) to preview the app. Ensure that you have set up the Streamlit properly in your machine. You may refer to Streamlit website for further information." }, { "code": null, "e": 1504, "s": 1442, "text": "Firstly, we import all the required libraries in our program." }, { "code": null, "e": 1639, "s": 1504, "text": "Here we are going to start using Streamlit to build our simulator. Streamlit is an open-source Python framework to develop a data app." }, { "code": null, "e": 1713, "s": 1639, "text": "Firstly, let us set our page title for our browser tab and the main page." }, { "code": null, "e": 1812, "s": 1713, "text": "Line 1: Use page_title inside the Streamlit set_page_config to define a title for our browser tab." }, { "code": null, "e": 1860, "s": 1812, "text": "Line 2: Create the main title of our simulator." }, { "code": null, "e": 2008, "s": 1860, "text": "At this point, we can try to run the Streamlit app to visualize the output. To do so, we type the following command in our terminal/command prompt." }, { "code": null, "e": 2044, "s": 2008, "text": "streamlit run YourPythonFileName.py" }, { "code": null, "e": 2157, "s": 2044, "text": "(Note: Ensure that you have navigated to your directory where you keep your script file before running the app.)" }, { "code": null, "e": 2194, "s": 2157, "text": "We should see the output as follows:" }, { "code": null, "e": 2357, "s": 2194, "text": "In order to simulate mortgage payment, we need four pieces of information and they are home value, down payment percentage, loan interest rate and payment period." }, { "code": null, "e": 2498, "s": 2357, "text": "In this section, we will build four numerical input fields using Streamlit to get user input on the four pieces of information stated above." }, { "code": null, "e": 2523, "s": 2498, "text": "Line 1: Create a header." }, { "code": null, "e": 2577, "s": 2523, "text": "Line 2: Define two columns to place our input fields." }, { "code": null, "e": 2817, "s": 2577, "text": "Line 4–9: In the first column, create relevant subheaders and use Streamlit number_input method to create the numerical input fields for home value and interest rate. We set the minimum value to zero and the input format to decimal number." }, { "code": null, "e": 3002, "s": 2817, "text": "Line 11–16: In the second column, repeat the similar process above to create relevant subheaders and numerical input fields for the down payment percentage and payment period in years." }, { "code": null, "e": 3182, "s": 3002, "text": "With the four pieces of information ready, we can now proceed to calculate the monthly instalments. This will give us a crude idea of our monthly commitment to mortgage repayment." }, { "code": null, "e": 3374, "s": 3182, "text": "Line 1–4: Calculate loan amount by deducting the down payment from home value. Multiply payment years by twelves to get the total number of payment months. Convert interest rate to a decimal." }, { "code": null, "e": 3476, "s": 3374, "text": "Line 5–6: Based on the input interest rate, we calculate the periodic interest rate using the formula" }, { "code": null, "e": 3979, "s": 3476, "text": "Periodic interest rate is the annual interest rate expressed over a shorter period (e.g. 1 month). Since the mortgage repayment is on monthly basis, here our aim is to obtain monthly periodic interest and therefore the N=12. At last, use Numpy pmt method to compute the monthly instalment amount based on the periodic interest rate, the total number of payment months, and the loan amount. Numpy pmt method will encapsulate the calculation logic and automatically result in a monthly instalment amount." }, { "code": null, "e": 4069, "s": 3979, "text": "Line 8–10: Display down payment, loan amount and the monthly instalment to our simulator." }, { "code": null, "e": 4169, "s": 4069, "text": "Let us try to input a sample set of values on those numerical input fields of the mortgage details:" }, { "code": null, "e": 4189, "s": 4169, "text": "Home Value — 500000" }, { "code": null, "e": 4215, "s": 4189, "text": "Down Payment Percent — 10" }, { "code": null, "e": 4240, "s": 4215, "text": "Loan Interest Rate — 4.5" }, { "code": null, "e": 4275, "s": 4240, "text": "Target Payment Period in years— 30" }, { "code": null, "e": 4365, "s": 4275, "text": "The simulator processes our sample input and results in a monthly instalment of $2256.02." }, { "code": null, "e": 4839, "s": 4365, "text": "At this stage, our simulator is able to estimate a monthly instalment amount based on the input values of the mortgage details given by us. However, the monthly instalment amount alone doesn’t give us an idea about how much of our payment contributed to the loan principal and loan interest, respectively. Although the monthly instalment is the same amount in total for each month, the amount fraction that covers the loan principal and loan interest will differ over time." }, { "code": null, "e": 5250, "s": 4839, "text": "In this section, we will generate an amortization schedule for the mortgage loan. The amortization schedule is a table that shows the amount of loan principal and loan interest that comprise each monthly instalment until the loan is totally paid off. Besides, we will also plot a chart to project a visualization of the monthly changes of loan principal and loan interest that comprise our monthly instalments." }, { "code": null, "e": 5435, "s": 5250, "text": "Line 4–6: Create three Numpy series to hold the values of the remaining principal, the principal paid and the interest paid every month. Initialize each of the Numpy series with zeros." }, { "code": null, "e": 5993, "s": 5435, "text": "Line 8–23: Create a loop to iteratively calculate the principal and interest payments that comprise the current month instalment. The current interest payment is computed based on the multiplication of the periodic interest rate with the previous remaining principal (Line 15). Subtract the resulting interest payment from the monthly instalment will result in the principal payment for that particular month (Line 16). Store the current interest payment, principal payment and the remaining principal to the three Numpy series created earlier (Line 21–23)." }, { "code": null, "e": 6111, "s": 5993, "text": "Line 31–37: Use the Python Plotly make_subplots method to create a composite figure that entails a table and a chart." }, { "code": null, "e": 6416, "s": 6111, "text": "Line 39–49: Use Plotly go.Table object to create a table that shows the monthly principal payment, the interest payment and the remaining principal. Plug in the Numpy series created earlier into the values of the cells (Line 44–46). Use add_trace method to add the table into the composite figure object." }, { "code": null, "e": 6660, "s": 6416, "text": "Line 51–58: Use Plotly go.Scatter object to create a line plot for the principal payment over months. Set the Numpy series of principal payment as the y-axis value. Use the add_trace method again to add the plot to the composite figure object." }, { "code": null, "e": 6934, "s": 6660, "text": "Line 60–67: In a similar way, use Plotly go.Scatter object to create a line plot for the interest payment over months. For this time, we use append_trace method to add the line plot so that it will be overlaid with the line plot for the principal payment in the same chart." }, { "code": null, "e": 7046, "s": 6934, "text": "Line 69–81: Configure the layout for the composite figure by setting the relevant title, dimension and legends." }, { "code": null, "e": 7121, "s": 7046, "text": "Line 83: Use Streamlit plotly_chart method to render the composite figure." }, { "code": null, "e": 7408, "s": 7121, "text": "From the amortization table and the line plots above, we can observe the majority of our monthly instalment is used to cover the loan interest at the early stage of our payment schedule. Only a small fraction of our instalment contribute to the principal payment in the first few years." }, { "code": null, "e": 7815, "s": 7408, "text": "However, this trend is changed over time. Since the interest payment is calculated based on the periodic interest rate of the previous remaining principal, a consistent repayment will result in a steady decrease of the interest payment from one month to another month. At the later stage of the amortization schedule, we will find the majority of the monthly instalment is used to cover our loan principal." }, { "code": null, "e": 8069, "s": 7815, "text": "A consistent repayment of the mortgage loan does not only reduce our interest payment from time to time but also keep increasing our home equity. Basically, home equity is the portion of a home’s current value that we actually possess at any given time." }, { "code": null, "e": 8516, "s": 8069, "text": "Let’s say we purchase a property at a $500,000 market price and our down payment is 10%. This means our initial home equity is equivalent to our down payment which is $50,000. When we start our mortgage repayment, our home equity will be accumulated whenever an instalment is made. For example, if we have made three months instalment which covers a total of $2700 cumulative principal payment, our latest home equity is $50,000 + $2700 = $52700." }, { "code": null, "e": 8708, "s": 8516, "text": "By presuming the market value of the house remains constant throughout our repayment period, our home equity will be equivalent to the $500,000 market price at the end of our mortgage tenure." }, { "code": null, "e": 8770, "s": 8708, "text": "Let us add a plot to our simulator to show a clearer picture." }, { "code": null, "e": 9044, "s": 8770, "text": "Line 4–5: Use Numpy cumsum method to obtain the cumulative sum of the principal payment and the interest payment series. The cumulative sum of the principal payment is equivalent to cumulative home equity (presuming that the market value of the property remains unchanged)." }, { "code": null, "e": 9103, "s": 9044, "text": "Line 7: Create a Plotly Fig object to show the line plots." }, { "code": null, "e": 9270, "s": 9103, "text": "Line 8–14: Use Plotly go.Scatter object to create a line plot to show cumulative home equity over months. Use add_trace method to add the line plot to the fig object." }, { "code": null, "e": 9436, "s": 9270, "text": "Line 16–22: In a similar way, use Plotly go.Scatter object to create another line plot to show the cumulative interest paid over months and add it to the fig object." }, { "code": null, "e": 9562, "s": 9436, "text": "Line 24–36: Configure the layout by setting the title name, x-axis & y-axis title, dimension and legends of the chart figure." }, { "code": null, "e": 9904, "s": 9562, "text": "From the line chart above, we can see our cumulative home equity keep increasing from month to month until it reaches its peak at the end of the repayment period. Besides, we can also observe that our cumulative home equity will only overtake cumulative interest payment roughly after Month-314 (approaching the end of the repayment period)." }, { "code": null, "e": 10076, "s": 9904, "text": "Let’s say if we adjust our loan annual interest rate in our simulator and lower it from 4.5 to 4. Once a value is changed, our plot will be updated automatically as below." }, { "code": null, "e": 10408, "s": 10076, "text": "With a 0.5% lower annual interest rate, we can observe that the final cumulative interest paid is reduced significantly. Our cumulative home equity will overtake the cumulative interest roughly after Month-278. This is the reason we always look for a financial institution that can offer us the best interest rate for our mortgage." }, { "code": null, "e": 10542, "s": 10408, "text": "Now, what if we adjust our payment period from 30 years to 25 years? Let see how will it affect our cumulative home equity over time." }, { "code": null, "e": 11010, "s": 10542, "text": "With a shorter loan repayment tenure, the cumulative interest paid is reduced drastically. Our cumulative home equity will be higher than the cumulative interest paid roughly right after the midterm of our mortgage tenure. This shows that while we can pay for a lower monthly instalment with a longer tenure, we bear a hefty cost of interest in the long run. There should be a balance in controlling our current financial commitment and the profit in the longer term." }, { "code": null, "e": 11271, "s": 11010, "text": "At last, let us add a growth forecast feature to our mortgage simulator. In the previous section, the evolvement of our home equity is solely based on our principal payment through the entire loan tenure without considering the growth of the home market value." }, { "code": null, "e": 11506, "s": 11271, "text": "What will happen to our home equity if the market value of our home has been changed from year to year (which always happen). This is important to note that the growth is not necessarily positive. There can be negative growth as well." }, { "code": null, "e": 11698, "s": 11506, "text": "Here we add another input field to get user input on the forecast growth rate in our simulator and also create a line chart to show the forecast home value and forecast home equity over time." }, { "code": null, "e": 11816, "s": 11698, "text": "Line 4–5: Create a relevant subheader and a new numerical input field for the home market value growth rate per year." }, { "code": null, "e": 11979, "s": 11816, "text": "Line 7–8: Convert the annual forecast growth rate into monthly growth. Create a growth array and populate it with the monthly growth rate using Numpy full method." }, { "code": null, "e": 12206, "s": 11979, "text": "Line 9–10: Use Numpy cumprod method to compute the cumulative product of the growth rate over the months. Multiply the resulting cumulative growth with the original home value. This will result in a forecast home value series." }, { "code": null, "e": 12414, "s": 12206, "text": "Line 11–12: Compute the cumulative percentage of home ownership over the months. Multiply this cumulative percentage with the forecast home value series and this will result in a forecast home equity series." }, { "code": null, "e": 12839, "s": 12414, "text": "Line 14–51: Repeat the similar step presented in the earlier section to create the line plots to show the forecast home value over the months, forecast home equity over the months and the principal remaining over the months. The three line plots are added to the same chart figure using the Plotly add_trace method. Configure the chart figure layout by setting a relevant title, x-axis & y-axis title, dimension and legends." }, { "code": null, "e": 12873, "s": 12839, "text": "Line 53: Render the chart figure." }, { "code": null, "e": 13411, "s": 12873, "text": "By setting a 3% growth rate per year, we will see our home market value will be doubled after 300 months (25 years). While we are still serving our mortgage with the same monthly instalment, our home equity has exceeded the original home value ($500,000) after 202 months. At the end of our repayment period, our home equity is equivalent to the forecast home value which is 200% of the original home value. Such increment of home equity can provide us with a chance to apply for a home equity loan that can convert our equity into cash." }, { "code": null, "e": 13536, "s": 13411, "text": "Now, let try to tweak the growth rate again with a negative value, -5 and see how it affects our home equity over the times." }, { "code": null, "e": 13845, "s": 13536, "text": "From the line plots above, we can observe that the home value is heavily depreciated to around 30% of the original market value after 300 months (25 years). This also means our home equity will also be depreciated as well at the end of our mortgage tenure. We suffer a great loss from a depreciated property." }, { "code": null, "e": 14278, "s": 13845, "text": "Besides, there is quite a long period of time (around Month-57 to Month-169), our home value falls under the remaining principal amount. Such a situation is known as an underwater mortgage. During this period, we will not have any equity available for credit and may even prevent us from selling the home unless we have sufficient cash to pay the loss. Underwater mortgages were a common problem during the Financial Crisis of 2008." }, { "code": null, "e": 14720, "s": 14278, "text": "Home investment can be very rewarding but it is a long term process which is full of risk. It requires careful market analysis and good self-control in our own financial planning. Hopefully, the Python simulator presented here will give you some vivid ideas about mortgage loan. Any investment would never be a random guess activity but will require some solid projection of future scenario which will help us to make a more decent decision." } ]
Determining the position and length of the match Java regex
The start() method of the java.util.regex.Matcher class returns the starting position of the match (if a match occurred). Similarly, the end() method of the Matcher class returns the ending position of the match. Therefore, return value of the start() method will be the starting position of the match and the difference between the return values of the end() and start() methods will be the length of the match. Live Demo import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherExample { public static void main(String[] args) { int start = 0, len = -1; Scanner sc = new Scanner(System.in); System.out.println("Enter input text: "); String input = sc.nextLine(); String regex = "\\d+"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(input); while (matcher.find()) { start = matcher.start(); len = matcher.end()-start; } System.out.println("Position of the match : "+start); System.out.println("Length of the match : "+len); } } Enter input text: sample data with digits 12345 Position of the match : 24 Length of the match : 5
[ { "code": null, "e": 1184, "s": 1062, "text": "The start() method of the java.util.regex.Matcher class returns the starting position of the match (if a match occurred)." }, { "code": null, "e": 1275, "s": 1184, "text": "Similarly, the end() method of the Matcher class returns the ending position of the match." }, { "code": null, "e": 1475, "s": 1275, "text": "Therefore, return value of the start() method will be the starting position of the match and the difference between the return values of the end() and start() methods will be the length of the match." }, { "code": null, "e": 1486, "s": 1475, "text": " Live Demo" }, { "code": null, "e": 2251, "s": 1486, "text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class MatcherExample {\n public static void main(String[] args) {\n int start = 0, len = -1;\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter input text: \");\n String input = sc.nextLine();\n String regex = \"\\\\d+\";\n //Creating a pattern object\n Pattern pattern = Pattern.compile(regex);\n //Matching the compiled pattern in the String\n Matcher matcher = pattern.matcher(input);\n while (matcher.find()) {\n start = matcher.start();\n len = matcher.end()-start;\n }\n System.out.println(\"Position of the match : \"+start);\n System.out.println(\"Length of the match : \"+len);\n }\n}" }, { "code": null, "e": 2350, "s": 2251, "text": "Enter input text:\nsample data with digits 12345\nPosition of the match : 24\nLength of the match : 5" } ]
What is Exploratory Spatial Data Analysis (ESDA)? | by Abdishakur | Towards Data Science
What do you do when you want to explore patterns from data based on locations. How do you know that your location data is not random? Is it enough to use the Correlation? Or are there any other statistical methods used for this kind of exploratory data analysis. In this tutorial, I show you how you can perform Exploratory data analysis for your location data with simple and easy steps used Python. The code is available also for this tutorial in Github. In Data Science, we tend to explore and investigate data before doing any modeling or processing task. This helps you identify patterns, summarize the main characteristics of the data, or test a hypothesis. The conventional Exploratory data analysis does not investigate the location component of the dataset explicitly but instead deals with the relationship between variables and how they affect each other. Correlation statistical methods are often used to explore the relationship between variables. In contrast, Exploratory Spatial Data Analysis (ESDA) correlates a specific variable to a location, taking into account the values of the same variable in the neighborhood. The methods used for this purpose are called Spatial Autocorrelation. Spatial autocorrelation is describing the presence (or absence) of spatial variations in a given variable. Like, conventional correlation methods, Spatial autocorrelation has positive and negative values. Positive spatial autocorrelation is when areas close to each other have similar values (High-high or Low-low). On the other hand, negative spatial autocorrelation indicates that neighborhood areas to be different (Low values next to high values). There are mainly two methods of Exploratory Spatial Data Analysis (ESDA): global and local spatial autocorrelation. The global spatial autocorrelation focuses on the overall trend in the dataset and tells us if the degree of clustering int eh dataset. In contrast, The local spatial autocorrelation detects variability and divergence in the dataset, which helps us identify hot spots and cold spots in the data. We use the Airbnb dataset (Point dataset) and Layer Super Output Areas — LSOA — neighborhoods (Polygon dataset) in London for this tutorial. We do spatial join to connect each point of Airbnb listings to neighborhood areas. If you like to understand and use the powerfull spatial join tool in your workflow. I have a tutorial here: towardsdatascience.com The dataset we use is spatially joined Airbnb properties in London with an average price of properties in each local area (Neighbourhood). For this tutorial, we use Pandas, Geopandas, and Python Spatial Analysis Library (Pysal) libraries. So let us import these libraries. import pandas as pdimport geopandas as gpdimport matplotlib.pyplot as pltimport pysalfrom pysal import esda, weightsfrom esda.moran import Moran, Moran_Localimport splotfrom splot.esda import moran_scatterplot, plot_moran, lisa_cluster We can read the data in Geopandas. avrg_price_airbnb = gpd.read_file(“london-airbnb-avrgprice.shp”)avrg_price_airbnb.head() Here are the first 5 rows of the Average prices of Airbnb properties in London. Since we have a geometry column (Latitude and Longitude), we can map the data. And here is a choropleth map of the average prices per neighborhood. Well, with this choropleth map, we can see binned price ranges, but that does not give us any statistics we can determine if there is spatial autocorrelation (Positive or Negative, or even where the hotspots and coldspots are. That is what we do next. Before we perform any spatial autocorrelation, we first need to determine the spatial weights and spatial lag. Spatial weights are how we determine the area’s neighborhood. There are different statistical methods that are used for determining spatial weights, and it is beyond this to provide an in-depth explanation of each in this article. One of the most commonly used spatial weights methods is Queen Contiguity Matrix, which we use. Here is a diagram explaining how the Queen contiguity matrix works ( included also is the rook contiguity matrix) To calculate Queen contiguity spatial weights, we use Pysal. w = weights.Queen.from_dataframe(avrg_price_airbnb, idVariable=”LSOA_CODE” )w.transform = "R" Spatial Lag is, on the other hand, is the product of spatial weights matrix for a given variable (in our case, the price). The spatial leg standardizes the rows and takes the average result of the price in each weighted neighborhood. avrg_price_airbnb[“w_price”] = weights.lag_spatial(w, avrg_price_airbnb[“price”]) Now, we created a new column in our table that holds the weighted price of each neighborhood. Global spatial autocorrelation determines the overall pattern in the dataset. Here we can calculate if there is a trend and summarize the variable of interest. Moran’s I statistics is typically used to determine the global spatial autocorrelation, so let us calculate that. y = avrg_price_airbnb[“price”]moran = Moran(y, w)moran.I And we get this number for this dataset 0.54. What does this number mean? This number summarises the statistics of the dataset, just like the mean does for non-spatial data. Moran’s I values range from -1 to 1. In our case, this number provides information that there is a positive spatial autocorrelation in this dataset. Remember that we are determining only the global autocorrelation with Moran’s I statistics. It does not tell us where this positive spatial autocorrelation exists ( We do that next). We use Moran’s I plot to visualize the global spatial autocorrelation, which is identical to other scatter plots, with a linear fit that shows the relationship between the two variables. fig, ax = moran_scatterplot(moran, aspect_equal=True)plt.show() Both Moran’s I and Moran’s I Scatter plot show positively correlated observations by location in the dataset. Let us see where we have spatial variations in the dataset. So far, we have only determined that there is a positive spatial autocorrelation between the price of properties in neighborhoods and their locations. But we have not detected where clusters are. Local Indicators of Spatial Association (LISA) is used to do that. LISA classifies areas into four groups: high values near to high values (HH), Low values with nearby low values (LL), Low values with high values in its neighborhood, and vice-versa. We had already calculated the weights (w) and determined the price as our variable of interest(y). To calculate Moran Local, we use Pysal’s functionality. # calculate Moran Local m_local = Moran_Local(y, w) And plot Moran’s Local Scatter Plot. # Plotfig, ax = moran_scatterplot(m_local, p=0.05)ax.set_xlabel(‘Price’)ax.set_ylabel(‘Spatial Lag of Price’)plt.text(1.95, 0.5, “HH”, fontsize=25)plt.text(1.95, -1.5, “HL”, fontsize=25)plt.text(-2, 1, “LH”, fontsize=25)plt.text(-1, -1, “LL”, fontsize=25)plt.show() The scatter plot divides the areas into the four groups, as we mentioned. Now, this is cool, and we can see all values classified into four groups, but the exciting part is to see where these values cluster together in a map. Again, there is a function in Pysal (splot) to plot a map of the LISA results. The map above shows the variation in the average price of Airbnb Properties. The red colors indicate neighborhoods clustered together, which have high prices surrounded by high prices as well (mostly the center of the city). The blue areas indicate where prices are low, also surrounded by areas with low-value prices (Mostly peripheries). Equally interesting is also Low-high and High-low area concentration. Compared to the Choropleth map we started with this tutorial, the LISA is much more decluttered and provides a clear picture of the dataset. Exploratory Spatial Data Analysis (ESDA) techniques are powerful tools that help you identify spatial autocorrelation and local clusters that you can apply in any given variable. In this tutorial, we have explored how we can perform Exploratory Data Analysis (EDA) for spatial data. The code for this tutorial is available in this GitHub with the notebooks and the data. github.com You can also directly run a Google Colab Notebook from here:
[ { "code": null, "e": 434, "s": 171, "text": "What do you do when you want to explore patterns from data based on locations. How do you know that your location data is not random? Is it enough to use the Correlation? Or are there any other statistical methods used for this kind of exploratory data analysis." }, { "code": null, "e": 628, "s": 434, "text": "In this tutorial, I show you how you can perform Exploratory data analysis for your location data with simple and easy steps used Python. The code is available also for this tutorial in Github." }, { "code": null, "e": 1132, "s": 628, "text": "In Data Science, we tend to explore and investigate data before doing any modeling or processing task. This helps you identify patterns, summarize the main characteristics of the data, or test a hypothesis. The conventional Exploratory data analysis does not investigate the location component of the dataset explicitly but instead deals with the relationship between variables and how they affect each other. Correlation statistical methods are often used to explore the relationship between variables." }, { "code": null, "e": 1375, "s": 1132, "text": "In contrast, Exploratory Spatial Data Analysis (ESDA) correlates a specific variable to a location, taking into account the values of the same variable in the neighborhood. The methods used for this purpose are called Spatial Autocorrelation." }, { "code": null, "e": 1827, "s": 1375, "text": "Spatial autocorrelation is describing the presence (or absence) of spatial variations in a given variable. Like, conventional correlation methods, Spatial autocorrelation has positive and negative values. Positive spatial autocorrelation is when areas close to each other have similar values (High-high or Low-low). On the other hand, negative spatial autocorrelation indicates that neighborhood areas to be different (Low values next to high values)." }, { "code": null, "e": 2239, "s": 1827, "text": "There are mainly two methods of Exploratory Spatial Data Analysis (ESDA): global and local spatial autocorrelation. The global spatial autocorrelation focuses on the overall trend in the dataset and tells us if the degree of clustering int eh dataset. In contrast, The local spatial autocorrelation detects variability and divergence in the dataset, which helps us identify hot spots and cold spots in the data." }, { "code": null, "e": 2571, "s": 2239, "text": "We use the Airbnb dataset (Point dataset) and Layer Super Output Areas — LSOA — neighborhoods (Polygon dataset) in London for this tutorial. We do spatial join to connect each point of Airbnb listings to neighborhood areas. If you like to understand and use the powerfull spatial join tool in your workflow. I have a tutorial here:" }, { "code": null, "e": 2594, "s": 2571, "text": "towardsdatascience.com" }, { "code": null, "e": 2733, "s": 2594, "text": "The dataset we use is spatially joined Airbnb properties in London with an average price of properties in each local area (Neighbourhood)." }, { "code": null, "e": 2867, "s": 2733, "text": "For this tutorial, we use Pandas, Geopandas, and Python Spatial Analysis Library (Pysal) libraries. So let us import these libraries." }, { "code": null, "e": 3103, "s": 2867, "text": "import pandas as pdimport geopandas as gpdimport matplotlib.pyplot as pltimport pysalfrom pysal import esda, weightsfrom esda.moran import Moran, Moran_Localimport splotfrom splot.esda import moran_scatterplot, plot_moran, lisa_cluster" }, { "code": null, "e": 3138, "s": 3103, "text": "We can read the data in Geopandas." }, { "code": null, "e": 3227, "s": 3138, "text": "avrg_price_airbnb = gpd.read_file(“london-airbnb-avrgprice.shp”)avrg_price_airbnb.head()" }, { "code": null, "e": 3307, "s": 3227, "text": "Here are the first 5 rows of the Average prices of Airbnb properties in London." }, { "code": null, "e": 3455, "s": 3307, "text": "Since we have a geometry column (Latitude and Longitude), we can map the data. And here is a choropleth map of the average prices per neighborhood." }, { "code": null, "e": 3707, "s": 3455, "text": "Well, with this choropleth map, we can see binned price ranges, but that does not give us any statistics we can determine if there is spatial autocorrelation (Positive or Negative, or even where the hotspots and coldspots are. That is what we do next." }, { "code": null, "e": 3818, "s": 3707, "text": "Before we perform any spatial autocorrelation, we first need to determine the spatial weights and spatial lag." }, { "code": null, "e": 4259, "s": 3818, "text": "Spatial weights are how we determine the area’s neighborhood. There are different statistical methods that are used for determining spatial weights, and it is beyond this to provide an in-depth explanation of each in this article. One of the most commonly used spatial weights methods is Queen Contiguity Matrix, which we use. Here is a diagram explaining how the Queen contiguity matrix works ( included also is the rook contiguity matrix)" }, { "code": null, "e": 4320, "s": 4259, "text": "To calculate Queen contiguity spatial weights, we use Pysal." }, { "code": null, "e": 4414, "s": 4320, "text": "w = weights.Queen.from_dataframe(avrg_price_airbnb, idVariable=”LSOA_CODE” )w.transform = \"R\"" }, { "code": null, "e": 4648, "s": 4414, "text": "Spatial Lag is, on the other hand, is the product of spatial weights matrix for a given variable (in our case, the price). The spatial leg standardizes the rows and takes the average result of the price in each weighted neighborhood." }, { "code": null, "e": 4730, "s": 4648, "text": "avrg_price_airbnb[“w_price”] = weights.lag_spatial(w, avrg_price_airbnb[“price”])" }, { "code": null, "e": 4824, "s": 4730, "text": "Now, we created a new column in our table that holds the weighted price of each neighborhood." }, { "code": null, "e": 5098, "s": 4824, "text": "Global spatial autocorrelation determines the overall pattern in the dataset. Here we can calculate if there is a trend and summarize the variable of interest. Moran’s I statistics is typically used to determine the global spatial autocorrelation, so let us calculate that." }, { "code": null, "e": 5155, "s": 5098, "text": "y = avrg_price_airbnb[“price”]moran = Moran(y, w)moran.I" }, { "code": null, "e": 5661, "s": 5155, "text": "And we get this number for this dataset 0.54. What does this number mean? This number summarises the statistics of the dataset, just like the mean does for non-spatial data. Moran’s I values range from -1 to 1. In our case, this number provides information that there is a positive spatial autocorrelation in this dataset. Remember that we are determining only the global autocorrelation with Moran’s I statistics. It does not tell us where this positive spatial autocorrelation exists ( We do that next)." }, { "code": null, "e": 5848, "s": 5661, "text": "We use Moran’s I plot to visualize the global spatial autocorrelation, which is identical to other scatter plots, with a linear fit that shows the relationship between the two variables." }, { "code": null, "e": 5912, "s": 5848, "text": "fig, ax = moran_scatterplot(moran, aspect_equal=True)plt.show()" }, { "code": null, "e": 6082, "s": 5912, "text": "Both Moran’s I and Moran’s I Scatter plot show positively correlated observations by location in the dataset. Let us see where we have spatial variations in the dataset." }, { "code": null, "e": 6528, "s": 6082, "text": "So far, we have only determined that there is a positive spatial autocorrelation between the price of properties in neighborhoods and their locations. But we have not detected where clusters are. Local Indicators of Spatial Association (LISA) is used to do that. LISA classifies areas into four groups: high values near to high values (HH), Low values with nearby low values (LL), Low values with high values in its neighborhood, and vice-versa." }, { "code": null, "e": 6683, "s": 6528, "text": "We had already calculated the weights (w) and determined the price as our variable of interest(y). To calculate Moran Local, we use Pysal’s functionality." }, { "code": null, "e": 6735, "s": 6683, "text": "# calculate Moran Local m_local = Moran_Local(y, w)" }, { "code": null, "e": 6772, "s": 6735, "text": "And plot Moran’s Local Scatter Plot." }, { "code": null, "e": 7038, "s": 6772, "text": "# Plotfig, ax = moran_scatterplot(m_local, p=0.05)ax.set_xlabel(‘Price’)ax.set_ylabel(‘Spatial Lag of Price’)plt.text(1.95, 0.5, “HH”, fontsize=25)plt.text(1.95, -1.5, “HL”, fontsize=25)plt.text(-2, 1, “LH”, fontsize=25)plt.text(-1, -1, “LL”, fontsize=25)plt.show()" }, { "code": null, "e": 7112, "s": 7038, "text": "The scatter plot divides the areas into the four groups, as we mentioned." }, { "code": null, "e": 7343, "s": 7112, "text": "Now, this is cool, and we can see all values classified into four groups, but the exciting part is to see where these values cluster together in a map. Again, there is a function in Pysal (splot) to plot a map of the LISA results." }, { "code": null, "e": 7753, "s": 7343, "text": "The map above shows the variation in the average price of Airbnb Properties. The red colors indicate neighborhoods clustered together, which have high prices surrounded by high prices as well (mostly the center of the city). The blue areas indicate where prices are low, also surrounded by areas with low-value prices (Mostly peripheries). Equally interesting is also Low-high and High-low area concentration." }, { "code": null, "e": 8073, "s": 7753, "text": "Compared to the Choropleth map we started with this tutorial, the LISA is much more decluttered and provides a clear picture of the dataset. Exploratory Spatial Data Analysis (ESDA) techniques are powerful tools that help you identify spatial autocorrelation and local clusters that you can apply in any given variable." }, { "code": null, "e": 8265, "s": 8073, "text": "In this tutorial, we have explored how we can perform Exploratory Data Analysis (EDA) for spatial data. The code for this tutorial is available in this GitHub with the notebooks and the data." }, { "code": null, "e": 8276, "s": 8265, "text": "github.com" } ]
Descending Order in Map and Multimap of C++ STL - GeeksforGeeks
07 Jan, 2022 We have discussed map in C++ STL and multimap in C++ STL. The default behavior of these data structures is to store elements in ascending order. How to store elements in reverse order or descending order when inserting in map and multimap? We can use the third parameter, that is std::greater along with map and multimap to store elements in descending order.Descending order in the map: A map stores key-value pairs. A self-balancing-BST (typically Red-Black tree) is used to implement it. Syntax: map<key_datatype, value_datatype, greater<int> > mapName; Example: Input : (10, "queen"), (20, "rose"), (5," lion") Output : (20, "rose"), (10, "queen"), (5," lion") Here, we want to save the elements in descending order, i.e. 20> 10> 5. CPP // C++ program makes a map to store// elements in descending order#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ map<int, string, greater<int> > mymap; // Inserting the elements one by one mymap.insert(make_pair(10, "queen")); mymap.insert(make_pair(20, "rose")); mymap.insert(make_pair(5, " lion")); // begin() returns to the first value of map map<int, string>::iterator it; for (it = mymap.begin(); it != mymap.end(); it++) cout << "(" << (*it).first << ", " << (*it).second << ")" << endl; return 0;} (20, rose) (10, queen) (5, lion) Here, if greater<int> is used to make sure that elements are stored in descending order of keys. Also, the following functions have been used here: insert(): Inserts elements in the map container. begin(): Returns an iterator to the first element in the map end(): Returns an iterator to the theoretical element that follows the last element in the map Descending order in multimap: Multimap is similar to a map with the addition that multiple elements can have the same keys. Rather than each element is unique, the key-value and mapped value pair have to be unique in this case. Syntax: multimap<key_datatype, value_datatype, greater<int> > multimapName; Example: Input : (10, "queen"), (20, "rose"), (5," lion"), (20, "van"), (20, "watch"), (5, "joker") Output : (20, rose), (20, van), (20, watch), (10, queen), (5, lion), (5, joker) CPP // C++ program makes a multimap to store// elements in descending order.#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ multimap<int, string, greater<int> > mymap; // Inserting the elements one by one mymap.insert(make_pair(10, "queen")); mymap.insert(make_pair(20, "rose")); mymap.insert(make_pair(5, " lion")); mymap.insert(make_pair(20, "van")); // Duplicates allowed mymap.insert(make_pair(20, "watch")); mymap.insert(make_pair(5, "joker")); // begin() returns to the first value of multimap. multimap<int, string>::iterator it; for (it = mymap.begin(); it != mymap.end(); it++) cout << "(" << (*it).first << ", " << (*it).second << ")" << endl; return 0;} (20, rose) (20, van) (20, watch) (10, queen) (5, lion) (5, joker) Here, if greater<int> is used to make sure that elements are stored in descending order of keys. Also, the following functions have been used here: insert(): Inserts elements in the map container. begin(): Returns an iterator to the first element in the map end(): Returns an iterator to the theoretical element that follows the last element in the map This article is contributed by Jatin Goyal. 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. ArunrajShanmugam anshikajain26 STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inheritance in C++ Constructors in C++ C++ Classes and Objects Bitwise Operators in C/C++ Socket Programming in C/C++ Operator Overloading in C++ Multidimensional Arrays in C / C++ Copy Constructor in C++ Virtual Function in C++ Templates in C++ with Examples
[ { "code": null, "e": 24181, "s": 24153, "text": "\n07 Jan, 2022" }, { "code": null, "e": 24421, "s": 24181, "text": "We have discussed map in C++ STL and multimap in C++ STL. The default behavior of these data structures is to store elements in ascending order. How to store elements in reverse order or descending order when inserting in map and multimap?" }, { "code": null, "e": 24570, "s": 24421, "text": "We can use the third parameter, that is std::greater along with map and multimap to store elements in descending order.Descending order in the map: " }, { "code": null, "e": 24673, "s": 24570, "text": "A map stores key-value pairs. A self-balancing-BST (typically Red-Black tree) is used to implement it." }, { "code": null, "e": 24681, "s": 24673, "text": "Syntax:" }, { "code": null, "e": 24739, "s": 24681, "text": "map<key_datatype, value_datatype, greater<int> > mapName;" }, { "code": null, "e": 24749, "s": 24739, "text": "Example: " }, { "code": null, "e": 24853, "s": 24749, "text": "Input : (10, \"queen\"), (20, \"rose\"), (5,\" lion\")\nOutput : (20, \"rose\"), (10, \"queen\"), (5,\" lion\")" }, { "code": null, "e": 24925, "s": 24853, "text": "Here, we want to save the elements in descending order, i.e. 20> 10> 5." }, { "code": null, "e": 24929, "s": 24925, "text": "CPP" }, { "code": "// C++ program makes a map to store// elements in descending order#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ map<int, string, greater<int> > mymap; // Inserting the elements one by one mymap.insert(make_pair(10, \"queen\")); mymap.insert(make_pair(20, \"rose\")); mymap.insert(make_pair(5, \" lion\")); // begin() returns to the first value of map map<int, string>::iterator it; for (it = mymap.begin(); it != mymap.end(); it++) cout << \"(\" << (*it).first << \", \" << (*it).second << \")\" << endl; return 0;}", "e": 25512, "s": 24929, "text": null }, { "code": null, "e": 25546, "s": 25512, "text": "(20, rose)\n(10, queen)\n(5, lion)" }, { "code": null, "e": 25694, "s": 25546, "text": "Here, if greater<int> is used to make sure that elements are stored in descending order of keys. Also, the following functions have been used here:" }, { "code": null, "e": 25743, "s": 25694, "text": "insert(): Inserts elements in the map container." }, { "code": null, "e": 25804, "s": 25743, "text": "begin(): Returns an iterator to the first element in the map" }, { "code": null, "e": 25899, "s": 25804, "text": "end(): Returns an iterator to the theoretical element that follows the last element in the map" }, { "code": null, "e": 26127, "s": 25899, "text": "Descending order in multimap: Multimap is similar to a map with the addition that multiple elements can have the same keys. Rather than each element is unique, the key-value and mapped value pair have to be unique in this case." }, { "code": null, "e": 26135, "s": 26127, "text": "Syntax:" }, { "code": null, "e": 26203, "s": 26135, "text": "multimap<key_datatype, value_datatype, greater<int> > multimapName;" }, { "code": null, "e": 26212, "s": 26203, "text": "Example:" }, { "code": null, "e": 26407, "s": 26212, "text": "Input : (10, \"queen\"), (20, \"rose\"), (5,\" lion\"), \n (20, \"van\"), (20, \"watch\"), (5, \"joker\")\nOutput : (20, rose), (20, van), (20, watch), \n (10, queen), (5, lion), (5, joker)" }, { "code": null, "e": 26411, "s": 26407, "text": "CPP" }, { "code": "// C++ program makes a multimap to store// elements in descending order.#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ multimap<int, string, greater<int> > mymap; // Inserting the elements one by one mymap.insert(make_pair(10, \"queen\")); mymap.insert(make_pair(20, \"rose\")); mymap.insert(make_pair(5, \" lion\")); mymap.insert(make_pair(20, \"van\")); // Duplicates allowed mymap.insert(make_pair(20, \"watch\")); mymap.insert(make_pair(5, \"joker\")); // begin() returns to the first value of multimap. multimap<int, string>::iterator it; for (it = mymap.begin(); it != mymap.end(); it++) cout << \"(\" << (*it).first << \", \" << (*it).second << \")\" << endl; return 0;}", "e": 27157, "s": 26411, "text": null }, { "code": null, "e": 27224, "s": 27157, "text": "(20, rose)\n(20, van)\n(20, watch)\n(10, queen)\n(5, lion)\n(5, joker)" }, { "code": null, "e": 27372, "s": 27224, "text": "Here, if greater<int> is used to make sure that elements are stored in descending order of keys. Also, the following functions have been used here:" }, { "code": null, "e": 27421, "s": 27372, "text": "insert(): Inserts elements in the map container." }, { "code": null, "e": 27482, "s": 27421, "text": "begin(): Returns an iterator to the first element in the map" }, { "code": null, "e": 27577, "s": 27482, "text": "end(): Returns an iterator to the theoretical element that follows the last element in the map" }, { "code": null, "e": 27997, "s": 27577, "text": "This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28014, "s": 27997, "text": "ArunrajShanmugam" }, { "code": null, "e": 28028, "s": 28014, "text": "anshikajain26" }, { "code": null, "e": 28032, "s": 28028, "text": "STL" }, { "code": null, "e": 28036, "s": 28032, "text": "C++" }, { "code": null, "e": 28040, "s": 28036, "text": "STL" }, { "code": null, "e": 28044, "s": 28040, "text": "CPP" }, { "code": null, "e": 28142, "s": 28044, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28151, "s": 28142, "text": "Comments" }, { "code": null, "e": 28164, "s": 28151, "text": "Old Comments" }, { "code": null, "e": 28183, "s": 28164, "text": "Inheritance in C++" }, { "code": null, "e": 28203, "s": 28183, "text": "Constructors in C++" }, { "code": null, "e": 28227, "s": 28203, "text": "C++ Classes and Objects" }, { "code": null, "e": 28254, "s": 28227, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 28282, "s": 28254, "text": "Socket Programming in C/C++" }, { "code": null, "e": 28310, "s": 28282, "text": "Operator Overloading in C++" }, { "code": null, "e": 28345, "s": 28310, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 28369, "s": 28345, "text": "Copy Constructor in C++" }, { "code": null, "e": 28393, "s": 28369, "text": "Virtual Function in C++" } ]
How to convert array to SimpleXML in PHP - GeeksforGeeks
22 Nov, 2018 Many times need to store the data as a XML format into the database or into the file for later use. To fulfill this requirement need to convert data to XML and save XML file. The SimpleXML extension functions provides the tool set to convert XML to an object. Those objects deals with normal property selectors and array iterators. Example 1: <?php// Code to convert php array to xml document // Define a function that converts array to xml.function arrayToXml($array, $rootElement = null, $xml = null) { $_xml = $xml; // If there is no Root Element then insert root if ($_xml === null) { $_xml = new SimpleXMLElement($rootElement !== null ? $rootElement : '<root/>'); } // Visit all key value pair foreach ($array as $k => $v) { // If there is nested array then if (is_array($v)) { // Call function for nested array arrayToXml($v, $k, $_xml->addChild($k)); } else { // Simply add child element. $_xml->addChild($k, $v); } } return $_xml->asXML();} // Creating an array for demo$my_array = array ('name' => 'GFG','subject' => 'CS', // Creating nested array. 'contact_info' => array ( 'city' => 'Noida', 'state' => 'UP', 'email' => 'feedback@geeksforgeeks.org' ),); // Calling arrayToxml Function and printing the resultecho arrayToXml($my_array);?> Output: <?xml version="1.0"?> <root> <name> GFG </name> <subject> CS </subject> <contact_info > <city > Noida < /city > <state > UP < /state > <email > feedback@geeksforgeeks.org </email> <contact_info> <root> The above problem ca be solved using array_walk_recursive() function. This function converts array to xml document where keys of array are converted into values and values of array are converted into element of xml. Example 2: <?php// Code to convert php array to xml document // Creating an array$my_array = array ( 'a' => 'x', 'b' => 'y', // creating nested array 'another_array' => array ( 'c' => 'z', ),); // This function create a xml object with element root.$xml = new SimpleXMLElement('<root/>'); // This function resursively added element// of array to xml documentarray_walk_recursive($my_array, array ($xml, 'addChild')); // This function prints xml document.print $xml->asXML();?> Output: <?xml version="1.0"? > <root > <x> a </x > <y> b </y > <z> c </z > </root > Note: If the system generate error of type :PHP Fatal error: Uncaught Error: Class ‘SimpleXMLElement’ not found in /home/6bc5567266b35ae3e76d84307e5bdc78.php:24 then simply install php-xml, php-simplexml packages. Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? How to receive JSON POST with PHP ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to call PHP function on the click of a Button ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP?
[ { "code": null, "e": 24461, "s": 24433, "text": "\n22 Nov, 2018" }, { "code": null, "e": 24636, "s": 24461, "text": "Many times need to store the data as a XML format into the database or into the file for later use. To fulfill this requirement need to convert data to XML and save XML file." }, { "code": null, "e": 24793, "s": 24636, "text": "The SimpleXML extension functions provides the tool set to convert XML to an object. Those objects deals with normal property selectors and array iterators." }, { "code": null, "e": 24804, "s": 24793, "text": "Example 1:" }, { "code": "<?php// Code to convert php array to xml document // Define a function that converts array to xml.function arrayToXml($array, $rootElement = null, $xml = null) { $_xml = $xml; // If there is no Root Element then insert root if ($_xml === null) { $_xml = new SimpleXMLElement($rootElement !== null ? $rootElement : '<root/>'); } // Visit all key value pair foreach ($array as $k => $v) { // If there is nested array then if (is_array($v)) { // Call function for nested array arrayToXml($v, $k, $_xml->addChild($k)); } else { // Simply add child element. $_xml->addChild($k, $v); } } return $_xml->asXML();} // Creating an array for demo$my_array = array ('name' => 'GFG','subject' => 'CS', // Creating nested array. 'contact_info' => array ( 'city' => 'Noida', 'state' => 'UP', 'email' => 'feedback@geeksforgeeks.org' ),); // Calling arrayToxml Function and printing the resultecho arrayToXml($my_array);?>", "e": 25919, "s": 24804, "text": null }, { "code": null, "e": 25927, "s": 25919, "text": "Output:" }, { "code": null, "e": 26170, "s": 25927, "text": "<?xml version=\"1.0\"?>\n<root>\n <name> GFG </name>\n <subject> CS </subject>\n <contact_info >\n <city > Noida < /city >\n <state > UP < /state >\n <email > feedback@geeksforgeeks.org </email>\n <contact_info>\n<root>\n" }, { "code": null, "e": 26386, "s": 26170, "text": "The above problem ca be solved using array_walk_recursive() function. This function converts array to xml document where keys of array are converted into values and values of array are converted into element of xml." }, { "code": null, "e": 26397, "s": 26386, "text": "Example 2:" }, { "code": "<?php// Code to convert php array to xml document // Creating an array$my_array = array ( 'a' => 'x', 'b' => 'y', // creating nested array 'another_array' => array ( 'c' => 'z', ),); // This function create a xml object with element root.$xml = new SimpleXMLElement('<root/>'); // This function resursively added element// of array to xml documentarray_walk_recursive($my_array, array ($xml, 'addChild')); // This function prints xml document.print $xml->asXML();?>", "e": 26895, "s": 26397, "text": null }, { "code": null, "e": 26903, "s": 26895, "text": "Output:" }, { "code": null, "e": 27001, "s": 26903, "text": "<?xml version=\"1.0\"? >\n<root >\n <x> a </x >\n <y> b </y >\n <z> c </z >\n</root >\n" }, { "code": null, "e": 27215, "s": 27001, "text": "Note: If the system generate error of type :PHP Fatal error: Uncaught Error: Class ‘SimpleXMLElement’ not found in /home/6bc5567266b35ae3e76d84307e5bdc78.php:24 then simply install php-xml, php-simplexml packages." }, { "code": null, "e": 27222, "s": 27215, "text": "Picked" }, { "code": null, "e": 27226, "s": 27222, "text": "PHP" }, { "code": null, "e": 27239, "s": 27226, "text": "PHP Programs" }, { "code": null, "e": 27256, "s": 27239, "text": "Web Technologies" }, { "code": null, "e": 27260, "s": 27256, "text": "PHP" }, { "code": null, "e": 27358, "s": 27260, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27367, "s": 27358, "text": "Comments" }, { "code": null, "e": 27380, "s": 27367, "text": "Old Comments" }, { "code": null, "e": 27430, "s": 27380, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27470, "s": 27430, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27531, "s": 27470, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 27581, "s": 27531, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 27617, "s": 27581, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 27667, "s": 27617, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27707, "s": 27667, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27759, "s": 27707, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 27820, "s": 27759, "text": "How to Upload Image into Database and Display it using PHP ?" } ]
Passing a vector to constructor in C++
This is a simple C++ program to pass a vector to a constructor. Begin Declare a class named as vector. Declare vec of vector type. Declare a constructor of vector class. Pass a vector object v as a parameter to the constructor. Initialize vec = v. Declare a function show() to display the values of vector. for (int i = 0; i < vec.size(); i++) print the all values of variable i. Declare v of vector type. Initialize some values into v in array pattern. Declare ob as an object against the vector class. Pass values of v vector via ob vector object to class vector. Call show() function using vector object to show the all values of vector v. End. Live Demo #include <iostream> #include <vector> using namespace std; class Vector { vector<int> vec; public: Vector(vector<int> v) { vec = v; } void show() { for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; } }; int main() { vector<int> v = {7,6,5,4}; Vector ob(v); ob.show(); return 0; } 7 6 5 4
[ { "code": null, "e": 1126, "s": 1062, "text": "This is a simple C++ program to pass a vector to a constructor." }, { "code": null, "e": 1803, "s": 1126, "text": "Begin\n Declare a class named as vector.\n Declare vec of vector type.\n Declare a constructor of vector class.\n Pass a vector object v as a parameter to the constructor.\n Initialize vec = v.\n Declare a function show() to display the values of vector.\n for (int i = 0; i < vec.size(); i++)\n print the all values of variable i.\n Declare v of vector type.\n Initialize some values into v in array pattern.\n Declare ob as an object against the vector class.\n Pass values of v vector via ob vector object to class vector.\n Call show() function using vector object to show the all values of\n vector v.\nEnd." }, { "code": null, "e": 1814, "s": 1803, "text": " Live Demo" }, { "code": null, "e": 2149, "s": 1814, "text": "#include <iostream>\n#include <vector>\nusing namespace std;\nclass Vector {\n vector<int> vec;\n public:\n Vector(vector<int> v) {\n vec = v;\n}\nvoid show() {\n for (int i = 0; i < vec.size(); i++)\n cout << vec[i] << \" \";\n }\n};\nint main() {\n vector<int> v = {7,6,5,4};\n Vector ob(v);\n ob.show();\n return 0;\n}" }, { "code": null, "e": 2157, "s": 2149, "text": "7 6 5 4" } ]
Can we have a try block without a catch block in Java?
Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System.exit() it will execute always. public class TryBlockWithoutCatch { public static void main(String[] args) { try { System.out.println("Try Block"); } finally { System.out.println("Finally Block"); } } } Try Block Finally Block A final block will always execute even though the method has a return type and try block returns some value. public class TryWithFinally { public static int method() { try { System.out.println("Try Block with return type"); return 10; } finally { System.out.println("Finally Block always execute"); } } public static void main(String[] args) { System.out.println(method()); } } Try Block with return type Finally Block always execute 10
[ { "code": null, "e": 1148, "s": 1062, "text": "Yes, It is possible to have a try block without a catch block by using a final block." }, { "code": null, "e": 1291, "s": 1148, "text": "As we know, a final block will always execute even there is an exception occurred in a try block, except System.exit() it will execute always." }, { "code": null, "e": 1504, "s": 1291, "text": "public class TryBlockWithoutCatch {\n public static void main(String[] args) {\n try {\n System.out.println(\"Try Block\");\n } finally {\n System.out.println(\"Finally Block\");\n }\n }\n}" }, { "code": null, "e": 1528, "s": 1504, "text": "Try Block\nFinally Block" }, { "code": null, "e": 1637, "s": 1528, "text": "A final block will always execute even though the method has a return type and try block returns some value." }, { "code": null, "e": 1969, "s": 1637, "text": "public class TryWithFinally {\n public static int method() {\n try {\n System.out.println(\"Try Block with return type\");\n return 10;\n } finally {\n System.out.println(\"Finally Block always execute\");\n }\n }\n public static void main(String[] args) {\n System.out.println(method());\n }\n}" }, { "code": null, "e": 2028, "s": 1969, "text": "Try Block with return type\nFinally Block always execute\n10" } ]
Enum Classes in C++ and Their Advantage over Enum DataType - GeeksforGeeks
22 Nov, 2020 Enums or Enumerated type (enumeration) is a user-defined data type that can be assigned some limited values. These values are defined by the programmer at the time of declaring the enumerated type. Need for Enum Class over Enum Type: Below are some of the reasons as to what are the limitations of Enum Type and why we need Enum Class to cover them. Two enumerations cannot share the same names: CPP #include <bits/stdc++.h>using namespace std; int main(){ // Defining enum1 Gender enum Gender { Male, Female }; // Defining enum2 Gender2 with same values // This will throw error enum Gender2 { Male, Female }; // Creating Gender type variable Gender gender = Male; Gender2 gender2 = Female; cout << gender << endl << gender2; return 0;} Compilation Error: prog.cpp:13:20: error: redeclaration of 'Male' enum Gender2 { Male, ^ prog.cpp:8:19: note: previous declaration 'main()::Gender Male' enum Gender { Male, ^ prog.cpp:14:20: error: redeclaration of 'Female' Female }; ^ prog.cpp:9:19: note: previous declaration 'main()::Gender Female' Female }; ^ prog.cpp:18:23: error: cannot convert 'main()::Gender' to 'main()::Gender2' in initialization Gender2 gender2 = Female; ^ No variable can have a name which is already in some enumeration: CPP #include <bits/stdc++.h>using namespace std; int main(){ // Defining enum1 Gender enum Gender { Male, Female }; // Creating Gender type variable Gender gender = Male; // creating a variable Male // this will throw error int Male = 10; cout << gender << endl; return 0;} Compilation Error: prog.cpp: In function 'int main()': prog.cpp:16:9: error: 'int Male' redeclared as different kind of symbol int Male = 10; ^ prog.cpp:8:19: note: previous declaration 'main()::Gender Male' enum Gender { Male, ^ Enums are not type-safe: CPP #include <bits/stdc++.h>using namespace std; int main(){ // Defining enum1 Gender enum Gender { Male, Female }; // Defining enum2 Color enum Color { Red, Green }; // Creating Gender type variable Gender gender = Male; Color color = Red; // Upon comparing gender and color // it will return true as both have value 0 // which should not be the case actually if (gender == color) cout << "Equal"; return 0;} Warning: prog.cpp: In function 'int main()': prog.cpp:23:19: warning: comparison between 'enum main()::Gender' and 'enum main()::Color' [-Wenum-compare] if (gender == color) ^ C++11 has introduced enum classes (also called scoped enumerations), that makes enumerations both strongly typed and strongly scoped. Class enum doesn’t allow implicit conversion to int, and also doesn’t compare enumerators from different enumerations.To define enum class we use class keyword after enum keyword. Syntax: // Declaration enum class EnumName{ Value1, Value2, ... ValueN}; // Initialisation EnumName ObjectName = EnumName::Value; Example: // Declaration enum class Color{ Red, Green, Blue}; // Initialisation Color col = Color::Red; Below is an implementation to show Enum Class CPP // C++ program to demonstrate working// of Enum Classes #include <iostream>using namespace std; int main(){ enum class Color { Red, Green, Blue }; enum class Color2 { Red, Black, White }; enum class People { Good, Bad }; // An enum value can now be used // to create variables int Green = 10; // Instantiating the Enum Class Color x = Color::Green; // Comparison now is completely type-safe if (x == Color::Red) cout << "It's Red\n"; else cout << "It's not Red\n"; People p = People::Good; if (p == People::Bad) cout << "Bad people\n"; else cout << "Good people\n"; // gives an error // if(x == p) // cout<<"red is equal to good"; // won't work as there is no // implicit conversion to int // cout<< x; cout << int(x); return 0;} It's not Red Good people 1 Enumerated types declared the enum class also have more control over their underlying type; it may be any integral data type, such as char, short or unsigned int, which essentially serves to determines the size of the type. This is specified by a colon and underlying type following the enumerated type: eg: enum class eyecolor : char {char,green,blue}; Here eyecolor is a distinct type with the same size as a char (1 byte). C++ #include <iostream>using namespace std;enum rainbow{ violet, indigo, blue, green,yellow,orange,red}colors;enum class eyecolor:char{ blue,green,brown}eye;int main() { cout<<"size of enum rainbow variable: "<<sizeof(colors)<<endl; cout<<"size of enum class eyecolor variable:"<<sizeof(eye)<<endl; return 0;} size of enum rainbow variable: 4 size of enum class eyecolor variable:1 Reference: https://en.cppreference.com/w/cpp/language/enum aryanrawlani007 viveksaroj098 C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Operator Overloading in C++ Constructors in C++ Socket Programming in C/C++ Virtual Function in C++ Multidimensional Arrays in C / C++ Templates in C++ with Examples Copy Constructor in C++ Object Oriented Programming in C++
[ { "code": null, "e": 24491, "s": 24463, "text": "\n22 Nov, 2020" }, { "code": null, "e": 24689, "s": 24491, "text": "Enums or Enumerated type (enumeration) is a user-defined data type that can be assigned some limited values. These values are defined by the programmer at the time of declaring the enumerated type." }, { "code": null, "e": 24842, "s": 24689, "text": "Need for Enum Class over Enum Type: Below are some of the reasons as to what are the limitations of Enum Type and why we need Enum Class to cover them. " }, { "code": null, "e": 24890, "s": 24842, "text": "Two enumerations cannot share the same names: " }, { "code": null, "e": 24894, "s": 24890, "text": "CPP" }, { "code": "#include <bits/stdc++.h>using namespace std; int main(){ // Defining enum1 Gender enum Gender { Male, Female }; // Defining enum2 Gender2 with same values // This will throw error enum Gender2 { Male, Female }; // Creating Gender type variable Gender gender = Male; Gender2 gender2 = Female; cout << gender << endl << gender2; return 0;}", "e": 25309, "s": 24894, "text": null }, { "code": null, "e": 25330, "s": 25309, "text": "Compilation Error: " }, { "code": null, "e": 25911, "s": 25330, "text": "prog.cpp:13:20: error: redeclaration of 'Male'\n enum Gender2 { Male,\n ^\nprog.cpp:8:19: note: previous declaration 'main()::Gender Male'\n enum Gender { Male,\n ^\nprog.cpp:14:20: error: redeclaration of 'Female'\n Female };\n ^\nprog.cpp:9:19: note: previous declaration 'main()::Gender Female'\n Female };\n ^\nprog.cpp:18:23: error: cannot convert 'main()::Gender' \nto 'main()::Gender2' in initialization\n Gender2 gender2 = Female;\n ^\n\n\n\n\n\n\n\n" }, { "code": null, "e": 25980, "s": 25913, "text": "No variable can have a name which is already in some enumeration: " }, { "code": null, "e": 25984, "s": 25980, "text": "CPP" }, { "code": "#include <bits/stdc++.h>using namespace std; int main(){ // Defining enum1 Gender enum Gender { Male, Female }; // Creating Gender type variable Gender gender = Male; // creating a variable Male // this will throw error int Male = 10; cout << gender << endl; return 0;}", "e": 26302, "s": 25984, "text": null }, { "code": null, "e": 26323, "s": 26302, "text": "Compilation Error: " }, { "code": null, "e": 26573, "s": 26323, "text": "prog.cpp: In function 'int main()':\nprog.cpp:16:9: error: 'int Male' redeclared as different kind of symbol\n int Male = 10;\n ^\nprog.cpp:8:19: note: previous declaration 'main()::Gender Male'\n enum Gender { Male,\n ^\n" }, { "code": null, "e": 26601, "s": 26575, "text": "Enums are not type-safe: " }, { "code": null, "e": 26605, "s": 26601, "text": "CPP" }, { "code": "#include <bits/stdc++.h>using namespace std; int main(){ // Defining enum1 Gender enum Gender { Male, Female }; // Defining enum2 Color enum Color { Red, Green }; // Creating Gender type variable Gender gender = Male; Color color = Red; // Upon comparing gender and color // it will return true as both have value 0 // which should not be the case actually if (gender == color) cout << \"Equal\"; return 0;}", "e": 27091, "s": 26605, "text": null }, { "code": null, "e": 27102, "s": 27091, "text": "Warning: " }, { "code": null, "e": 27291, "s": 27102, "text": "prog.cpp: In function 'int main()':\nprog.cpp:23:19: warning: comparison between 'enum main()::Gender'\nand 'enum main()::Color' [-Wenum-compare]\n if (gender == color) ^\n\n" }, { "code": null, "e": 27617, "s": 27293, "text": "C++11 has introduced enum classes (also called scoped enumerations), that makes enumerations both strongly typed and strongly scoped. Class enum doesn’t allow implicit conversion to int, and also doesn’t compare enumerators from different enumerations.To define enum class we use class keyword after enum keyword. Syntax: " }, { "code": null, "e": 27741, "s": 27617, "text": "// Declaration\nenum class EnumName{ Value1, Value2, ... ValueN};\n\n// Initialisation\nEnumName ObjectName = EnumName::Value;\n" }, { "code": null, "e": 27752, "s": 27741, "text": "Example: " }, { "code": null, "e": 27848, "s": 27752, "text": "// Declaration\nenum class Color{ Red, Green, Blue};\n\n// Initialisation\nColor col = Color::Red;\n" }, { "code": null, "e": 27895, "s": 27848, "text": "Below is an implementation to show Enum Class " }, { "code": null, "e": 27899, "s": 27895, "text": "CPP" }, { "code": "// C++ program to demonstrate working// of Enum Classes #include <iostream>using namespace std; int main(){ enum class Color { Red, Green, Blue }; enum class Color2 { Red, Black, White }; enum class People { Good, Bad }; // An enum value can now be used // to create variables int Green = 10; // Instantiating the Enum Class Color x = Color::Green; // Comparison now is completely type-safe if (x == Color::Red) cout << \"It's Red\\n\"; else cout << \"It's not Red\\n\"; People p = People::Good; if (p == People::Bad) cout << \"Bad people\\n\"; else cout << \"Good people\\n\"; // gives an error // if(x == p) // cout<<\"red is equal to good\"; // won't work as there is no // implicit conversion to int // cout<< x; cout << int(x); return 0;}", "e": 28846, "s": 27899, "text": null }, { "code": null, "e": 28873, "s": 28846, "text": "It's not Red\nGood people\n1" }, { "code": null, "e": 29097, "s": 28873, "text": "Enumerated types declared the enum class also have more control over their underlying type; it may be any integral data type, such as char, short or unsigned int, which essentially serves to determines the size of the type." }, { "code": null, "e": 29177, "s": 29097, "text": "This is specified by a colon and underlying type following the enumerated type:" }, { "code": null, "e": 29299, "s": 29177, "text": "eg: enum class eyecolor : char {char,green,blue};\nHere eyecolor is a distinct type with the same size as a char (1 byte)." }, { "code": null, "e": 29303, "s": 29299, "text": "C++" }, { "code": "#include <iostream>using namespace std;enum rainbow{ violet, indigo, blue, green,yellow,orange,red}colors;enum class eyecolor:char{ blue,green,brown}eye;int main() { cout<<\"size of enum rainbow variable: \"<<sizeof(colors)<<endl; cout<<\"size of enum class eyecolor variable:\"<<sizeof(eye)<<endl; return 0;}", "e": 29634, "s": 29303, "text": null }, { "code": null, "e": 29707, "s": 29634, "text": "size of enum rainbow variable: 4\nsize of enum class eyecolor variable:1\n" }, { "code": null, "e": 29767, "s": 29707, "text": "Reference: https://en.cppreference.com/w/cpp/language/enum " }, { "code": null, "e": 29783, "s": 29767, "text": "aryanrawlani007" }, { "code": null, "e": 29797, "s": 29783, "text": "viveksaroj098" }, { "code": null, "e": 29801, "s": 29797, "text": "C++" }, { "code": null, "e": 29805, "s": 29801, "text": "CPP" }, { "code": null, "e": 29903, "s": 29805, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29922, "s": 29903, "text": "Inheritance in C++" }, { "code": null, "e": 29946, "s": 29922, "text": "C++ Classes and Objects" }, { "code": null, "e": 29974, "s": 29946, "text": "Operator Overloading in C++" }, { "code": null, "e": 29994, "s": 29974, "text": "Constructors in C++" }, { "code": null, "e": 30022, "s": 29994, "text": "Socket Programming in C/C++" }, { "code": null, "e": 30046, "s": 30022, "text": "Virtual Function in C++" }, { "code": null, "e": 30081, "s": 30046, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 30112, "s": 30081, "text": "Templates in C++ with Examples" }, { "code": null, "e": 30136, "s": 30112, "text": "Copy Constructor in C++" } ]
jsoup - Parsing String
Following example will showcase parsing an HTML String into a Document object. Document document = Jsoup.parse(html); Where document − document object represents the HTML DOM. document − document object represents the HTML DOM. Jsoup − main class to parse the given HTML String. Jsoup − main class to parse the given HTML String. html − HTML String. html − HTML String. The parse(String html) method parses the input HTML into a new Document. This document object can be used to traverse and get details of the html dom. Create the following java program using any editor of your choice in say C:/> jsoup. JsoupTester.java import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class JsoupTester { public static void main(String[] args) { String html = "<html><head><title>Sample Title</title></head>" + "<body><p>Sample Content</p></body></html>"; Document document = Jsoup.parse(html); System.out.println(document.title()); Elements paragraphs = document.getElementsByTag("p"); for (Element paragraph : paragraphs) { System.out.println(paragraph.text()); } } } Compile the class using javac compiler as follows: C:\jsoup>javac JsoupTester.java Now run the JsoupTester to see the result. C:\jsoup>java JsoupTester See the result. Sample Title Sample Content Print Add Notes Bookmark this page
[ { "code": null, "e": 2109, "s": 2030, "text": "Following example will showcase parsing an HTML String into a Document object." }, { "code": null, "e": 2149, "s": 2109, "text": "Document document = Jsoup.parse(html);\n" }, { "code": null, "e": 2155, "s": 2149, "text": "Where" }, { "code": null, "e": 2207, "s": 2155, "text": "document − document object represents the HTML DOM." }, { "code": null, "e": 2259, "s": 2207, "text": "document − document object represents the HTML DOM." }, { "code": null, "e": 2310, "s": 2259, "text": "Jsoup − main class to parse the given HTML String." }, { "code": null, "e": 2361, "s": 2310, "text": "Jsoup − main class to parse the given HTML String." }, { "code": null, "e": 2381, "s": 2361, "text": "html − HTML String." }, { "code": null, "e": 2401, "s": 2381, "text": "html − HTML String." }, { "code": null, "e": 2552, "s": 2401, "text": "The parse(String html) method parses the input HTML into a new Document. This document object can be used to traverse and get details of the html dom." }, { "code": null, "e": 2637, "s": 2552, "text": "Create the following java program using any editor of your choice in say C:/> jsoup." }, { "code": null, "e": 2654, "s": 2637, "text": "JsoupTester.java" }, { "code": null, "e": 3237, "s": 2654, "text": "import org.jsoup.Jsoup;\nimport org.jsoup.nodes.Document;\nimport org.jsoup.nodes.Element;\nimport org.jsoup.select.Elements;\n\npublic class JsoupTester {\n public static void main(String[] args) {\n \n String html = \"<html><head><title>Sample Title</title></head>\"\n + \"<body><p>Sample Content</p></body></html>\";\n Document document = Jsoup.parse(html);\n System.out.println(document.title());\n Elements paragraphs = document.getElementsByTag(\"p\");\n for (Element paragraph : paragraphs) {\n System.out.println(paragraph.text());\n }\n }\n}" }, { "code": null, "e": 3288, "s": 3237, "text": "Compile the class using javac compiler as follows:" }, { "code": null, "e": 3321, "s": 3288, "text": "C:\\jsoup>javac JsoupTester.java\n" }, { "code": null, "e": 3364, "s": 3321, "text": "Now run the JsoupTester to see the result." }, { "code": null, "e": 3391, "s": 3364, "text": "C:\\jsoup>java JsoupTester\n" }, { "code": null, "e": 3407, "s": 3391, "text": "See the result." }, { "code": null, "e": 3436, "s": 3407, "text": "Sample Title\nSample Content\n" }, { "code": null, "e": 3443, "s": 3436, "text": " Print" }, { "code": null, "e": 3454, "s": 3443, "text": " Add Notes" } ]
Mahotas - Hit & Miss transform - GeeksforGeeks
10 Jul, 2020 In this article we will see how we can perform hit and miss transform in mahotas. In mathematical morphology, hit-or-miss transform is an operation that detects a given configuration in a binary image, using the morphological erosion operator and a pair of disjoint structuring elements. In order to do this we will use mahotas.hitmiss method Syntax : mahotas.hitmiss(img, template) Argument : It takes two numpy ndarray as argument Return : It returns ndarray Below is the implementation # importing required librariesimport mahotas as mhimport numpy as npfrom pylab import imshow, show # creating region# numpy.ndarrayregions = np.zeros((10, 10), bool) # setting 1 value to the regionregions[1, :2] = 1regions[5:8, 6: 8] = 1regions[8, 0] = 1 # showing the image with interpolation = 'nearest'print("Image")imshow(regions, interpolation ='nearest')show() # template for hit misstemplate = np.array([ [0, 1, 1], [0, 1, 1], [0, 1, 1]]) # hit miss transformimg = mahotas.hitmiss(regions, template) # showing imageprint("Image after hit miss transform")imshow(img)show() Output : Image Image after hit miss transform Another example # importing required librariesimport mahotas as mhimport numpy as npfrom pylab import imshow, show # creating region# numpy.ndarrayregions = np.zeros((10, 10), bool) # setting 1 value to the regionregions[2:3, :3] = 1regions[7:, 7:] = 1 # showing the image with interpolation = 'nearest'print("Image")imshow(regions, interpolation ='nearest')show() # template for hit misstemplate = np.array([ [0, 1, 1], [0, 1, 1], [0, 1, 1]]) # hit miss transformimg = mahotas.hitmiss(regions, template) # showing imageprint("Image after hit miss transform")imshow(img)show() Output : Image Image after hit miss transform Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? 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": "\n10 Jul, 2020" }, { "code": null, "e": 24189, "s": 23901, "text": "In this article we will see how we can perform hit and miss transform in mahotas. In mathematical morphology, hit-or-miss transform is an operation that detects a given configuration in a binary image, using the morphological erosion operator and a pair of disjoint structuring elements." }, { "code": null, "e": 24244, "s": 24189, "text": "In order to do this we will use mahotas.hitmiss method" }, { "code": null, "e": 24284, "s": 24244, "text": "Syntax : mahotas.hitmiss(img, template)" }, { "code": null, "e": 24334, "s": 24284, "text": "Argument : It takes two numpy ndarray as argument" }, { "code": null, "e": 24362, "s": 24334, "text": "Return : It returns ndarray" }, { "code": null, "e": 24390, "s": 24362, "text": "Below is the implementation" }, { "code": "# importing required librariesimport mahotas as mhimport numpy as npfrom pylab import imshow, show # creating region# numpy.ndarrayregions = np.zeros((10, 10), bool) # setting 1 value to the regionregions[1, :2] = 1regions[5:8, 6: 8] = 1regions[8, 0] = 1 # showing the image with interpolation = 'nearest'print(\"Image\")imshow(regions, interpolation ='nearest')show() # template for hit misstemplate = np.array([ [0, 1, 1], [0, 1, 1], [0, 1, 1]]) # hit miss transformimg = mahotas.hitmiss(regions, template) # showing imageprint(\"Image after hit miss transform\")imshow(img)show()", "e": 25018, "s": 24390, "text": null }, { "code": null, "e": 25027, "s": 25018, "text": "Output :" }, { "code": null, "e": 25033, "s": 25027, "text": "Image" }, { "code": null, "e": 25064, "s": 25033, "text": "Image after hit miss transform" }, { "code": null, "e": 25080, "s": 25064, "text": "Another example" }, { "code": "# importing required librariesimport mahotas as mhimport numpy as npfrom pylab import imshow, show # creating region# numpy.ndarrayregions = np.zeros((10, 10), bool) # setting 1 value to the regionregions[2:3, :3] = 1regions[7:, 7:] = 1 # showing the image with interpolation = 'nearest'print(\"Image\")imshow(regions, interpolation ='nearest')show() # template for hit misstemplate = np.array([ [0, 1, 1], [0, 1, 1], [0, 1, 1]]) # hit miss transformimg = mahotas.hitmiss(regions, template) # showing imageprint(\"Image after hit miss transform\")imshow(img)show()", "e": 25690, "s": 25080, "text": null }, { "code": null, "e": 25699, "s": 25690, "text": "Output :" }, { "code": null, "e": 25705, "s": 25699, "text": "Image" }, { "code": null, "e": 25736, "s": 25705, "text": "Image after hit miss transform" }, { "code": null, "e": 25743, "s": 25736, "text": "Python" }, { "code": null, "e": 25841, "s": 25743, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25850, "s": 25841, "text": "Comments" }, { "code": null, "e": 25863, "s": 25850, "text": "Old Comments" }, { "code": null, "e": 25895, "s": 25863, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25951, "s": 25895, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25993, "s": 25951, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26035, "s": 25993, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26071, "s": 26035, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26093, "s": 26071, "text": "Defaultdict in Python" }, { "code": null, "e": 26132, "s": 26093, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26159, "s": 26132, "text": "Python Classes and Objects" }, { "code": null, "e": 26190, "s": 26159, "text": "Python | os.path.join() method" } ]
VBA - IsArray Function
The IsArray Function returns a boolean value that indicates whether or NOT the specified input variable is an array variable. IsArray(variablename) Add a button and add the following function. Private Sub Constant_demo_Click() Dim a,b as Variant a = array("Red","Blue","Yellow") b = "12345" msgbox("The IsArray result 1 : " & IsArray(a)) msgbox("The IsArray result 2 : " & IsArray(b)) End Sub When you execute the above function, it produces the following output. The IsArray result 1 : True The IsArray result 2 : False 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2061, "s": 1935, "text": "The IsArray Function returns a boolean value that indicates whether or NOT the specified input variable is an array variable." }, { "code": null, "e": 2084, "s": 2061, "text": "IsArray(variablename)\n" }, { "code": null, "e": 2129, "s": 2084, "text": "Add a button and add the following function." }, { "code": null, "e": 2347, "s": 2129, "text": "Private Sub Constant_demo_Click()\n Dim a,b as Variant\n a = array(\"Red\",\"Blue\",\"Yellow\")\n b = \"12345\"\n \n msgbox(\"The IsArray result 1 : \" & IsArray(a))\n msgbox(\"The IsArray result 2 : \" & IsArray(b))\nEnd Sub" }, { "code": null, "e": 2418, "s": 2347, "text": "When you execute the above function, it produces the following output." }, { "code": null, "e": 2476, "s": 2418, "text": "The IsArray result 1 : True\nThe IsArray result 2 : False\n" }, { "code": null, "e": 2510, "s": 2476, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 2525, "s": 2510, "text": " Pavan Lalwani" }, { "code": null, "e": 2558, "s": 2525, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 2573, "s": 2558, "text": " Arnold Higuit" }, { "code": null, "e": 2608, "s": 2573, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2626, "s": 2608, "text": " Prashant Panchal" }, { "code": null, "e": 2659, "s": 2626, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 2677, "s": 2659, "text": " Prashant Panchal" }, { "code": null, "e": 2710, "s": 2677, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 2725, "s": 2710, "text": " Arnold Higuit" }, { "code": null, "e": 2761, "s": 2725, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 2789, "s": 2761, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 2796, "s": 2789, "text": " Print" }, { "code": null, "e": 2807, "s": 2796, "text": " Add Notes" } ]
Interfacing Stepper Motor with 8051Microcontroller
In this section, we will see how to connect a stepper motor with Intel 8051 Microcontroller. Before discussing the interfacing techniques, we will see what are the stepper motors and how they work. Stepper motors are used to translate electrical pulses into mechanical movements. In some disk drives, dot matrix printers, and some other different places the stepper motors are used. The main advantage of using the stepper motor is the position control. Stepper motors generally have a permanent magnet shaft (rotor), and it is surrounded by a stator. Normal motor shafts can move freely but the stepper motor shafts move in fixed repeatable increments. Step Angle − The step angle is the angle in which the rotor moves when one pulse is applied as an input of the stator. This parameter is used to determine the positioning of a stepper motor. Step Angle − The step angle is the angle in which the rotor moves when one pulse is applied as an input of the stator. This parameter is used to determine the positioning of a stepper motor. Steps per Revolution − This is the number of step angles required for a complete revolution. So the formula is 360° /Step Angle. Steps per Revolution − This is the number of step angles required for a complete revolution. So the formula is 360° /Step Angle. Steps per Second − This parameter is used to measure a number of steps covered in each second. Steps per Second − This parameter is used to measure a number of steps covered in each second. RPM − The RPM is the Revolution Per Minute. It measures the frequency of rotation. By this parameter, we can measure the number of rotations in one minute. RPM − The RPM is the Revolution Per Minute. It measures the frequency of rotation. By this parameter, we can measure the number of rotations in one minute. The relation between RPM, steps per revolution, and steps per second is like below: Steps per Second = rpm x steps per revolution / 60 Weare using Port P0 of 8051 for connecting the stepper motor. HereULN2003 is used. This is basically a high voltage, high current Darlington transistor array. Each ULN2003 has seven NPN Darlington pairs. It can provide high voltage output with common cathode clamp diodes for switching inductive loads. The Unipolar stepper motor works in three modes. Wave Drive Mode − In this mode, one coil is energized at a time. So all four coils are energized one after another. This mode produces less torque than full step drive mode. Wave Drive Mode − In this mode, one coil is energized at a time. So all four coils are energized one after another. This mode produces less torque than full step drive mode. The following table is showing the sequence of input states in different windings. Full Drive Mode − In this mode, two coils are energized at the same time. This mode produces more torque. Here the power consumption is also high Full Drive Mode − In this mode, two coils are energized at the same time. This mode produces more torque. Here the power consumption is also high The following table is showing the sequence of input states in different windings. Half Drive Mode − In this mode, one and two coils are energized alternately. At first, one coil is energized then two coils are energized. This is basically a combination of wave and full drive mode. It increases the angular rotation of the motor Half Drive Mode − In this mode, one and two coils are energized alternately. At first, one coil is energized then two coils are energized. This is basically a combination of wave and full drive mode. It increases the angular rotation of the motor The following table is showing the sequence of input states in different windings. The circuit diagram is like below: We are using the full drive mode. #include<reg51.h> sbit LED_pin = P2^0; //set the LED pin as P2.0 void delay(int ms){ unsigned int i, j; for(i = 0; i<ms; i++){ // Outer for loop for given milliseconds value for(j = 0; j< 1275; j++){ //execute in each milliseconds; } } } void main(){ int rot_angle[] = {0x0C,0x06,0x03,0x09}; int i; while(1){ //infinite loop for LED blinking for(i = 0; i<4; i++){ P0 = rot_angle[i]; delay(100); } } }
[ { "code": null, "e": 1260, "s": 1062, "text": "In this section, we will see how to connect a stepper motor with Intel 8051 Microcontroller. Before discussing the interfacing techniques, we will see what are the stepper motors and how they work." }, { "code": null, "e": 1615, "s": 1260, "text": "Stepper motors are used to translate electrical pulses into mechanical movements. In some disk drives, dot matrix printers, and some other different places the stepper motors are used. The main advantage of using the stepper motor is the position control. Stepper motors generally have a permanent magnet shaft (rotor), and it is surrounded by a stator. " }, { "code": null, "e": 1717, "s": 1615, "text": "Normal motor shafts can move freely but the stepper motor shafts move in fixed repeatable increments." }, { "code": null, "e": 1909, "s": 1717, "text": "Step Angle − The step angle is the angle in which the rotor moves when one pulse is applied as an input of the stator. This parameter is used to determine the positioning of a stepper motor." }, { "code": null, "e": 2101, "s": 1909, "text": "Step Angle − The step angle is the angle in which the rotor moves when one pulse is applied as an input of the stator. This parameter is used to determine the positioning of a stepper motor." }, { "code": null, "e": 2231, "s": 2101, "text": "Steps per Revolution − This is the number of step angles required for a complete revolution. So the formula is 360° /Step Angle." }, { "code": null, "e": 2361, "s": 2231, "text": "Steps per Revolution − This is the number of step angles required for a complete revolution. So the formula is 360° /Step Angle." }, { "code": null, "e": 2457, "s": 2361, "text": "Steps per Second − This parameter is used to measure a number of steps covered in each second." }, { "code": null, "e": 2553, "s": 2457, "text": "Steps per Second − This parameter is used to measure a number of steps covered in each second." }, { "code": null, "e": 2710, "s": 2553, "text": "RPM − The RPM is the Revolution Per Minute. It measures the frequency of rotation. By this parameter, we can measure the number of rotations in one minute." }, { "code": null, "e": 2867, "s": 2710, "text": "RPM − The RPM is the Revolution Per Minute. It measures the frequency of rotation. By this parameter, we can measure the number of rotations in one minute." }, { "code": null, "e": 2951, "s": 2867, "text": "The relation between RPM, steps per revolution, and steps per second is like below:" }, { "code": null, "e": 3002, "s": 2951, "text": "Steps per Second = rpm x steps per revolution / 60" }, { "code": null, "e": 3305, "s": 3002, "text": "Weare using Port P0 of 8051 for connecting the stepper motor. HereULN2003 is used. This is basically a high voltage, high current Darlington transistor array. Each ULN2003 has seven NPN Darlington pairs. It can provide high voltage output with common cathode clamp diodes for switching inductive loads." }, { "code": null, "e": 3354, "s": 3305, "text": "The Unipolar stepper motor works in three modes." }, { "code": null, "e": 3528, "s": 3354, "text": "Wave Drive Mode − In this mode, one coil is energized at a time. So all four coils are energized one after another. This mode produces less torque than full step drive mode." }, { "code": null, "e": 3702, "s": 3528, "text": "Wave Drive Mode − In this mode, one coil is energized at a time. So all four coils are energized one after another. This mode produces less torque than full step drive mode." }, { "code": null, "e": 3785, "s": 3702, "text": "The following table is showing the sequence of input states in different windings." }, { "code": null, "e": 3931, "s": 3785, "text": "Full Drive Mode − In this mode, two coils are energized at the same time. This mode produces more torque. Here the power consumption is also high" }, { "code": null, "e": 4077, "s": 3931, "text": "Full Drive Mode − In this mode, two coils are energized at the same time. This mode produces more torque. Here the power consumption is also high" }, { "code": null, "e": 4160, "s": 4077, "text": "The following table is showing the sequence of input states in different windings." }, { "code": null, "e": 4407, "s": 4160, "text": "Half Drive Mode − In this mode, one and two coils are energized alternately. At first, one coil is energized then two coils are energized. This is basically a combination of wave and full drive mode. It increases the angular rotation of the motor" }, { "code": null, "e": 4654, "s": 4407, "text": "Half Drive Mode − In this mode, one and two coils are energized alternately. At first, one coil is energized then two coils are energized. This is basically a combination of wave and full drive mode. It increases the angular rotation of the motor" }, { "code": null, "e": 4737, "s": 4654, "text": "The following table is showing the sequence of input states in different windings." }, { "code": null, "e": 4806, "s": 4737, "text": "The circuit diagram is like below: We are using the full drive mode." }, { "code": null, "e": 5286, "s": 4806, "text": "#include<reg51.h>\nsbit LED_pin = P2^0; //set the LED pin as P2.0\nvoid delay(int ms){\n unsigned int i, j;\n for(i = 0; i<ms; i++){ // Outer for loop for given milliseconds value\n for(j = 0; j< 1275; j++){\n //execute in each milliseconds;\n }\n }\n}\nvoid main(){\n int rot_angle[] = {0x0C,0x06,0x03,0x09};\n int i;\n while(1){\n //infinite loop for LED blinking\n for(i = 0; i<4; i++){\n P0 = rot_angle[i];\n delay(100);\n }\n }\n}" } ]
Difference between Scanner and BufferReader Class in Java
Scanner and BufferReader both classes are used to read input from external system. Scanner is normally used when we know input is of type string or of primitive types and BufferReader is used to read text from character streams while buffering the characters for efficient reading of characters. Following are the important differences between Scanner class and a BufferReader class. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class JavaTester { public static void main(String args[]) throws NumberFormatException, IOException { BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter an number:"); int a = Integer.parseInt(bufferReader.readLine()); System.out.printf("You entered: " + a); Scanner scanner = new Scanner(System.in); System.out.println("\nEnter an number:"); a = scanner.nextInt(); System.out.printf("You entered: " + a); } } Enter an number: 1 You entered: 1 Enter an number: 2 You entered: 2
[ { "code": null, "e": 1446, "s": 1062, "text": "Scanner and BufferReader both classes are used to read input from external system. Scanner is normally used when we know input is of type string or of primitive types and BufferReader is used to read text from character streams while buffering the characters for efficient reading of characters. Following are the important differences between Scanner class and a BufferReader class." }, { "code": null, "e": 2094, "s": 1446, "text": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.Scanner;\npublic class JavaTester {\n public static void main(String args[]) throws NumberFormatException, IOException {\n BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));\n System.out.println(\"Enter an number:\");\n int a = Integer.parseInt(bufferReader.readLine());\n System.out.printf(\"You entered: \" + a);\n Scanner scanner = new Scanner(System.in);\n System.out.println(\"\\nEnter an number:\");\n a = scanner.nextInt();\n System.out.printf(\"You entered: \" + a);\n }\n}" }, { "code": null, "e": 2162, "s": 2094, "text": "Enter an number:\n1\nYou entered: 1\nEnter an number:\n2\nYou entered: 2" } ]
Pytorch model in Deep Java Library | by Shantanu Bhattacharyya | Towards Data Science
PyTorch is a fast growing and very popular open source Machine Learning framework. Its imperative design combined with “numpy” like workflow makes it a compelling first choice for beginners and professionals alike. However, serving these model in production is not straightforward and things are particularly difficult if the goal is to serve them natively in Java. Amazon’s Deep Java Library (DJL) aims to solve this particular pain point by providing high level APIs that can run inference on PyTorch models with very little code. My recent test drive with DJL tells me that it could be a very powerful tool but the existing example set and community guidance (aka stackoverflow help :) ) could be a little intimidating for new folks, specially those who come from python background and are unfamiliar with the java style. This simple demo, hopefully, makes things easier for them. All the scripts are also available at my git repo here. Let’s start by creating a simple linear regression model with PyTorch. import torchimport torch.nn as nnX = torch.tensor([[1],[2],[4],[7],[9]], dtype = torch.float32)Y = torch.tensor([[2],[4],[8],[14],[18]], dtype = torch.float32)X_test = torch.tensor([[5]], dtype=torch.float32)n_sample, n_features = X.shapemodel = nn.Linear(n_features, n_features)learn_rate = 0.01n_epochs = 500loss = nn.MSELoss()optimizer = torch.optim.SGD(lr = learn_rate, params=model.parameters())for i in range(0,n_epochs): y_pred = model(X) ls = loss(y_pred,Y) ls.backward() optimizer.step() optimizer.zero_grad() [w,b] = model.parameters() traced_cell = torch.jit.trace(model, X_test) #print(traced_cell(X_test).item()) print(f"{ls.item():0.3f}, {w[0][0].item():0.3f {model(X_test).item():0.3f}")traced_cell.save('./model1.zip') The model (model1) learns to take an input n and predict 2 * n. There are 2 lines in the script above that are usually not present in PyTorch scripts. 1. traced_cell = torch.jit.trace(model, X_test) 2. traced_cell.save('./model1.zip') These two lines are required to create a TorchScript model (serialized pytorch model) that can be used in a language agnostic fashion in high performance environments. We will now use this model to make inference using DJL. I have used a Jupyter notebook running Java kernel for this demo. 1 : Get all the required maven dependencies. DJL supports pytorch models out of the box. SLF4J is for logging purposes. %maven ai.djl.pytorch:pytorch-engine:0.8.0%maven ai.djl.pytorch:pytorch-native-auto:1.6.0%maven org.slf4j:slf4j-simple:1.7.26 If you get errors that say “unknown resolver null”, you can ignore them for now. 2 : Import the required modules import ai.djl.*;import ai.djl.inference.*;import ai.djl.ndarray.*;import ai.djl.translate.*;import java.nio.file.*; It is worth highlighting the ndarray import here. N-Dimensional array is a popular data structure in many languages and numpy (ndarray library in python) is pretty much ubiquitous in the field of deep learning or pretty much any application involving numerical computation. Java doesn’t have a similar ndarray implementation. DJL provides the ndarray functionality through the above import. This is one of the key factors that allows DJL to work with PyTorch models. 3. Declare path to model and model name. This assumes you are using a locally generated model. DJL provides some standard models too that can be used directly. Path modelDir = Paths.get("Path_To_Your_Model_Folder/");Model model = Model.newInstance("model name");model.load(modelDir);model Current DJL documentation says models can be .zip , .tar, .tar.gz, .tgz or .tar.z If the model is correctly loaded, you should see an output like ai.djl.pytorch.engine.PtModel@4cefa68f 4. Translator to handle the pre-processing and post-processing steps. Translator<Float, Float> translator = new Translator<Float, Float>(){ @Override public NDList processInput(TranslatorContext ctx, Float input) { NDManager manager = ctx.getNDManager(); NDArray array = manager.create(new float[] {input}); return new NDList (array); } @Override public Float processOutput(TranslatorContext ctx, NDList list) { NDArray temp_arr = list.get(0); return temp_arr.getFloat(); } @Override public Batchifier getBatchifier() { // The Batchifier describes how to combine a batch together // Stacking, the most common batchifier, takes N [X1, X2, ...] arrays to a single [N, X1, X2, ...] array return Batchifier.STACK; }}; This is the step that confuses most people. The translator defines the signature for the input and output data types <Input type, Output type>. For our example they both happen to be a float. Make sure to use Float, not float, as a reference is explicitly expected. This translation step is not optional. Further, if you look at the DJL doc for PreProcessor , you will find that NDList is the expected type for the preprocessing output that gets fed to the model. So, even if your input was hypothetically already an NDList type, you still need to do this step. The case for post processing is similar. It consumes the NDList and outputs the type described by your Translator. All the three overides above are mandatory as well. There are of’course pre-implemented translators provided by DJL and I recommend you to explore them, particularly the image processing ones. 5. Making Prediction Congratulations, you have done the hard work and are just a couple of lines of code away from making the inference. Here they are Predictor<Float, Float> predictor = model.newPredictor(translator);predictor.predict(Your_Test_Float) For my test case, I did predictor.predict(2.9f) and it output 5.799781. Ahh, pure Joy ! So we saw how we can create a PyTorch model and use that model for inference in a Java environment. This was a very simplistic use case though. For more advanced use cases, making the translator do the preprocessing and postprocessing correctly could require a few iterations. Further, the number of inbuilt modules (like the image processing ones) are currently few in number. I am confident though, that DJL will evolve rapidly and could be the perfect library to utilise PyTorch models in Java (or C++) environment giving the perfect combination of development speed and high performance.
[ { "code": null, "e": 537, "s": 171, "text": "PyTorch is a fast growing and very popular open source Machine Learning framework. Its imperative design combined with “numpy” like workflow makes it a compelling first choice for beginners and professionals alike. However, serving these model in production is not straightforward and things are particularly difficult if the goal is to serve them natively in Java." }, { "code": null, "e": 1111, "s": 537, "text": "Amazon’s Deep Java Library (DJL) aims to solve this particular pain point by providing high level APIs that can run inference on PyTorch models with very little code. My recent test drive with DJL tells me that it could be a very powerful tool but the existing example set and community guidance (aka stackoverflow help :) ) could be a little intimidating for new folks, specially those who come from python background and are unfamiliar with the java style. This simple demo, hopefully, makes things easier for them. All the scripts are also available at my git repo here." }, { "code": null, "e": 1182, "s": 1111, "text": "Let’s start by creating a simple linear regression model with PyTorch." }, { "code": null, "e": 1944, "s": 1182, "text": "import torchimport torch.nn as nnX = torch.tensor([[1],[2],[4],[7],[9]], dtype = torch.float32)Y = torch.tensor([[2],[4],[8],[14],[18]], dtype = torch.float32)X_test = torch.tensor([[5]], dtype=torch.float32)n_sample, n_features = X.shapemodel = nn.Linear(n_features, n_features)learn_rate = 0.01n_epochs = 500loss = nn.MSELoss()optimizer = torch.optim.SGD(lr = learn_rate, params=model.parameters())for i in range(0,n_epochs): y_pred = model(X) ls = loss(y_pred,Y) ls.backward() optimizer.step() optimizer.zero_grad() [w,b] = model.parameters() traced_cell = torch.jit.trace(model, X_test) #print(traced_cell(X_test).item()) print(f\"{ls.item():0.3f}, {w[0][0].item():0.3f {model(X_test).item():0.3f}\")traced_cell.save('./model1.zip')" }, { "code": null, "e": 2008, "s": 1944, "text": "The model (model1) learns to take an input n and predict 2 * n." }, { "code": null, "e": 2095, "s": 2008, "text": "There are 2 lines in the script above that are usually not present in PyTorch scripts." }, { "code": null, "e": 2179, "s": 2095, "text": "1. traced_cell = torch.jit.trace(model, X_test) 2. traced_cell.save('./model1.zip')" }, { "code": null, "e": 2469, "s": 2179, "text": "These two lines are required to create a TorchScript model (serialized pytorch model) that can be used in a language agnostic fashion in high performance environments. We will now use this model to make inference using DJL. I have used a Jupyter notebook running Java kernel for this demo." }, { "code": null, "e": 2589, "s": 2469, "text": "1 : Get all the required maven dependencies. DJL supports pytorch models out of the box. SLF4J is for logging purposes." }, { "code": null, "e": 2715, "s": 2589, "text": "%maven ai.djl.pytorch:pytorch-engine:0.8.0%maven ai.djl.pytorch:pytorch-native-auto:1.6.0%maven org.slf4j:slf4j-simple:1.7.26" }, { "code": null, "e": 2796, "s": 2715, "text": "If you get errors that say “unknown resolver null”, you can ignore them for now." }, { "code": null, "e": 2828, "s": 2796, "text": "2 : Import the required modules" }, { "code": null, "e": 2944, "s": 2828, "text": "import ai.djl.*;import ai.djl.inference.*;import ai.djl.ndarray.*;import ai.djl.translate.*;import java.nio.file.*;" }, { "code": null, "e": 3218, "s": 2944, "text": "It is worth highlighting the ndarray import here. N-Dimensional array is a popular data structure in many languages and numpy (ndarray library in python) is pretty much ubiquitous in the field of deep learning or pretty much any application involving numerical computation." }, { "code": null, "e": 3411, "s": 3218, "text": "Java doesn’t have a similar ndarray implementation. DJL provides the ndarray functionality through the above import. This is one of the key factors that allows DJL to work with PyTorch models." }, { "code": null, "e": 3571, "s": 3411, "text": "3. Declare path to model and model name. This assumes you are using a locally generated model. DJL provides some standard models too that can be used directly." }, { "code": null, "e": 3700, "s": 3571, "text": "Path modelDir = Paths.get(\"Path_To_Your_Model_Folder/\");Model model = Model.newInstance(\"model name\");model.load(modelDir);model" }, { "code": null, "e": 3782, "s": 3700, "text": "Current DJL documentation says models can be .zip , .tar, .tar.gz, .tgz or .tar.z" }, { "code": null, "e": 3885, "s": 3782, "text": "If the model is correctly loaded, you should see an output like ai.djl.pytorch.engine.PtModel@4cefa68f" }, { "code": null, "e": 3955, "s": 3885, "text": "4. Translator to handle the pre-processing and post-processing steps." }, { "code": null, "e": 4690, "s": 3955, "text": "Translator<Float, Float> translator = new Translator<Float, Float>(){ @Override public NDList processInput(TranslatorContext ctx, Float input) { NDManager manager = ctx.getNDManager(); NDArray array = manager.create(new float[] {input}); return new NDList (array); } @Override public Float processOutput(TranslatorContext ctx, NDList list) { NDArray temp_arr = list.get(0); return temp_arr.getFloat(); } @Override public Batchifier getBatchifier() { // The Batchifier describes how to combine a batch together // Stacking, the most common batchifier, takes N [X1, X2, ...] arrays to a single [N, X1, X2, ...] array return Batchifier.STACK; }};" }, { "code": null, "e": 4995, "s": 4690, "text": "This is the step that confuses most people. The translator defines the signature for the input and output data types <Input type, Output type>. For our example they both happen to be a float. Make sure to use Float, not float, as a reference is explicitly expected. This translation step is not optional." }, { "code": null, "e": 5154, "s": 4995, "text": "Further, if you look at the DJL doc for PreProcessor , you will find that NDList is the expected type for the preprocessing output that gets fed to the model." }, { "code": null, "e": 5252, "s": 5154, "text": "So, even if your input was hypothetically already an NDList type, you still need to do this step." }, { "code": null, "e": 5367, "s": 5252, "text": "The case for post processing is similar. It consumes the NDList and outputs the type described by your Translator." }, { "code": null, "e": 5560, "s": 5367, "text": "All the three overides above are mandatory as well. There are of’course pre-implemented translators provided by DJL and I recommend you to explore them, particularly the image processing ones." }, { "code": null, "e": 5581, "s": 5560, "text": "5. Making Prediction" }, { "code": null, "e": 5711, "s": 5581, "text": "Congratulations, you have done the hard work and are just a couple of lines of code away from making the inference. Here they are" }, { "code": null, "e": 5813, "s": 5711, "text": "Predictor<Float, Float> predictor = model.newPredictor(translator);predictor.predict(Your_Test_Float)" }, { "code": null, "e": 5901, "s": 5813, "text": "For my test case, I did predictor.predict(2.9f) and it output 5.799781. Ahh, pure Joy !" }, { "code": null, "e": 6279, "s": 5901, "text": "So we saw how we can create a PyTorch model and use that model for inference in a Java environment. This was a very simplistic use case though. For more advanced use cases, making the translator do the preprocessing and postprocessing correctly could require a few iterations. Further, the number of inbuilt modules (like the image processing ones) are currently few in number." } ]
Find the count of unique group combinations in an R data frame.
To find the count of unique group combinations in an R data frame, we can use count function of dplyr package along with ungroup function. For Example, if we have a data frame called df that contains three grouping columns say G1, G2, and G3 then we can count the unique group combinations in df by using the below given command − count(df,G1,G2,G3)%%ungroup() Following snippet creates a sample data frame − Grp1<-sample(1:2,20,replace=TRUE) Grp2<-sample(1:2,20,replace=TRUE) Grp3<-sample(1:2,20,replace=TRUE) df1<-data.frame(Grp1,Grp2,Grp3) df1 The following dataframe is created Grp1 Grp2 Grp3 1 2 1 1 2 1 2 1 3 2 1 2 4 2 2 1 5 1 1 1 6 1 1 2 7 2 1 1 8 2 1 2 9 2 1 2 10 1 1 1 11 2 1 1 12 2 1 1 13 2 2 2 14 2 1 2 15 1 2 2 16 2 2 1 17 2 1 2 18 2 2 1 19 1 1 2 20 2 2 2 To load dplyr package and count the unique group combinations in df1 on the above created data frame, add the following code to the above snippet − Grp1<-sample(1:2,20,replace=TRUE) Grp2<-sample(1:2,20,replace=TRUE) Grp3<-sample(1:2,20,replace=TRUE) df1<-data.frame(Grp1,Grp2,Grp3) library(dplyr) count(df1,Grp1,Grp2,Grp3)%%ungroup() If you execute all the above given snippets as a single program, it generates the following Output − Grp1 Grp2 Grp3 n 1 1 1 1 2 2 1 1 2 2 3 1 2 1 1 4 1 2 2 1 5 2 1 1 4 6 2 1 2 5 7 2 2 1 3 8 2 2 2 2 Following snippet creates a sample data frame − Class1<-sample(c("First","Second","Third"),20,replace=TRUE) Class2<-sample(c("First","Second","Third"),20,replace=TRUE) Class3<-sample(c("First","Second","Third"),20,replace=TRUE) df2<-data.frame(Class1,Class2,Class3) df2 The following dataframe is created Class1 Class2 Class3 1 First Second Second 2 Second Third Second 3 Third Second Third 4 First Third Second 5 Second Third First 6 Second Third First 7 First Second Second 8 Third First Third 9 Third Third Third 10 Second First Third 11 Third Second Second 12 Second Second Second 13 Third Second Second 14 Third First Third 15 First First First 16 Third Third Third 17 Third Third Third 18 First Third Third 19 Third Second First 20 Second Second Second To count the unique group combinations in df2 on the above created data frame, add the following code to the above snippet − Class1<-sample(c("First","Second","Third"),20,replace=TRUE) Class2<-sample(c("First","Second","Third"),20,replace=TRUE) Class3<-sample(c("First","Second","Third"),20,replace=TRUE) df2<-data.frame(Class1,Class2,Class3) count(df2,Class1,Class2,Class3)%%ungroup() If you execute all the above given snippets as a single program, it generates the following Output − Class1 Class2 Class3 n 1 First First First 1 2 First Second Second 2 3 First Third Second 1 4 First Third Third 1 5 Second First Third 1 6 Second Second Second 2 7 Second Third First 2 8 Second Third Second 1 9 Third First Third 2 10 Third Second First 1 11 Third Second Second 2 12 Third Second Third 1 13 Third Third Third 3
[ { "code": null, "e": 1201, "s": 1062, "text": "To find the count of unique group combinations in an R data frame, we can use count\nfunction of dplyr package along with ungroup function." }, { "code": null, "e": 1393, "s": 1201, "text": "For Example, if we have a data frame called df that contains three grouping columns say\nG1, G2, and G3 then we can count the unique group combinations in df by using the\nbelow given command −" }, { "code": null, "e": 1423, "s": 1393, "text": "count(df,G1,G2,G3)%%ungroup()" }, { "code": null, "e": 1471, "s": 1423, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 1609, "s": 1471, "text": "Grp1<-sample(1:2,20,replace=TRUE)\nGrp2<-sample(1:2,20,replace=TRUE)\nGrp3<-sample(1:2,20,replace=TRUE)\ndf1<-data.frame(Grp1,Grp2,Grp3)\ndf1" }, { "code": null, "e": 1644, "s": 1609, "text": "The following dataframe is created" }, { "code": null, "e": 1920, "s": 1644, "text": " Grp1 Grp2 Grp3\n 1 2 1 1\n 2 1 2 1\n 3 2 1 2\n 4 2 2 1\n 5 1 1 1\n 6 1 1 2\n 7 2 1 1\n 8 2 1 2\n 9 2 1 2\n10 1 1 1\n11 2 1 1\n12 2 1 1\n13 2 2 2\n14 2 1 2\n15 1 2 2\n16 2 2 1\n17 2 1 2\n18 2 2 1\n19 1 1 2\n20 2 2 2" }, { "code": null, "e": 2068, "s": 1920, "text": "To load dplyr package and count the unique group combinations in df1 on the above\ncreated data frame, add the following code to the above snippet −" }, { "code": null, "e": 2254, "s": 2068, "text": "Grp1<-sample(1:2,20,replace=TRUE)\nGrp2<-sample(1:2,20,replace=TRUE)\nGrp3<-sample(1:2,20,replace=TRUE)\ndf1<-data.frame(Grp1,Grp2,Grp3)\nlibrary(dplyr)\ncount(df1,Grp1,Grp2,Grp3)%%ungroup()" }, { "code": null, "e": 2355, "s": 2254, "text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output −" }, { "code": null, "e": 2508, "s": 2355, "text": "Grp1 Grp2 Grp3 n\n1 1 1 1 2\n2 1 1 2 2\n3 1 2 1 1\n4 1 2 2 1\n5 2 1 1 4\n6 2 1 2 5\n7 2 2 1 3\n8 2 2 2 2" }, { "code": null, "e": 2556, "s": 2508, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 2778, "s": 2556, "text": "Class1<-sample(c(\"First\",\"Second\",\"Third\"),20,replace=TRUE)\nClass2<-sample(c(\"First\",\"Second\",\"Third\"),20,replace=TRUE)\nClass3<-sample(c(\"First\",\"Second\",\"Third\"),20,replace=TRUE)\ndf2<-data.frame(Class1,Class2,Class3)\ndf2" }, { "code": null, "e": 2813, "s": 2778, "text": "The following dataframe is created" }, { "code": null, "e": 3305, "s": 2813, "text": " Class1 Class2 Class3\n 1 First Second Second\n 2 Second Third Second\n 3 Third Second Third\n 4 First Third Second\n 5 Second Third First\n 6 Second Third First\n 7 First Second Second\n 8 Third First Third\n 9 Third Third Third\n10 Second First Third\n11 Third Second Second\n12 Second Second Second\n13 Third Second Second\n14 Third First Third\n15 First First First\n16 Third Third Third\n17 Third Third Third\n18 First Third Third\n19 Third Second First\n20 Second Second Second" }, { "code": null, "e": 3430, "s": 3305, "text": "To count the unique group combinations in df2 on the above created data frame, add the\nfollowing code to the above snippet −" }, { "code": null, "e": 3691, "s": 3430, "text": "Class1<-sample(c(\"First\",\"Second\",\"Third\"),20,replace=TRUE)\nClass2<-sample(c(\"First\",\"Second\",\"Third\"),20,replace=TRUE)\nClass3<-sample(c(\"First\",\"Second\",\"Third\"),20,replace=TRUE)\ndf2<-data.frame(Class1,Class2,Class3)\ncount(df2,Class1,Class2,Class3)%%ungroup()" }, { "code": null, "e": 3792, "s": 3691, "text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output −" }, { "code": null, "e": 4148, "s": 3792, "text": " Class1 Class2 Class3 n\n 1 First First First 1\n 2 First Second Second 2\n 3 First Third Second 1\n 4 First Third Third 1\n 5 Second First Third 1\n 6 Second Second Second 2\n 7 Second Third First 2\n 8 Second Third Second 1\n 9 Third First Third 2\n10 Third Second First 1\n11 Third Second Second 2\n12 Third Second Third 1\n13 Third Third Third 3" } ]
Error 1046 No database Selected, how to resolve?
The 1046 error occurs if you forget to select any database before creating a table. Let us see how and why this error occurs. We will try to create a table without selecting a database − mysql> CREATE table MyTable1 -> ( -> id int -> ); ERROR 1046 (3D000): No database selected Or mysql> INSERT into sample values(1); ERROR 1046 (3D000): No database selected Look at the output above, we are getting the same 1046 error: “No database selected” Now, we can resolve this error after selecting any database with the help of USE command − mysql> USE business; Database changed Above, I have included the database with the name ‘business’. After that, we can create the same table (which we tried creating above) under the database, “business” − mysql> CREATE table MyTable1 -> ( -> id int -> ); Query OK, 0 rows affected (0.49 sec) We can check whether the table is present or not in the “business” database. The query is as follows − mysql> SHOW tables like '%MyTable1%'; The following is the output +---------------------------------+ | Tables_in_business (%MyTable1%) | +---------------------------------+ | mytable1 | +---------------------------------+ 1 row in set (0.05 sec)
[ { "code": null, "e": 1249, "s": 1062, "text": "The 1046 error occurs if you forget to select any database before creating a table.\nLet us see how and why this error occurs. We will try to create a table without selecting a\ndatabase −" }, { "code": null, "e": 1431, "s": 1249, "text": "mysql> CREATE table MyTable1\n -> (\n -> id int\n -> );\nERROR 1046 (3D000): No database selected\nOr\nmysql> INSERT into sample values(1);\nERROR 1046 (3D000): No database selected\n" }, { "code": null, "e": 1516, "s": 1431, "text": "Look at the output above, we are getting the same 1046 error: “No database selected”" }, { "code": null, "e": 1607, "s": 1516, "text": "Now, we can resolve this error after selecting any database with the help of USE command −" }, { "code": null, "e": 1646, "s": 1607, "text": "mysql> USE business;\nDatabase changed\n" }, { "code": null, "e": 1814, "s": 1646, "text": "Above, I have included the database with the name ‘business’. After that, we can create the\nsame table (which we tried creating above) under the database, “business” −" }, { "code": null, "e": 1911, "s": 1814, "text": "mysql> CREATE table MyTable1\n -> (\n -> id int\n -> );\nQuery OK, 0 rows affected (0.49 sec)\n" }, { "code": null, "e": 2014, "s": 1911, "text": "We can check whether the table is present or not in the “business” database. The query is as\nfollows −" }, { "code": null, "e": 2053, "s": 2014, "text": "mysql> SHOW tables like '%MyTable1%';\n" }, { "code": null, "e": 2081, "s": 2053, "text": "The following is the output" }, { "code": null, "e": 2286, "s": 2081, "text": "+---------------------------------+\n| Tables_in_business (%MyTable1%) |\n+---------------------------------+\n| mytable1 |\n+---------------------------------+\n1 row in set (0.05 sec)\n" } ]
How to display a value when select a JList item in Java?
A JList is a subclass of JComponent class that allows the user to choose either a single or multiple selections of items. A JList can generate a ListSelectiionListener interface and it includes one abstract method valueChanged(). We can display a value when an item is selected from a JList by implementing MouseListener interface or extending MouseAdapter class and call the getClickCount() method with single-click event (getClickCount() == 1) of MouseEvent class. import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class JListItemSeletionTest extends JFrame { private JList list; private JScrollPane jsp; private Vector data; public JListItemSeletionTest() { setTitle("JListItemSeletion Test"); list = new JList(); data = new Vector(); data.addElement("India"); data.addElement("Australia"); data.addElement("England"); data.addElement("England"); data.addElement("New Zealand"); data.addElement("South Africa"); list.setListData(data); list.setSelectedIndex(0); list.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { if (me.getClickCount() == 1) { JList target = (JList)me.getSource(); int index = target.locationToIndex(me.getPoint()); if (index >= 0) { Object item = target.getModel().getElementAt(index); JOptionPane.showMessageDialog(null, item.toString()); } } } }); jsp = new JScrollPane(list); add(jsp, BorderLayout.NORTH); setSize(400, 275); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String args[]) { new JListItemSeletionTest(); } }
[ { "code": null, "e": 1529, "s": 1062, "text": "A JList is a subclass of JComponent class that allows the user to choose either a single or multiple selections of items. A JList can generate a ListSelectiionListener interface and it includes one abstract method valueChanged(). We can display a value when an item is selected from a JList by implementing MouseListener interface or extending MouseAdapter class and call the getClickCount() method with single-click event (getClickCount() == 1) of MouseEvent class." }, { "code": null, "e": 2938, "s": 1529, "text": "import javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\npublic class JListItemSeletionTest extends JFrame {\n private JList list;\n private JScrollPane jsp;\n private Vector data;\n public JListItemSeletionTest() {\n setTitle(\"JListItemSeletion Test\");\n list = new JList();\n data = new Vector();\n data.addElement(\"India\");\n data.addElement(\"Australia\");\n data.addElement(\"England\");\n data.addElement(\"England\");\n data.addElement(\"New Zealand\");\n data.addElement(\"South Africa\");\n list.setListData(data);\n list.setSelectedIndex(0);\n list.addMouseListener(new MouseAdapter() {\n public void mouseClicked(MouseEvent me) {\n if (me.getClickCount() == 1) {\n JList target = (JList)me.getSource();\n int index = target.locationToIndex(me.getPoint());\n if (index >= 0) {\n Object item = target.getModel().getElementAt(index);\n JOptionPane.showMessageDialog(null, item.toString());\n }\n }\n }\n });\n jsp = new JScrollPane(list);\n add(jsp, BorderLayout.NORTH);\n setSize(400, 275);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String args[]) {\n new JListItemSeletionTest();\n }\n}" } ]
A Quick, Easy Way to Unpivot Data in Python | by Nik Piepenbreier | Towards Data Science
In a previous post, we took a look at doing three common Excel tasks in Python. Today we’ll take a look a function that, while possible in Excel, is pretty well hidden and kind of clunky. I’m talking about “un-pivoting” data in Excel. Python and Excel make it incredibly easy to analyze data and to present that analysis in a cross-tab style format. But what if you receive data only in that format? To take on meaningful analysis beyond that, it’s often necessary to spend a good chunk of time to reformat the data. We’ll call that process “un-pivoting”. Let’s load our dataset into a Pandas dataframe by running: import pandas as pddf = pd.read_excel('https://github.com/datagy/mediumdata/raw/master/pythonexcel.xlsx') If you want to explore the data in Excel, you can download the file here. We can print out the column names by writing the following: print(df.columns) This will return: ['Product', 'Quarter 1', 'Quarter 2', 'Quarter 3', 'Quarter 4'] Essentially, we want to turn all the Quarters into a single column (called Quarter), and have the Sales as a separate column. The Pandas Melt function makes this quite easy. We can simply write: df = df.melt(id_vars = 'Product', var_name = 'Quarter', value_name = 'Sales') Let’s break this down a little bit: id_vars: identifies the column to be used as identifier variables value_vars: the columns to unpivot. Which, if empty, (as is the case here), uses all columns except those identified in id_vars var_name: assigns a name to the columns that were unpivoted value_name: assigns a name to to the value column When we now print out df, we see it returned in a way that looks like this: Now, say we wanted to do this in good, old Excel. How would we go about this? Up until Excel 2016, this required downloading the Power Query add-on. Beginning with that version, features of the add-on were built into the main version. Let’s begin by opening the dataset. From there: Select the Data TabWhile having the table selected, select From Table/Range in Get & Transform DataSwitch to the Transform MenuSelect the columns to unpivotClick Unpivot ColumnsSelect Close and Load on the Home TabEnjoy your unpivoted data! Select the Data Tab While having the table selected, select From Table/Range in Get & Transform Data Switch to the Transform Menu Select the columns to unpivot Click Unpivot Columns Select Close and Load on the Home Tab Enjoy your unpivoted data! Thanks for reading this article! Be sure to check out my other posts, including Learn How to (easily!!) do 3 Advanced Excel Tasks in Python.
[ { "code": null, "e": 407, "s": 172, "text": "In a previous post, we took a look at doing three common Excel tasks in Python. Today we’ll take a look a function that, while possible in Excel, is pretty well hidden and kind of clunky. I’m talking about “un-pivoting” data in Excel." }, { "code": null, "e": 728, "s": 407, "text": "Python and Excel make it incredibly easy to analyze data and to present that analysis in a cross-tab style format. But what if you receive data only in that format? To take on meaningful analysis beyond that, it’s often necessary to spend a good chunk of time to reformat the data. We’ll call that process “un-pivoting”." }, { "code": null, "e": 787, "s": 728, "text": "Let’s load our dataset into a Pandas dataframe by running:" }, { "code": null, "e": 893, "s": 787, "text": "import pandas as pddf = pd.read_excel('https://github.com/datagy/mediumdata/raw/master/pythonexcel.xlsx')" }, { "code": null, "e": 967, "s": 893, "text": "If you want to explore the data in Excel, you can download the file here." }, { "code": null, "e": 1027, "s": 967, "text": "We can print out the column names by writing the following:" }, { "code": null, "e": 1045, "s": 1027, "text": "print(df.columns)" }, { "code": null, "e": 1063, "s": 1045, "text": "This will return:" }, { "code": null, "e": 1127, "s": 1063, "text": "['Product', 'Quarter 1', 'Quarter 2', 'Quarter 3', 'Quarter 4']" }, { "code": null, "e": 1322, "s": 1127, "text": "Essentially, we want to turn all the Quarters into a single column (called Quarter), and have the Sales as a separate column. The Pandas Melt function makes this quite easy. We can simply write:" }, { "code": null, "e": 1400, "s": 1322, "text": "df = df.melt(id_vars = 'Product', var_name = 'Quarter', value_name = 'Sales')" }, { "code": null, "e": 1436, "s": 1400, "text": "Let’s break this down a little bit:" }, { "code": null, "e": 1502, "s": 1436, "text": "id_vars: identifies the column to be used as identifier variables" }, { "code": null, "e": 1630, "s": 1502, "text": "value_vars: the columns to unpivot. Which, if empty, (as is the case here), uses all columns except those identified in id_vars" }, { "code": null, "e": 1690, "s": 1630, "text": "var_name: assigns a name to the columns that were unpivoted" }, { "code": null, "e": 1740, "s": 1690, "text": "value_name: assigns a name to to the value column" }, { "code": null, "e": 1816, "s": 1740, "text": "When we now print out df, we see it returned in a way that looks like this:" }, { "code": null, "e": 2099, "s": 1816, "text": "Now, say we wanted to do this in good, old Excel. How would we go about this? Up until Excel 2016, this required downloading the Power Query add-on. Beginning with that version, features of the add-on were built into the main version. Let’s begin by opening the dataset. From there:" }, { "code": null, "e": 2340, "s": 2099, "text": "Select the Data TabWhile having the table selected, select From Table/Range in Get & Transform DataSwitch to the Transform MenuSelect the columns to unpivotClick Unpivot ColumnsSelect Close and Load on the Home TabEnjoy your unpivoted data!" }, { "code": null, "e": 2360, "s": 2340, "text": "Select the Data Tab" }, { "code": null, "e": 2441, "s": 2360, "text": "While having the table selected, select From Table/Range in Get & Transform Data" }, { "code": null, "e": 2470, "s": 2441, "text": "Switch to the Transform Menu" }, { "code": null, "e": 2500, "s": 2470, "text": "Select the columns to unpivot" }, { "code": null, "e": 2522, "s": 2500, "text": "Click Unpivot Columns" }, { "code": null, "e": 2560, "s": 2522, "text": "Select Close and Load on the Home Tab" }, { "code": null, "e": 2587, "s": 2560, "text": "Enjoy your unpivoted data!" } ]
How to filter data using where Clause, “BETWEEN” and “AND” 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 filter data using where Clause, “BETWEEN” and “AND” 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" /> </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 after insert values to update listview from cursor using BETWEEN and AND operator. 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; 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); final ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list); listView.setAdapter(arrayAdapter); 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.util.ArrayList; class DatabaseHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "salaryDatabase3"; public static final String CONTACTS_TABLE_NAME = "SalaryDetails"; public DatabaseHelper(Context context) { super(context,DATABASE_NAME,null,1); } @Override public void onCreate(SQLiteDatabase db) { try { db.execSQL( "create table "+ CONTACTS_TABLE_NAME +"(id INTEGER PRIMARY KEY, name text,salary text )" ); } 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.insert(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 * from "+CONTACTS_TABLE_NAME+" WHERE salary BETWEEN '10' AND '10000' ", null ); res.moveToFirst(); while(res.isAfterLast() == false) { array_list.add(res.getString(res.getColumnIndex("name"))); res.moveToNext(); } return array_list; } } 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 it is showing names with salary is not in between 10 AND 10000 in list view. 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 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." }, { "code": null, "e": 1566, "s": 1457, "text": "This example demonstrate about How to filter data using where Clause, “BETWEEN” and “AND” in Android sqlite." }, { "code": null, "e": 1695, "s": 1566, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1760, "s": 1695, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 3048, "s": 1760, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\"\n android:orientation=\"vertical\">\n <EditText\n android:id=\"@+id/name\"\n android:layout_width=\"match_parent\"\n android:hint=\"Enter Name\"\n android:layout_height=\"wrap_content\" />\n <EditText\n android:id=\"@+id/salary\"\n android:layout_width=\"match_parent\"\n android:inputType=\"numberDecimal\"\n android:hint=\"Enter Salary\"\n android:layout_height=\"wrap_content\" />\n <LinearLayout\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"><Button\n android:id=\"@+id/save\"\n android:text=\"Save\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:id=\"@+id/refresh\"\n android:text=\"Refresh\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n </LinearLayout>\n\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\">\n </ListView>\n</LinearLayout>" }, { "code": null, "e": 3295, "s": 3048, "text": "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 after insert values to update listview from cursor using BETWEEN and AND operator." }, { "code": null, "e": 3352, "s": 3295, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5480, "s": 3352, "text": "package com.example.andy.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Toast;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends AppCompatActivity {\n Button save, refresh;\n EditText name, salary;\n private ListView listView;\n\n @Override\n protected void onCreate(Bundle readdInstanceState) {\n super.onCreate(readdInstanceState);\n setContentView(R.layout.activity_main);\n final DatabaseHelper helper = new DatabaseHelper(this);\n final ArrayList array_list = helper.getAllCotacts();\n name = findViewById(R.id.name);\n salary = findViewById(R.id.salary);\n listView = findViewById(R.id.listView);\n final ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list);\n listView.setAdapter(arrayAdapter);\n findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n array_list.clear();\n array_list.addAll(helper.getAllCotacts());\n arrayAdapter.notifyDataSetChanged();\n listView.invalidateViews();\n listView.refreshDrawableState();\n }\n });\n\n findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {\n if (helper.insert(name.getText().toString(), salary.getText().toString())) {\n Toast.makeText(MainActivity.this, \"Inserted\", Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(MainActivity.this, \"NOT Inserted\", Toast.LENGTH_LONG).show();\n }\n } else {\n name.setError(\"Enter NAME\");\n salary.setError(\"Enter Salary\");\n }\n }\n });\n }\n}" }, { "code": null, "e": 5540, "s": 5480, "text": "Step 4 − Add the following code to src/ DatabaseHelper.java" }, { "code": null, "e": 7524, "s": 5540, "text": "package com.example.andy.myapplication;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteException;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\n\nclass DatabaseHelper extends SQLiteOpenHelper {\n public static final String DATABASE_NAME = \"salaryDatabase3\";\n public static final String CONTACTS_TABLE_NAME = \"SalaryDetails\";\n public DatabaseHelper(Context context) {\n super(context,DATABASE_NAME,null,1);\n }\n\n @Override\n public void onCreate(SQLiteDatabase db) {\n try {\n db.execSQL(\n \"create table \"+ CONTACTS_TABLE_NAME +\"(id INTEGER PRIMARY KEY, name text,salary text )\"\n );\n } catch (SQLiteException e) {\n try {\n throw new IOException(e);\n } catch (IOException e1) {\n e1.printStackTrace();\n }\n }\n }\n\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n db.execSQL(\"DROP TABLE IF EXISTS \"+CONTACTS_TABLE_NAME);\n onCreate(db);\n }\n\n public boolean insert(String s, String s1) {\n SQLiteDatabase db = this.getWritableDatabase();\n\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"name\", s);\n contentValues.put(\"salary\", s1);\n db.insert(CONTACTS_TABLE_NAME, null, contentValues);\n return true;\n }\n\n public ArrayList getAllCotacts() {\n SQLiteDatabase db = this.getReadableDatabase();\n ArrayList<String> array_list = new ArrayList<String>();\n Cursor res = db.rawQuery( \"select * from \"+CONTACTS_TABLE_NAME+\" WHERE salary BETWEEN '10' AND '10000' \", null );\n res.moveToFirst();\n\n while(res.isAfterLast() == false) {\n array_list.add(res.getString(res.getColumnIndex(\"name\")));\n res.moveToNext();\n }\n return array_list;\n }\n}" }, { "code": null, "e": 7871, "s": 7524, "text": "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 −" }, { "code": null, "e": 7968, "s": 7871, "text": "In the above result it is showing names with salary is not in between 10 AND 10000 in list view." }, { "code": null, "e": 8008, "s": 7968, "text": "Click here to download the project code" } ]
How to create an increment of 10 value once you click a button in JavaScript?
For this, use click() along with parseInt(). Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css"> </head> <body> <div id="add">10</div> <div id="sequenceValue"></div> <button id="addSequenceOf10">addValue10EachTimePressMe</button> <script> addValue = 0; $("#addSequenceOf10").click(function() { var actualValue = parseInt($("#add").html()); addValue =addValue+ actualValue; $("#sequenceValue").html(addValue); }); </script> </body> </html> To run the above program, just save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS Code editor. This will produce the following output − Now, press the button you will get 10 then 20 30 40.......N; as in the below output − After clicking one more time, the snapshot is as follows. This will produce the following output −
[ { "code": null, "e": 1107, "s": 1062, "text": "For this, use click() along with parseInt()." }, { "code": null, "e": 1118, "s": 1107, "text": " Live Demo" }, { "code": null, "e": 1978, "s": 1118, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css\">\n</head>\n<body>\n<div id=\"add\">10</div>\n<div id=\"sequenceValue\"></div>\n<button id=\"addSequenceOf10\">addValue10EachTimePressMe</button>\n<script>\n addValue = 0;\n $(\"#addSequenceOf10\").click(function() {\n var actualValue = parseInt($(\"#add\").html());\n addValue =addValue+ actualValue;\n $(\"#sequenceValue\").html(addValue);\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2144, "s": 1978, "text": "To run the above program, just save the file name anyName.html(index.html) and right click on\nthe file and select the option open with live server in VS Code editor." }, { "code": null, "e": 2185, "s": 2144, "text": "This will produce the following output −" }, { "code": null, "e": 2271, "s": 2185, "text": "Now, press the button you will get 10 then 20 30 40.......N; as in the below output −" }, { "code": null, "e": 2329, "s": 2271, "text": "After clicking one more time, the snapshot is as follows." }, { "code": null, "e": 2370, "s": 2329, "text": "This will produce the following output −" } ]
Unraveling Spline Regression in R | by Trisha Chandra | Towards Data Science
When we talk about regression, the first things that come to our mind are linear or logistic regression and somewhere in the distant back of the mind polynomial regression. Linear and logistic regression are 2 of the most popular types of regression methods. However, there are many different types of regression methods which can prove to be useful in different scenarios. Today we will be looking at Spline Regression using Step Functions. Spline Regression is a non-parametric regression technique. This regression technique divides the datasets into bins at intervals or points called knots and each bin has its separate fit. Let’s look at one simple implementation of Spline regression using step function in R. Visualizing the dataset: Quantity <- c(25,39,45,57,70,85,89,100,110,124,137,150,177)Sales <- c(1000,1250,2600,3000,3500,4500,5000,4700,4405,4000,3730,3400,3300)data <- data.frame(Quantity,Sales)data library(plotly)plot_ly(data,x=~Quantity, y=~Sales, type="scatter") Let’s fit a linear regression on and see how it works: fit <- lm(Sales ~ Quantity, data=data)summary(fit) plot_ly(data,x=~Quantity, y=~Sales, type="scatter") %>% add_lines(x = ~Quantity, y = fitted(fit)) The equation here takes the form of: In this case: We can see that linear regression produces a terrible fit in this case, as seen from the plot above and the R-squared value. Let’s now introduce a polynomial term (quadratic here) to the equation and analyze the performance of the model. fit2 <- lm(Sales ~ poly(Quantity,2) + Quantity, data=data)summary(fit2) plot_ly(data,x=~Quantity, y=~Sales, type="scatter") %>% add_lines(x = ~Quantity, y = fitted(fit2)) The equation here takes the form of: In this case: We can see that it’s not a bad fit but not a great one either. The predicted apex is somewhat far from the actual apex. Polynomial regression also comes with various disadvantages that it tends to overfit. It can lead to an increase in complexity as the number of features increases. The disadvantages of the polynomial regression and incompetence of the linear model can be overcome by using Spline Regression. Let us visualize the dataset by dividing it into two bins. One on the left side of the peak that occurs at Quantity = 89 and the other at its right side, as shown in the two images below, respectively. Now let’s combine the above two images into one equation and perform piecewise regression or spline regression using step function. The equation would take the form of: In this case: Xbar here is called the Knot value. data$Xbar <- ifelse(data$Quantity>89,1,0)data$diff <- data$Quantity - 89data$X <- data$diff*data$Xbardata After performing the above manipulation the data would look like this: Let us now fit the equation we saw above: The X in the equation below is (x-xbar)*Xk reg <- lm(Sales ~ Quantity + X, data = data)plot_ly(data,x=~Quantity, y=~Sales, type="scatter") %>% add_lines(x = ~Quantity, y = fitted(reg)) summary(reg) As we can see from the plot and the R-squared values above, spline regression produces a much better result, in this scenario. The above results can also be obtained using Segmented package in R: library(segmented)fit_seg <- segmented(fit, seg.Z = ~Quantity, psi = list(Quantity=89))plot_ly(data,x=~Quantity, y=~Sales, type="scatter") %>% add_lines(x = ~Quantity, y = fitted(fit_seg)) Note: If you are not providing the breakpoint value (Quantity = 89, here), then use “psi = NA” summary(fit_seg) Both methods produce the same result. This was one simple example of spline regression. Splines can be fitted using polynomials functions as well, called Polynomial Splines, so instead of fitting a high-degree polynomial for the entire range of X, splines or piecewise polynomial regression with lower degree polynomials can be fit in sperate regions of X. CHOOSING THE LOCATION AND NUMBER OF THE KNOTS Splines can be modelled by adding more number of knots thereby increasing the flexibility of the model. In general, placing K knots lead to the fitting of K + 1 functions. The choice of placing a knot may depend on various factors. Since regression is highly flexible in areas where there are more knots placed, it’s intuitive to place knots where there is more variation in the data or where the function changes more rapidly. The regions which seem comparatively stable need not have too many knots and can use fewer of them. CONCLUSION: We learned about Spline regression using step function in this article. There are other kinds of polynomial functions that can be applied too. One of the common ones is the cubic spline which uses a polynomial function of the third order. Yet another method of implementing splines is Smoothing Splines. Splines often provide better results as compared to polynomial regression. In splines, flexibility can be increased by increasing the number of knots and without increasing the degree of the polynomial. They also produce more stable results as compared to polynomial regression, in general. I hope this article was useful in grabbing the idea of Spline and Piecewise Regression and getting started with it. REFERENCES: [1]Splines in Regression By Andrew Wheeler. http://utdallas.edu/~Andrew.Wheeler/Splines.html [2]How to Develop a Piecewise Linear Regression Model in R by Shokoufeh Mirzaei. https://www.youtube.com/watch?v=onfXC1qe7LI [3]Breakpoint analysis, segmented regression. https://rpubs.com/MarkusLoew/12164 [4]Gareth James, Daniela Witten, Trevor Hastie, Robert Tibshirani. An Introduction to Statistical Learning: with Applications in R. New York: Springer, 2013.
[ { "code": null, "e": 614, "s": 172, "text": "When we talk about regression, the first things that come to our mind are linear or logistic regression and somewhere in the distant back of the mind polynomial regression. Linear and logistic regression are 2 of the most popular types of regression methods. However, there are many different types of regression methods which can prove to be useful in different scenarios. Today we will be looking at Spline Regression using Step Functions." }, { "code": null, "e": 889, "s": 614, "text": "Spline Regression is a non-parametric regression technique. This regression technique divides the datasets into bins at intervals or points called knots and each bin has its separate fit. Let’s look at one simple implementation of Spline regression using step function in R." }, { "code": null, "e": 914, "s": 889, "text": "Visualizing the dataset:" }, { "code": null, "e": 1088, "s": 914, "text": "Quantity <- c(25,39,45,57,70,85,89,100,110,124,137,150,177)Sales <- c(1000,1250,2600,3000,3500,4500,5000,4700,4405,4000,3730,3400,3300)data <- data.frame(Quantity,Sales)data" }, { "code": null, "e": 1169, "s": 1088, "text": "library(plotly)plot_ly(data,x=~Quantity, y=~Sales, type=\"scatter\")" }, { "code": null, "e": 1224, "s": 1169, "text": "Let’s fit a linear regression on and see how it works:" }, { "code": null, "e": 1275, "s": 1224, "text": "fit <- lm(Sales ~ Quantity, data=data)summary(fit)" }, { "code": null, "e": 1388, "s": 1275, "text": "plot_ly(data,x=~Quantity, y=~Sales, type=\"scatter\") %>% add_lines(x = ~Quantity, y = fitted(fit))" }, { "code": null, "e": 1425, "s": 1388, "text": "The equation here takes the form of:" }, { "code": null, "e": 1439, "s": 1425, "text": "In this case:" }, { "code": null, "e": 1564, "s": 1439, "text": "We can see that linear regression produces a terrible fit in this case, as seen from the plot above and the R-squared value." }, { "code": null, "e": 1677, "s": 1564, "text": "Let’s now introduce a polynomial term (quadratic here) to the equation and analyze the performance of the model." }, { "code": null, "e": 1749, "s": 1677, "text": "fit2 <- lm(Sales ~ poly(Quantity,2) + Quantity, data=data)summary(fit2)" }, { "code": null, "e": 1863, "s": 1749, "text": "plot_ly(data,x=~Quantity, y=~Sales, type=\"scatter\") %>% add_lines(x = ~Quantity, y = fitted(fit2))" }, { "code": null, "e": 1900, "s": 1863, "text": "The equation here takes the form of:" }, { "code": null, "e": 1914, "s": 1900, "text": "In this case:" }, { "code": null, "e": 2198, "s": 1914, "text": "We can see that it’s not a bad fit but not a great one either. The predicted apex is somewhat far from the actual apex. Polynomial regression also comes with various disadvantages that it tends to overfit. It can lead to an increase in complexity as the number of features increases." }, { "code": null, "e": 2326, "s": 2198, "text": "The disadvantages of the polynomial regression and incompetence of the linear model can be overcome by using Spline Regression." }, { "code": null, "e": 2528, "s": 2326, "text": "Let us visualize the dataset by dividing it into two bins. One on the left side of the peak that occurs at Quantity = 89 and the other at its right side, as shown in the two images below, respectively." }, { "code": null, "e": 2660, "s": 2528, "text": "Now let’s combine the above two images into one equation and perform piecewise regression or spline regression using step function." }, { "code": null, "e": 2697, "s": 2660, "text": "The equation would take the form of:" }, { "code": null, "e": 2711, "s": 2697, "text": "In this case:" }, { "code": null, "e": 2747, "s": 2711, "text": "Xbar here is called the Knot value." }, { "code": null, "e": 2853, "s": 2747, "text": "data$Xbar <- ifelse(data$Quantity>89,1,0)data$diff <- data$Quantity - 89data$X <- data$diff*data$Xbardata" }, { "code": null, "e": 2924, "s": 2853, "text": "After performing the above manipulation the data would look like this:" }, { "code": null, "e": 2966, "s": 2924, "text": "Let us now fit the equation we saw above:" }, { "code": null, "e": 3009, "s": 2966, "text": "The X in the equation below is (x-xbar)*Xk" }, { "code": null, "e": 3166, "s": 3009, "text": "reg <- lm(Sales ~ Quantity + X, data = data)plot_ly(data,x=~Quantity, y=~Sales, type=\"scatter\") %>% add_lines(x = ~Quantity, y = fitted(reg))" }, { "code": null, "e": 3179, "s": 3166, "text": "summary(reg)" }, { "code": null, "e": 3306, "s": 3179, "text": "As we can see from the plot and the R-squared values above, spline regression produces a much better result, in this scenario." }, { "code": null, "e": 3375, "s": 3306, "text": "The above results can also be obtained using Segmented package in R:" }, { "code": null, "e": 3579, "s": 3375, "text": "library(segmented)fit_seg <- segmented(fit, seg.Z = ~Quantity, psi = list(Quantity=89))plot_ly(data,x=~Quantity, y=~Sales, type=\"scatter\") %>% add_lines(x = ~Quantity, y = fitted(fit_seg))" }, { "code": null, "e": 3674, "s": 3579, "text": "Note: If you are not providing the breakpoint value (Quantity = 89, here), then use “psi = NA”" }, { "code": null, "e": 3691, "s": 3674, "text": "summary(fit_seg)" }, { "code": null, "e": 3729, "s": 3691, "text": "Both methods produce the same result." }, { "code": null, "e": 4048, "s": 3729, "text": "This was one simple example of spline regression. Splines can be fitted using polynomials functions as well, called Polynomial Splines, so instead of fitting a high-degree polynomial for the entire range of X, splines or piecewise polynomial regression with lower degree polynomials can be fit in sperate regions of X." }, { "code": null, "e": 4094, "s": 4048, "text": "CHOOSING THE LOCATION AND NUMBER OF THE KNOTS" }, { "code": null, "e": 4622, "s": 4094, "text": "Splines can be modelled by adding more number of knots thereby increasing the flexibility of the model. In general, placing K knots lead to the fitting of K + 1 functions. The choice of placing a knot may depend on various factors. Since regression is highly flexible in areas where there are more knots placed, it’s intuitive to place knots where there is more variation in the data or where the function changes more rapidly. The regions which seem comparatively stable need not have too many knots and can use fewer of them." }, { "code": null, "e": 4634, "s": 4622, "text": "CONCLUSION:" }, { "code": null, "e": 5229, "s": 4634, "text": "We learned about Spline regression using step function in this article. There are other kinds of polynomial functions that can be applied too. One of the common ones is the cubic spline which uses a polynomial function of the third order. Yet another method of implementing splines is Smoothing Splines. Splines often provide better results as compared to polynomial regression. In splines, flexibility can be increased by increasing the number of knots and without increasing the degree of the polynomial. They also produce more stable results as compared to polynomial regression, in general." }, { "code": null, "e": 5345, "s": 5229, "text": "I hope this article was useful in grabbing the idea of Spline and Piecewise Regression and getting started with it." }, { "code": null, "e": 5357, "s": 5345, "text": "REFERENCES:" }, { "code": null, "e": 5450, "s": 5357, "text": "[1]Splines in Regression By Andrew Wheeler. http://utdallas.edu/~Andrew.Wheeler/Splines.html" }, { "code": null, "e": 5575, "s": 5450, "text": "[2]How to Develop a Piecewise Linear Regression Model in R by Shokoufeh Mirzaei. https://www.youtube.com/watch?v=onfXC1qe7LI" }, { "code": null, "e": 5656, "s": 5575, "text": "[3]Breakpoint analysis, segmented regression. https://rpubs.com/MarkusLoew/12164" } ]
Classifying fashion apparel- Getting started with Computer Vision | by Navendu Pottekkat | Towards Data Science
In this guide, you will be training a neural network model to classify images of clothing like shirts, coats, sneakers etc. Whew! That sounds a lot for a beginner tutorial, I mean we are just getting started right? Not to worry! Don’t get overwhelmed, it’s okay if you don’t understand all the details. You would learn all the details as you go deeper into the article, trust me :). If you are totally new to machine learning, I would suggest you check out my beginner tutorial. Here are the completed Colab Notebook and the GitHub repo. With that said, let’s get started! We will be using the Fashion-MNIST dataset. It is a data set composed of 60,000 square (28x28 pixel) grayscale images of 10 types of clothing. Each of the apparels are assigned a particular label: 0- T-shirt/top1- Trouser2- Pullover3- Dress4- Coat5- Sandal6- Shirt7- Sneaker8- Bag9- Ankle boot We will use TensorFlow and TensorFlow Keras for building our model. TensorFlow is an end-to-end open source platform for machine learning. It has a comprehensive, flexible ecosystem of tools, libraries and community resources that lets researchers push the state-of-the-art in ML and developers easily build and deploy ML-powered applications. Keras is TensorFlow’s high-level API for building and training deep learning models. You can read more about them. Getting a basic idea about the tools are enough for now as you would learn more about TensorFlow and Keras as you go along. Less talking, more code!!! We will use the numpy and matplotlib also as helper libraries. The Fashion-MNIST data is readily available in Keras datasets. This will load the fashion_mnist data into 4 NumPy arrays: The train_images and train_labels arrays are the training set — the data the model uses to learn. The model is tested against the test set, the test_images, and test_labels arrays. The following code shows that there are 6000 training images and 1000 test images of 28x28 pixels. We will train the model on the training images and test the performance of the model by performing predictions on the test images. The images have been labelled correspondingly in the train_labels and test_labels. Train Images Shape: (60000, 28, 28)Train Labels Shape: (60000,)Test Images Shape: (10000, 28, 28)Test Labels Shape: (10000,) Now let’s take a look at the data we just loaded. Since the pixel values lie between 0–255, we convert it into values between 0 and 1. I.e we just divide the pixel values by 255.0. Building a neural network requires configuring the layers of the model and then compiling the model. Layers are the basic building blocks of a neural network. They extract features or representations from the data that is fed into them. After training, these features would help us solve the problem at hand — classifying fashion apparels. Here we will chain together some simple layers to create our model. The first layer of the network, tf.keras.layers.Flatten, transforms the image which is a 2D array (of 28x28 pixels) to a 1D array (of size 28*28 = 784). It basically takes the input image and lines up each row of pixels back to back. This layer is used only for transforming the data. Once the input images have been transformed by the Flatten layer, the network then has two tf.keras.layers.Dense layers. These are well, densely connected or fully connected layers. The first Dense layer has 128 neurons and the second Dense layer, which is the last layer of our network, has 10 neurons. The last layer of the network is our output layer which would provide the output of the model. Each of the 10 nodes would contain the probability score that indicates the current image belongs to one of the 10 classes. (Remember there are 10 classifications for the apparels in our data) We are almost ready to train our model! Before that, we have to configure a few more settings. Loss function: This measures how accurate the model is during training. You want to minimize this function to “steer” the model in the right direction. I.e the model tries to minimise the loss function with each step of the training to improve the model. Optimizer: Optimizers update the weight parameters to minimize the loss function. Metrics: A metric is a function that is used to judge the performance of your model. Metric functions are similar to loss functions, except that the results from evaluating a metric are not used when training the model. The following model uses accuracy, the fraction of the images that are correctly classified. You don’t need to know all the details about the loss function sparse_categorical_crossentropy or adam optimizer for now. You can check out the docs if you need to learn more. For now, having a grasp of what loss function and optimizers are would be enough. For training our model, we simply feed the model our training data and labels contained in train_images and train_labels respectively. We call the model.fit method to “fit” the model to the training data. Epoch 1/101875/1875 [==============================] - 3s 2ms/step - loss: 0.3768 - accuracy: 0.8636Epoch 2/101875/1875 [==============================] - 3s 2ms/step - loss: 0.3394 - accuracy: 0.8762Epoch 3/101875/1875 [==============================] - 3s 2ms/step - loss: 0.3145 - accuracy: 0.8851Epoch 4/101875/1875 [==============================] - 3s 2ms/step - loss: 0.2965 - accuracy: 0.8902Epoch 5/101875/1875 [==============================] - 3s 2ms/step - loss: 0.2818 - accuracy: 0.8957Epoch 6/101875/1875 [==============================] - 3s 2ms/step - loss: 0.2698 - accuracy: 0.9002Epoch 7/101875/1875 [==============================] - 3s 2ms/step - loss: 0.2582 - accuracy: 0.9043Epoch 8/101875/1875 [==============================] - 3s 2ms/step - loss: 0.2495 - accuracy: 0.9074Epoch 9/101875/1875 [==============================] - 3s 2ms/step - loss: 0.2409 - accuracy: 0.9095Epoch 10/101875/1875 [==============================] - 4s 2ms/step - loss: 0.2324 - accuracy: 0.9137 We can see the loss and accuracy metrics displayed as the model is being trained. As the model trains, the loss decreases and accuracy increases. Kudos! Your model is learning! The model has about 90% (0.90) accuracy on the training data. You may have values somewhere around 90% (not to worry if it is slightly different as it is prone to some randomness) But that is not enough! We still haven’t tested the model. We will now test our model on our test data, which the model has never seen before! Let’s see how it performs. 313/313 - 1s - loss: 0.3366 - accuracy: 0.8838Test accuracy: 0.8838000297546387 It turns out that the accuracy on the test dataset is a little less than the train dataset. This could mean that our model is over-fitting on our training data. We will not worry about that now. In future articles, we will discuss what causes over-fitting and how we can prevent it. Finally! We can now use our model to make predictions on images. Here we have a function to plot 100 random test images and their predicted labels. If a prediction result is different from the label provided in the test_labels dataset, we will highlight it in red color. Wow! You have done it! You have successfully created a model which can look at images of fashion apparels and classify them with a good certainty! When you think about it, all it took was a few lines of code. We see a few errors, but for our first model, things are looking pretty good! The completed Colab Notebook is available here and the code is also available in GitHub. With this new knowledge of TensorFlow, Keras and machine learning in general, you would be able to create your own models for a wide variety of datasets. Moreover, the tools and techniques you learned here are the foundations of complex models used in practice. In the coming tutorials, we will take a look at Convolutional Neural Networks- a type of neural network used widely for computer vision applications. We will see that we can improve the accuracy of our model further using CNNs. Happy Coding! Some rights reserved
[ { "code": null, "e": 171, "s": 47, "text": "In this guide, you will be training a neural network model to classify images of clothing like shirts, coats, sneakers etc." }, { "code": null, "e": 262, "s": 171, "text": "Whew! That sounds a lot for a beginner tutorial, I mean we are just getting started right?" }, { "code": null, "e": 430, "s": 262, "text": "Not to worry! Don’t get overwhelmed, it’s okay if you don’t understand all the details. You would learn all the details as you go deeper into the article, trust me :)." }, { "code": null, "e": 526, "s": 430, "text": "If you are totally new to machine learning, I would suggest you check out my beginner tutorial." }, { "code": null, "e": 585, "s": 526, "text": "Here are the completed Colab Notebook and the GitHub repo." }, { "code": null, "e": 620, "s": 585, "text": "With that said, let’s get started!" }, { "code": null, "e": 763, "s": 620, "text": "We will be using the Fashion-MNIST dataset. It is a data set composed of 60,000 square (28x28 pixel) grayscale images of 10 types of clothing." }, { "code": null, "e": 817, "s": 763, "text": "Each of the apparels are assigned a particular label:" }, { "code": null, "e": 914, "s": 817, "text": "0- T-shirt/top1- Trouser2- Pullover3- Dress4- Coat5- Sandal6- Shirt7- Sneaker8- Bag9- Ankle boot" }, { "code": null, "e": 982, "s": 914, "text": "We will use TensorFlow and TensorFlow Keras for building our model." }, { "code": null, "e": 1258, "s": 982, "text": "TensorFlow is an end-to-end open source platform for machine learning. It has a comprehensive, flexible ecosystem of tools, libraries and community resources that lets researchers push the state-of-the-art in ML and developers easily build and deploy ML-powered applications." }, { "code": null, "e": 1343, "s": 1258, "text": "Keras is TensorFlow’s high-level API for building and training deep learning models." }, { "code": null, "e": 1497, "s": 1343, "text": "You can read more about them. Getting a basic idea about the tools are enough for now as you would learn more about TensorFlow and Keras as you go along." }, { "code": null, "e": 1524, "s": 1497, "text": "Less talking, more code!!!" }, { "code": null, "e": 1587, "s": 1524, "text": "We will use the numpy and matplotlib also as helper libraries." }, { "code": null, "e": 1650, "s": 1587, "text": "The Fashion-MNIST data is readily available in Keras datasets." }, { "code": null, "e": 1709, "s": 1650, "text": "This will load the fashion_mnist data into 4 NumPy arrays:" }, { "code": null, "e": 1807, "s": 1709, "text": "The train_images and train_labels arrays are the training set — the data the model uses to learn." }, { "code": null, "e": 1890, "s": 1807, "text": "The model is tested against the test set, the test_images, and test_labels arrays." }, { "code": null, "e": 2203, "s": 1890, "text": "The following code shows that there are 6000 training images and 1000 test images of 28x28 pixels. We will train the model on the training images and test the performance of the model by performing predictions on the test images. The images have been labelled correspondingly in the train_labels and test_labels." }, { "code": null, "e": 2328, "s": 2203, "text": "Train Images Shape: (60000, 28, 28)Train Labels Shape: (60000,)Test Images Shape: (10000, 28, 28)Test Labels Shape: (10000,)" }, { "code": null, "e": 2378, "s": 2328, "text": "Now let’s take a look at the data we just loaded." }, { "code": null, "e": 2509, "s": 2378, "text": "Since the pixel values lie between 0–255, we convert it into values between 0 and 1. I.e we just divide the pixel values by 255.0." }, { "code": null, "e": 2610, "s": 2509, "text": "Building a neural network requires configuring the layers of the model and then compiling the model." }, { "code": null, "e": 2849, "s": 2610, "text": "Layers are the basic building blocks of a neural network. They extract features or representations from the data that is fed into them. After training, these features would help us solve the problem at hand — classifying fashion apparels." }, { "code": null, "e": 2917, "s": 2849, "text": "Here we will chain together some simple layers to create our model." }, { "code": null, "e": 3202, "s": 2917, "text": "The first layer of the network, tf.keras.layers.Flatten, transforms the image which is a 2D array (of 28x28 pixels) to a 1D array (of size 28*28 = 784). It basically takes the input image and lines up each row of pixels back to back. This layer is used only for transforming the data." }, { "code": null, "e": 3323, "s": 3202, "text": "Once the input images have been transformed by the Flatten layer, the network then has two tf.keras.layers.Dense layers." }, { "code": null, "e": 3384, "s": 3323, "text": "These are well, densely connected or fully connected layers." }, { "code": null, "e": 3794, "s": 3384, "text": "The first Dense layer has 128 neurons and the second Dense layer, which is the last layer of our network, has 10 neurons. The last layer of the network is our output layer which would provide the output of the model. Each of the 10 nodes would contain the probability score that indicates the current image belongs to one of the 10 classes. (Remember there are 10 classifications for the apparels in our data)" }, { "code": null, "e": 3889, "s": 3794, "text": "We are almost ready to train our model! Before that, we have to configure a few more settings." }, { "code": null, "e": 4144, "s": 3889, "text": "Loss function: This measures how accurate the model is during training. You want to minimize this function to “steer” the model in the right direction. I.e the model tries to minimise the loss function with each step of the training to improve the model." }, { "code": null, "e": 4226, "s": 4144, "text": "Optimizer: Optimizers update the weight parameters to minimize the loss function." }, { "code": null, "e": 4539, "s": 4226, "text": "Metrics: A metric is a function that is used to judge the performance of your model. Metric functions are similar to loss functions, except that the results from evaluating a metric are not used when training the model. The following model uses accuracy, the fraction of the images that are correctly classified." }, { "code": null, "e": 4797, "s": 4539, "text": "You don’t need to know all the details about the loss function sparse_categorical_crossentropy or adam optimizer for now. You can check out the docs if you need to learn more. For now, having a grasp of what loss function and optimizers are would be enough." }, { "code": null, "e": 4932, "s": 4797, "text": "For training our model, we simply feed the model our training data and labels contained in train_images and train_labels respectively." }, { "code": null, "e": 5002, "s": 4932, "text": "We call the model.fit method to “fit” the model to the training data." }, { "code": null, "e": 6004, "s": 5002, "text": "Epoch 1/101875/1875 [==============================] - 3s 2ms/step - loss: 0.3768 - accuracy: 0.8636Epoch 2/101875/1875 [==============================] - 3s 2ms/step - loss: 0.3394 - accuracy: 0.8762Epoch 3/101875/1875 [==============================] - 3s 2ms/step - loss: 0.3145 - accuracy: 0.8851Epoch 4/101875/1875 [==============================] - 3s 2ms/step - loss: 0.2965 - accuracy: 0.8902Epoch 5/101875/1875 [==============================] - 3s 2ms/step - loss: 0.2818 - accuracy: 0.8957Epoch 6/101875/1875 [==============================] - 3s 2ms/step - loss: 0.2698 - accuracy: 0.9002Epoch 7/101875/1875 [==============================] - 3s 2ms/step - loss: 0.2582 - accuracy: 0.9043Epoch 8/101875/1875 [==============================] - 3s 2ms/step - loss: 0.2495 - accuracy: 0.9074Epoch 9/101875/1875 [==============================] - 3s 2ms/step - loss: 0.2409 - accuracy: 0.9095Epoch 10/101875/1875 [==============================] - 4s 2ms/step - loss: 0.2324 - accuracy: 0.9137" }, { "code": null, "e": 6181, "s": 6004, "text": "We can see the loss and accuracy metrics displayed as the model is being trained. As the model trains, the loss decreases and accuracy increases. Kudos! Your model is learning!" }, { "code": null, "e": 6361, "s": 6181, "text": "The model has about 90% (0.90) accuracy on the training data. You may have values somewhere around 90% (not to worry if it is slightly different as it is prone to some randomness)" }, { "code": null, "e": 6531, "s": 6361, "text": "But that is not enough! We still haven’t tested the model. We will now test our model on our test data, which the model has never seen before! Let’s see how it performs." }, { "code": null, "e": 6611, "s": 6531, "text": "313/313 - 1s - loss: 0.3366 - accuracy: 0.8838Test accuracy: 0.8838000297546387" }, { "code": null, "e": 6894, "s": 6611, "text": "It turns out that the accuracy on the test dataset is a little less than the train dataset. This could mean that our model is over-fitting on our training data. We will not worry about that now. In future articles, we will discuss what causes over-fitting and how we can prevent it." }, { "code": null, "e": 7165, "s": 6894, "text": "Finally! We can now use our model to make predictions on images. Here we have a function to plot 100 random test images and their predicted labels. If a prediction result is different from the label provided in the test_labels dataset, we will highlight it in red color." }, { "code": null, "e": 7374, "s": 7165, "text": "Wow! You have done it! You have successfully created a model which can look at images of fashion apparels and classify them with a good certainty! When you think about it, all it took was a few lines of code." }, { "code": null, "e": 7452, "s": 7374, "text": "We see a few errors, but for our first model, things are looking pretty good!" }, { "code": null, "e": 7541, "s": 7452, "text": "The completed Colab Notebook is available here and the code is also available in GitHub." }, { "code": null, "e": 7803, "s": 7541, "text": "With this new knowledge of TensorFlow, Keras and machine learning in general, you would be able to create your own models for a wide variety of datasets. Moreover, the tools and techniques you learned here are the foundations of complex models used in practice." }, { "code": null, "e": 8031, "s": 7803, "text": "In the coming tutorials, we will take a look at Convolutional Neural Networks- a type of neural network used widely for computer vision applications. We will see that we can improve the accuracy of our model further using CNNs." }, { "code": null, "e": 8045, "s": 8031, "text": "Happy Coding!" } ]
Bayesian Hyper-Parameter Optimization: Neural Networks, TensorFlow, Facies Prediction Example | by Ryan A. Mardani | Towards Data Science
The purpose of this work is to optimize the neural network model hyper-parameters to estimate facies classes from well logs. I will include some codes in this paper but for a full jupyter notebook file, you can visit my Github. note: if you are new in TensorFlow, its installation elaborated by Jeff Heaton. In machine learning, model parameters can be divided into two main categories:1- Trainable parameters: such as weights in neural networks learned by training algorithms and the user does not interfere in the process,2- Hyper-parameters: users can set them before training operation such as learning rate or the number of dense layers in the model.Selecting the best hyper-parameters can be a tedious task if you try it by hand and it is almost impossible to find the best ones if you are dealing with more than two parameters.One way is to divide each parameter into a valid evenly range and then simply ask the computer to loop for the combination of parameters and calculate the results. The method is called Grid Search. Although it is done by machine, it will be a time-consuming process. Suppose you have 3 hyper-parameters with 10 possible values in each. In this approach, you will run 103 neural network models (even with reasonable training datasets size, this task is huge).Another way is a random search approach. In fact, instead of using organized parameter searching, it will go through a random combination of parameters and look for the optimized ones. You may estimate that chance of success decreases to zero for larger hyper-parameter tunings. Scikit-Optimize, skopt, which we will use here to the facies estimation task, is a simple and efficient library to minimize expensive noisy black-box functions. Bayesian optimization constructs another model of search-space for parameters. Gaussian Process is one kind of these models. This generates an estimate of how model performance varies with hyper-parameter changes. As we see in the picture, the true objective function(red dash line) is surrounded by noise (red shade). The red line shows how scikit optimize sampled the search space for hyper-parameters(one dimension). Scikit-optimize fills the area between sample points with the Gaussian process (green line) and estimates true real fitness value. In the areas with low samples or lack(like the left side of the picture between two red samples), there is great uncertainty (big difference between red and green lines causing big uncertainty green shade area such as two standard deviations uncertainty).In this process, then we ask a new set of hyper-parameter to explore more search space. In the initial steps, it goes with sparse accuracy but in later iterations, it focuses on where sampling points are more with the good agreement of fitness function with true objective function(trough area in the graph).For more study, you may refer to Scikit Optimize documentation. Data ReviewThe Council Grove gas reservoir is located in Kansas. From this carbonate reservoir, nine wells are available. Facies are studied from core samples in every half foot and matched with logging data in well location. Feature variables include five from wireline log measurements and two geologic constraining variables that are derived from geologic knowledge. For more detail refer here. For the dataset, you may download it from here. The seven variables are: GR: this wireline logging tools measure gamma emissionILD_log10: this is resistivity measurementPE: photoelectric effect logDeltaPHI: Phi is a porosity index in petrophysics.PNHIND: Average of neutron and density log.NM_M:nonmarine-marine indicatorRELPOS: relative position GR: this wireline logging tools measure gamma emission ILD_log10: this is resistivity measurement PE: photoelectric effect log DeltaPHI: Phi is a porosity index in petrophysics. PNHIND: Average of neutron and density log. NM_M:nonmarine-marine indicator RELPOS: relative position The nine discrete facies (classes of rocks) are: (SS) Nonmarine sandstone(CSiS) Nonmarine coarse siltstone(FSiS) Nonmarine fine siltstone(SiSH) Marine siltstone and shale(MS) Mudstone (limestone)(WS) Wackestone (limestone)(D) Dolomite(PS) Packstone-grainstone (limestone)(BS) Phylloid-algal bafflestone (limestone) (SS) Nonmarine sandstone (CSiS) Nonmarine coarse siltstone (FSiS) Nonmarine fine siltstone (SiSH) Marine siltstone and shale (MS) Mudstone (limestone) (WS) Wackestone (limestone) (D) Dolomite (PS) Packstone-grainstone (limestone) (BS) Phylloid-algal bafflestone (limestone) After reading the dataset into python, we can keep one well data as a blind set for future model performance examination. We also need to convert facies numbers into strings in the dataset. Refer to the full notebook. df = pd.read_csv(‘training_data.csv’)blind = df[df['Well Name'] == 'SHANKLE']training_data = df[df['Well Name'] != 'SHANKLE'] Feature EngineeringFacies classes should be converted to dummy variable in order to use in neural network: dummies = pd.get_dummies(training_data[‘FaciesLabels’]) Facies_cat = dummies.columns labels = dummies.values # target matirx# select predictors features = training_data.drop(['Facies', 'Formation', 'Well Name', 'Depth','FaciesLabels'], axis=1) As we are dealing with various range of data, to make network efficient, let’s normalize it. from sklearn import preprocessingscaler = preprocessing.StandardScaler().fit(features)scaled_features = scaler.transform(features)#Data splitfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( scaled_features, labels, test_size=0.2, random_state=42) In this work, we will predict facies from well logs using deep learning in Tensorflow. There several hyper-parameters that we may adjust for deep learning. I will try to find out the optimized parameters for: Learning rateNumber of dense layersNumber of nodes for each layerWhich activation function: ‘relu’ or sigmoid Learning rate Number of dense layers Number of nodes for each layer Which activation function: ‘relu’ or sigmoid To elaborate in this search dimension, we will use scikit-optimize(skopt) library. From skopt, real function will define our favorite range(lower bound = 1e-6, higher bound = 1e-1) for learning rate and will use logarithmic transformation. The search dimension for the number of layers (we look between 1 to 5) and each layer’s node amounts(between 5 to 512) can be implemented with Integer function of skopt. dim_learning_rate = Real(low=1e-6, high=1e-1, prior='log-uniform', name='learning_rate')dim_num_dense_layers = Integer(low=1, high=10, name='num_dense_layers')dim_num_dense_nodes = Integer(low=5, high=512, name='num_dense_nodes') For activation algorithms, we should use categorical function for optimization. dim_activation = Categorical(categories=['relu', 'sigmoid'], name='activation') Bring all search-dimensions into a single list: dimensions = [dim_learning_rate, dim_num_dense_layers, dim_num_dense_nodes, dim_activation] If you already worked with deep learning for a specific project and found your hyper-parameters by hand for that project, you know how hard it is to optimize. You may also use your own guess (like mine as default) to compare the results with the Bayesian tuning approach. default_parameters = [1e-5, 1, 16, ‘relu’] Like some examples developed by Tneseflow, we also need to define a model function first. After defining the type of model(Sequential here), we need to introduce the data dimension (data shape) in the first line. The number of layers and activation types are those two hyper-parameters that we are looking for to optimize. Softmax activation should be used for classification problems. Then another hyper-parameter is the learning rate which should be defined in the Adam function. The model should be compiled considering that loss function should be ‘categorical_crossentropy’ as we are dealing with the classification problems (facies prediction). def create_model(learning_rate, num_dense_layers, num_dense_nodes, activation): model = Sequential() model.add(InputLayer(input_shape=(scaled_features.shape[1]))) for i in range(num_dense_layers): name = 'layer_dense_{0}'.format(i+1) # add dense layer model.add(Dense(num_dense_nodes, activation=activation, name=name)) # use softmax-activation for classification. model.add(Dense(labels.shape[1], activation='softmax')) # Use the Adam method for training the network. optimizer = Adam(lr=learning_rate) #compile the model so it can be trained. model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) return model This function aims to create and train a network with given hyper-parameters and then evaluate model performance with the validation dataset. It returns fitness value, negative classification accuracy on the dataset. It is negative because skopt performs minimization rather than maximization. @use_named_args(dimensions=dimensions)def fitness(learning_rate, num_dense_layers, num_dense_nodes, activation): """ Hyper-parameters: learning_rate: Learning-rate for the optimizer. num_dense_layers: Number of dense layers. num_dense_nodes: Number of nodes in each dense layer. activation: Activation function for all layers. """ # Print the hyper-parameters. print('learning rate: {0:.1e}'.format(learning_rate)) print('num_dense_layers:', num_dense_layers) print('num_dense_nodes:', num_dense_nodes) print('activation:', activation) print() # Create the neural network with these hyper-parameters. model = create_model(learning_rate=learning_rate, num_dense_layers=num_dense_layers, num_dense_nodes=num_dense_nodes, activation=activation) # Dir-name for the TensorBoard log-files. log_dir = log_dir_name(learning_rate, num_dense_layers, num_dense_nodes, activation) # Create a callback-function for Keras which will be # run after each epoch has ended during training. # This saves the log-files for TensorBoard. # Note that there are complications when histogram_freq=1. # It might give strange errors and it also does not properly # support Keras data-generators for the validation-set. callback_log = TensorBoard( log_dir=log_dir, histogram_freq=0, write_graph=True, write_grads=False, write_images=False) # Use Keras to train the model. history = model.fit(x= X_train, y= y_train, epochs=3, batch_size=128, validation_data=validation_data, callbacks=[callback_log]) # Get the classification accuracy on the validation-set # after the last training-epoch. accuracy = history.history['val_accuracy'][-1] # Print the classification accuracy. print() print("Accuracy: {0:.2%}".format(accuracy)) print() # Save the model if it improves on the best-found performance. # We use the global keyword so we update the variable outside # of this function. global best_accuracy # If the classification accuracy of the saved model is improved ... if accuracy > best_accuracy: # Save the new model to harddisk. model.save(path_best_model) # Update the classification accuracy. best_accuracy = accuracy # Delete the Keras model with these hyper-parameters from memory. del model # Clear the Keras session, otherwise it will keep adding new # models to the same TensorFlow graph each time we create # a model with a different set of hyper-parameters. K.clear_session() # NOTE: Scikit-optimize does minimization so it tries to # find a set of hyper-parameters with the LOWEST fitness-value. # Because we are interested in the HIGHEST classification # accuracy, we need to negate this number so it can be minimized. return -accuracy# This function exactly comes from :Hvass-Labs, TensorFlow-Tutorials run this: fitness(x= default_parameters) We already checked the default hyper-parameter performance. Now we can examine Bayesian optimization from scikit-optimize library. Here we use 40 runs for fitness function, though it is an expensive operation and needs to used carefully with datasets. search_result = gp_minimize(func=fitness, dimensions=dimensions, acq_func='EI', # Expected Improvement. n_calls=40, x0=default_parameters) just some last runs shows below: Using plot_convergence function of skopt, we may see the optimization progress and the best fitness value found on y-axis. plot_convergence(search_result) # plt.savefig("Converge.png", dpi=400) Using the serach_result function, we can see the best hyper-parameter that Bayesian-optimizer generated. search_result.x Optimized hyper-parameters are in order: Learning rate, number of dense layers, number of nodes in each layer, and the best activation function. We can see all results for 40 calls with corresponding hyper-parameters and fitness values. sorted(zip(search_result.func_vals, search_result.x_iters)) An interesting point is that the ‘relu’ activation function is almost dominant. First, let’s look at 2D plot of two optimized parameters. Here we made landscape-plot of estimated fitness values for learning rate and number of nodes in each layer.The Bayesian optimizer builds a surrogate model of search space and searches inside this dimension rather than real search-space, that is why it is faster. In the plot, the yellow regions are better and blue regions are worse. Balck dots are the optimizer’s sampling location and the red star is the best parameter found. from skopt.plots import plot_objective_2Dfig = plot_objective_2D(result=search_result, dimension_identifier1='learning_rate', dimension_identifier2='num_dense_nodes', levels=50)# plt.savefig("Lr_numnods.png", dpi=400) Some points: The surrogate model can be inaccurate because it is built from only 40 samples of calls to the fitness functionThe plot may change in each time of optimization re-run because of random noise and training process in NNThis is 2D plot, while we optimized 4 parameters and could be imagined 4 dimensions. The surrogate model can be inaccurate because it is built from only 40 samples of calls to the fitness function The plot may change in each time of optimization re-run because of random noise and training process in NN This is 2D plot, while we optimized 4 parameters and could be imagined 4 dimensions. # create a list for plottingdim_names = ['learning_rate', 'num_dense_layers', 'num_dense_nodes', 'activation' ]fig, ax = plot_objective(result=search_result, dimensions=dim_names)plt.savefig("all_dimen.png", dpi=400) In these plots, we can see how the optimization happened. The Bayesian approach tries to fit model parameters with prior info at the points with a higher density of sampling. Gathering all four parameters into a scikit-optimization approach will introduce the best results in this run if the learning rate is about 0.003, the number of dense layers 6, the number of nodes in each layer about 327, and activation function is ‘relu’. The same steps of data preparation are required here as well. We skip repeating here. Now we can make a model with optimized parameters to see the prediction. opt_par = search_result.x# use hyper-parameters from optimization learning_rate = opt_par[0]num_layers = opt_par[1] num_nodes = opt_par[2] activation = opt_par[3] create model: import numpy as npimport tensorflow.kerasfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Activationfrom tensorflow.keras.callbacks import EarlyStoppingmodel = Sequential()model.add(InputLayer(input_shape=(scaled_features.shape[1])))model.add(Dense(num_nodes, activation=activation, kernel_initializer='random_normal'))model.add(Dense(labels.shape[1], activation='softmax', kernel_initializer='random_normal'))optimizer = Adam(lr=learning_rate) model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])monitor = EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=20, verbose=1, mode='auto', restore_best_weights=True)histories = model.fit(X_train,y_train, validation_data=(X_test,y_test), callbacks=[monitor],verbose=2,epochs=100) let’s see the model accuracy development: plt.plot(histories.history['accuracy'], 'bo')plt.plot(histories.history['val_accuracy'],'b' )plt.title('Training and validation accuracy')plt.ylabel('accuracy')plt.xlabel('epoch')plt.legend(['train', 'test'], loc='upper left')plt.savefig("accu.png", dpi=400)plt.show() Training and validation accuracy plot shows that almost after 80% accuracy (iteration 10), the model starts to overfit because we can not see improvement in test data prediction accuracy. Let’s evaluate model performance with a dataset that has not seen yet (blind well). We always predict that Machine Learning models will predict with blind data by less accuracy than training process if dataset is small or features are not big enough to cover all complexity of data dimensions. result = model.evaluate(scaled_features_blind, labels_blind)print("{0}: {1:.2%}".format(model.metrics_names[1], result[1])) y_pred = model.predict(scaled_features_blind) # result is probability arrayy_pred_idx = np.argmax(y_pred, axis=1) + 1# +1 becuase facies starts from 1 not zero like indexblind['Pred_Facies']= y_pred_idx function to plot: def compare_facies_plot(logs, compadre, facies_colors): #make sure logs are sorted by depth logs = logs.sort_values(by='Depth') cmap_facies = colors.ListedColormap( facies_colors[0:len(facies_colors)], 'indexed') ztop=logs.Depth.min(); zbot=logs.Depth.max() cluster1 = np.repeat(np.expand_dims(logs['Facies'].values,1), 100, 1) cluster2 = np.repeat(np.expand_dims(logs[compadre].values,1), 100, 1) f, ax = plt.subplots(nrows=1, ncols=7, figsize=(12, 6)) ax[0].plot(logs.GR, logs.Depth, '-g', alpha=0.8, lw = 0.9) ax[1].plot(logs.ILD_log10, logs.Depth, '-b', alpha=0.8, lw = 0.9) ax[2].plot(logs.DeltaPHI, logs.Depth, '-k', alpha=0.8, lw = 0.9) ax[3].plot(logs.PHIND, logs.Depth, '-r', alpha=0.8, lw = 0.9) ax[4].plot(logs.PE, logs.Depth, '-c', alpha=0.8, lw = 0.9) im1 = ax[5].imshow(cluster1, interpolation='none', aspect='auto', cmap=cmap_facies,vmin=1,vmax=9) im2 = ax[6].imshow(cluster2, interpolation='none', aspect='auto', cmap=cmap_facies,vmin=1,vmax=9) divider = make_axes_locatable(ax[6]) cax = divider.append_axes("right", size="20%", pad=0.05) cbar=plt.colorbar(im2, cax=cax) cbar.set_label((5*' ').join([' SS ', 'CSiS', 'FSiS', 'SiSh', ' MS ', ' WS ', ' D ', ' PS ', ' BS '])) cbar.set_ticks(range(0,1)); cbar.set_ticklabels('') for i in range(len(ax)-2): ax[i].set_ylim(ztop,zbot) ax[i].invert_yaxis() ax[i].grid() ax[i].locator_params(axis='x', nbins=3) ax[0].set_xlabel("GR") ax[0].set_xlim(logs.GR.min(),logs.GR.max()) ax[1].set_xlabel("ILD_log10") ax[1].set_xlim(logs.ILD_log10.min(),logs.ILD_log10.max()) ax[2].set_xlabel("DeltaPHI") ax[2].set_xlim(logs.DeltaPHI.min(),logs.DeltaPHI.max()) ax[3].set_xlabel("PHIND") ax[3].set_xlim(logs.PHIND.min(),logs.PHIND.max()) ax[4].set_xlabel("PE") ax[4].set_xlim(logs.PE.min(),logs.PE.max()) ax[5].set_xlabel('Facies') ax[6].set_xlabel(compadre) ax[1].set_yticklabels([]); ax[2].set_yticklabels([]); ax[3].set_yticklabels([]) ax[4].set_yticklabels([]); ax[5].set_yticklabels([]); ax[6].set_yticklabels([]) ax[5].set_xticklabels([]) ax[6].set_xticklabels([]) f.suptitle('Well: %s'%logs.iloc[0]['Well Name'], fontsize=14,y=0.94) Run: compare_facies_plot(blind, 'Pred_Facies', facies_colors)plt.savefig("Compo.png", dpi=400) In this work, we optimized hyper-parameters using a Bayesian approach with a scikit-learn library called skopt. This approach is superior to a random search and grid search, especially in complex datasets. Using this method, we can get rid of the hand-tuning of hyper-parameters for the neural networks, although in each run, you will face new parameters.
[ { "code": null, "e": 399, "s": 171, "text": "The purpose of this work is to optimize the neural network model hyper-parameters to estimate facies classes from well logs. I will include some codes in this paper but for a full jupyter notebook file, you can visit my Github." }, { "code": null, "e": 479, "s": 399, "text": "note: if you are new in TensorFlow, its installation elaborated by Jeff Heaton." }, { "code": null, "e": 1742, "s": 479, "text": "In machine learning, model parameters can be divided into two main categories:1- Trainable parameters: such as weights in neural networks learned by training algorithms and the user does not interfere in the process,2- Hyper-parameters: users can set them before training operation such as learning rate or the number of dense layers in the model.Selecting the best hyper-parameters can be a tedious task if you try it by hand and it is almost impossible to find the best ones if you are dealing with more than two parameters.One way is to divide each parameter into a valid evenly range and then simply ask the computer to loop for the combination of parameters and calculate the results. The method is called Grid Search. Although it is done by machine, it will be a time-consuming process. Suppose you have 3 hyper-parameters with 10 possible values in each. In this approach, you will run 103 neural network models (even with reasonable training datasets size, this task is huge).Another way is a random search approach. In fact, instead of using organized parameter searching, it will go through a random combination of parameters and look for the optimized ones. You may estimate that chance of success decreases to zero for larger hyper-parameter tunings." }, { "code": null, "e": 2117, "s": 1742, "text": "Scikit-Optimize, skopt, which we will use here to the facies estimation task, is a simple and efficient library to minimize expensive noisy black-box functions. Bayesian optimization constructs another model of search-space for parameters. Gaussian Process is one kind of these models. This generates an estimate of how model performance varies with hyper-parameter changes." }, { "code": null, "e": 3081, "s": 2117, "text": "As we see in the picture, the true objective function(red dash line) is surrounded by noise (red shade). The red line shows how scikit optimize sampled the search space for hyper-parameters(one dimension). Scikit-optimize fills the area between sample points with the Gaussian process (green line) and estimates true real fitness value. In the areas with low samples or lack(like the left side of the picture between two red samples), there is great uncertainty (big difference between red and green lines causing big uncertainty green shade area such as two standard deviations uncertainty).In this process, then we ask a new set of hyper-parameter to explore more search space. In the initial steps, it goes with sparse accuracy but in later iterations, it focuses on where sampling points are more with the good agreement of fitness function with true objective function(trough area in the graph).For more study, you may refer to Scikit Optimize documentation." }, { "code": null, "e": 3552, "s": 3081, "text": "Data ReviewThe Council Grove gas reservoir is located in Kansas. From this carbonate reservoir, nine wells are available. Facies are studied from core samples in every half foot and matched with logging data in well location. Feature variables include five from wireline log measurements and two geologic constraining variables that are derived from geologic knowledge. For more detail refer here. For the dataset, you may download it from here. The seven variables are:" }, { "code": null, "e": 3826, "s": 3552, "text": "GR: this wireline logging tools measure gamma emissionILD_log10: this is resistivity measurementPE: photoelectric effect logDeltaPHI: Phi is a porosity index in petrophysics.PNHIND: Average of neutron and density log.NM_M:nonmarine-marine indicatorRELPOS: relative position" }, { "code": null, "e": 3881, "s": 3826, "text": "GR: this wireline logging tools measure gamma emission" }, { "code": null, "e": 3924, "s": 3881, "text": "ILD_log10: this is resistivity measurement" }, { "code": null, "e": 3953, "s": 3924, "text": "PE: photoelectric effect log" }, { "code": null, "e": 4004, "s": 3953, "text": "DeltaPHI: Phi is a porosity index in petrophysics." }, { "code": null, "e": 4048, "s": 4004, "text": "PNHIND: Average of neutron and density log." }, { "code": null, "e": 4080, "s": 4048, "text": "NM_M:nonmarine-marine indicator" }, { "code": null, "e": 4106, "s": 4080, "text": "RELPOS: relative position" }, { "code": null, "e": 4155, "s": 4106, "text": "The nine discrete facies (classes of rocks) are:" }, { "code": null, "e": 4421, "s": 4155, "text": "(SS) Nonmarine sandstone(CSiS) Nonmarine coarse siltstone(FSiS) Nonmarine fine siltstone(SiSH) Marine siltstone and shale(MS) Mudstone (limestone)(WS) Wackestone (limestone)(D) Dolomite(PS) Packstone-grainstone (limestone)(BS) Phylloid-algal bafflestone (limestone)" }, { "code": null, "e": 4446, "s": 4421, "text": "(SS) Nonmarine sandstone" }, { "code": null, "e": 4480, "s": 4446, "text": "(CSiS) Nonmarine coarse siltstone" }, { "code": null, "e": 4512, "s": 4480, "text": "(FSiS) Nonmarine fine siltstone" }, { "code": null, "e": 4546, "s": 4512, "text": "(SiSH) Marine siltstone and shale" }, { "code": null, "e": 4572, "s": 4546, "text": "(MS) Mudstone (limestone)" }, { "code": null, "e": 4600, "s": 4572, "text": "(WS) Wackestone (limestone)" }, { "code": null, "e": 4613, "s": 4600, "text": "(D) Dolomite" }, { "code": null, "e": 4651, "s": 4613, "text": "(PS) Packstone-grainstone (limestone)" }, { "code": null, "e": 4695, "s": 4651, "text": "(BS) Phylloid-algal bafflestone (limestone)" }, { "code": null, "e": 4913, "s": 4695, "text": "After reading the dataset into python, we can keep one well data as a blind set for future model performance examination. We also need to convert facies numbers into strings in the dataset. Refer to the full notebook." }, { "code": null, "e": 5039, "s": 4913, "text": "df = pd.read_csv(‘training_data.csv’)blind = df[df['Well Name'] == 'SHANKLE']training_data = df[df['Well Name'] != 'SHANKLE']" }, { "code": null, "e": 5146, "s": 5039, "text": "Feature EngineeringFacies classes should be converted to dummy variable in order to use in neural network:" }, { "code": null, "e": 5440, "s": 5146, "text": "dummies = pd.get_dummies(training_data[‘FaciesLabels’]) Facies_cat = dummies.columns labels = dummies.values # target matirx# select predictors features = training_data.drop(['Facies', 'Formation', 'Well Name', 'Depth','FaciesLabels'], axis=1)" }, { "code": null, "e": 5533, "s": 5440, "text": "As we are dealing with various range of data, to make network efficient, let’s normalize it." }, { "code": null, "e": 5843, "s": 5533, "text": "from sklearn import preprocessingscaler = preprocessing.StandardScaler().fit(features)scaled_features = scaler.transform(features)#Data splitfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( scaled_features, labels, test_size=0.2, random_state=42)" }, { "code": null, "e": 6052, "s": 5843, "text": "In this work, we will predict facies from well logs using deep learning in Tensorflow. There several hyper-parameters that we may adjust for deep learning. I will try to find out the optimized parameters for:" }, { "code": null, "e": 6162, "s": 6052, "text": "Learning rateNumber of dense layersNumber of nodes for each layerWhich activation function: ‘relu’ or sigmoid" }, { "code": null, "e": 6176, "s": 6162, "text": "Learning rate" }, { "code": null, "e": 6199, "s": 6176, "text": "Number of dense layers" }, { "code": null, "e": 6230, "s": 6199, "text": "Number of nodes for each layer" }, { "code": null, "e": 6275, "s": 6230, "text": "Which activation function: ‘relu’ or sigmoid" }, { "code": null, "e": 6685, "s": 6275, "text": "To elaborate in this search dimension, we will use scikit-optimize(skopt) library. From skopt, real function will define our favorite range(lower bound = 1e-6, higher bound = 1e-1) for learning rate and will use logarithmic transformation. The search dimension for the number of layers (we look between 1 to 5) and each layer’s node amounts(between 5 to 512) can be implemented with Integer function of skopt." }, { "code": null, "e": 6939, "s": 6685, "text": "dim_learning_rate = Real(low=1e-6, high=1e-1, prior='log-uniform', name='learning_rate')dim_num_dense_layers = Integer(low=1, high=10, name='num_dense_layers')dim_num_dense_nodes = Integer(low=5, high=512, name='num_dense_nodes')" }, { "code": null, "e": 7019, "s": 6939, "text": "For activation algorithms, we should use categorical function for optimization." }, { "code": null, "e": 7127, "s": 7019, "text": "dim_activation = Categorical(categories=['relu', 'sigmoid'], name='activation')" }, { "code": null, "e": 7175, "s": 7127, "text": "Bring all search-dimensions into a single list:" }, { "code": null, "e": 7306, "s": 7175, "text": "dimensions = [dim_learning_rate, dim_num_dense_layers, dim_num_dense_nodes, dim_activation]" }, { "code": null, "e": 7578, "s": 7306, "text": "If you already worked with deep learning for a specific project and found your hyper-parameters by hand for that project, you know how hard it is to optimize. You may also use your own guess (like mine as default) to compare the results with the Bayesian tuning approach." }, { "code": null, "e": 7621, "s": 7578, "text": "default_parameters = [1e-5, 1, 16, ‘relu’]" }, { "code": null, "e": 8272, "s": 7621, "text": "Like some examples developed by Tneseflow, we also need to define a model function first. After defining the type of model(Sequential here), we need to introduce the data dimension (data shape) in the first line. The number of layers and activation types are those two hyper-parameters that we are looking for to optimize. Softmax activation should be used for classification problems. Then another hyper-parameter is the learning rate which should be defined in the Adam function. The model should be compiled considering that loss function should be ‘categorical_crossentropy’ as we are dealing with the classification problems (facies prediction)." }, { "code": null, "e": 9087, "s": 8272, "text": "def create_model(learning_rate, num_dense_layers, num_dense_nodes, activation): model = Sequential() model.add(InputLayer(input_shape=(scaled_features.shape[1]))) for i in range(num_dense_layers): name = 'layer_dense_{0}'.format(i+1) # add dense layer model.add(Dense(num_dense_nodes, activation=activation, name=name)) # use softmax-activation for classification. model.add(Dense(labels.shape[1], activation='softmax')) # Use the Adam method for training the network. optimizer = Adam(lr=learning_rate) #compile the model so it can be trained. model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) return model" }, { "code": null, "e": 9381, "s": 9087, "text": "This function aims to create and train a network with given hyper-parameters and then evaluate model performance with the validation dataset. It returns fitness value, negative classification accuracy on the dataset. It is negative because skopt performs minimization rather than maximization." }, { "code": null, "e": 12548, "s": 9381, "text": "@use_named_args(dimensions=dimensions)def fitness(learning_rate, num_dense_layers, num_dense_nodes, activation): \"\"\" Hyper-parameters: learning_rate: Learning-rate for the optimizer. num_dense_layers: Number of dense layers. num_dense_nodes: Number of nodes in each dense layer. activation: Activation function for all layers. \"\"\" # Print the hyper-parameters. print('learning rate: {0:.1e}'.format(learning_rate)) print('num_dense_layers:', num_dense_layers) print('num_dense_nodes:', num_dense_nodes) print('activation:', activation) print() # Create the neural network with these hyper-parameters. model = create_model(learning_rate=learning_rate, num_dense_layers=num_dense_layers, num_dense_nodes=num_dense_nodes, activation=activation) # Dir-name for the TensorBoard log-files. log_dir = log_dir_name(learning_rate, num_dense_layers, num_dense_nodes, activation) # Create a callback-function for Keras which will be # run after each epoch has ended during training. # This saves the log-files for TensorBoard. # Note that there are complications when histogram_freq=1. # It might give strange errors and it also does not properly # support Keras data-generators for the validation-set. callback_log = TensorBoard( log_dir=log_dir, histogram_freq=0, write_graph=True, write_grads=False, write_images=False) # Use Keras to train the model. history = model.fit(x= X_train, y= y_train, epochs=3, batch_size=128, validation_data=validation_data, callbacks=[callback_log]) # Get the classification accuracy on the validation-set # after the last training-epoch. accuracy = history.history['val_accuracy'][-1] # Print the classification accuracy. print() print(\"Accuracy: {0:.2%}\".format(accuracy)) print() # Save the model if it improves on the best-found performance. # We use the global keyword so we update the variable outside # of this function. global best_accuracy # If the classification accuracy of the saved model is improved ... if accuracy > best_accuracy: # Save the new model to harddisk. model.save(path_best_model) # Update the classification accuracy. best_accuracy = accuracy # Delete the Keras model with these hyper-parameters from memory. del model # Clear the Keras session, otherwise it will keep adding new # models to the same TensorFlow graph each time we create # a model with a different set of hyper-parameters. K.clear_session() # NOTE: Scikit-optimize does minimization so it tries to # find a set of hyper-parameters with the LOWEST fitness-value. # Because we are interested in the HIGHEST classification # accuracy, we need to negate this number so it can be minimized. return -accuracy# This function exactly comes from :Hvass-Labs, TensorFlow-Tutorials" }, { "code": null, "e": 12558, "s": 12548, "text": "run this:" }, { "code": null, "e": 12589, "s": 12558, "text": "fitness(x= default_parameters)" }, { "code": null, "e": 12841, "s": 12589, "text": "We already checked the default hyper-parameter performance. Now we can examine Bayesian optimization from scikit-optimize library. Here we use 40 runs for fitness function, though it is an expensive operation and needs to used carefully with datasets." }, { "code": null, "e": 13088, "s": 12841, "text": "search_result = gp_minimize(func=fitness, dimensions=dimensions, acq_func='EI', # Expected Improvement. n_calls=40, x0=default_parameters)" }, { "code": null, "e": 13121, "s": 13088, "text": "just some last runs shows below:" }, { "code": null, "e": 13244, "s": 13121, "text": "Using plot_convergence function of skopt, we may see the optimization progress and the best fitness value found on y-axis." }, { "code": null, "e": 13315, "s": 13244, "text": "plot_convergence(search_result) # plt.savefig(\"Converge.png\", dpi=400)" }, { "code": null, "e": 13420, "s": 13315, "text": "Using the serach_result function, we can see the best hyper-parameter that Bayesian-optimizer generated." }, { "code": null, "e": 13436, "s": 13420, "text": "search_result.x" }, { "code": null, "e": 13581, "s": 13436, "text": "Optimized hyper-parameters are in order: Learning rate, number of dense layers, number of nodes in each layer, and the best activation function." }, { "code": null, "e": 13673, "s": 13581, "text": "We can see all results for 40 calls with corresponding hyper-parameters and fitness values." }, { "code": null, "e": 13733, "s": 13673, "text": "sorted(zip(search_result.func_vals, search_result.x_iters))" }, { "code": null, "e": 13813, "s": 13733, "text": "An interesting point is that the ‘relu’ activation function is almost dominant." }, { "code": null, "e": 14301, "s": 13813, "text": "First, let’s look at 2D plot of two optimized parameters. Here we made landscape-plot of estimated fitness values for learning rate and number of nodes in each layer.The Bayesian optimizer builds a surrogate model of search space and searches inside this dimension rather than real search-space, that is why it is faster. In the plot, the yellow regions are better and blue regions are worse. Balck dots are the optimizer’s sampling location and the red star is the best parameter found." }, { "code": null, "e": 14588, "s": 14301, "text": "from skopt.plots import plot_objective_2Dfig = plot_objective_2D(result=search_result, dimension_identifier1='learning_rate', dimension_identifier2='num_dense_nodes', levels=50)# plt.savefig(\"Lr_numnods.png\", dpi=400)" }, { "code": null, "e": 14601, "s": 14588, "text": "Some points:" }, { "code": null, "e": 14903, "s": 14601, "text": "The surrogate model can be inaccurate because it is built from only 40 samples of calls to the fitness functionThe plot may change in each time of optimization re-run because of random noise and training process in NNThis is 2D plot, while we optimized 4 parameters and could be imagined 4 dimensions." }, { "code": null, "e": 15015, "s": 14903, "text": "The surrogate model can be inaccurate because it is built from only 40 samples of calls to the fitness function" }, { "code": null, "e": 15122, "s": 15015, "text": "The plot may change in each time of optimization re-run because of random noise and training process in NN" }, { "code": null, "e": 15207, "s": 15122, "text": "This is 2D plot, while we optimized 4 parameters and could be imagined 4 dimensions." }, { "code": null, "e": 15424, "s": 15207, "text": "# create a list for plottingdim_names = ['learning_rate', 'num_dense_layers', 'num_dense_nodes', 'activation' ]fig, ax = plot_objective(result=search_result, dimensions=dim_names)plt.savefig(\"all_dimen.png\", dpi=400)" }, { "code": null, "e": 15856, "s": 15424, "text": "In these plots, we can see how the optimization happened. The Bayesian approach tries to fit model parameters with prior info at the points with a higher density of sampling. Gathering all four parameters into a scikit-optimization approach will introduce the best results in this run if the learning rate is about 0.003, the number of dense layers 6, the number of nodes in each layer about 327, and activation function is ‘relu’." }, { "code": null, "e": 16015, "s": 15856, "text": "The same steps of data preparation are required here as well. We skip repeating here. Now we can make a model with optimized parameters to see the prediction." }, { "code": null, "e": 16178, "s": 16015, "text": "opt_par = search_result.x# use hyper-parameters from optimization learning_rate = opt_par[0]num_layers = opt_par[1] num_nodes = opt_par[2] activation = opt_par[3]" }, { "code": null, "e": 16192, "s": 16178, "text": "create model:" }, { "code": null, "e": 17040, "s": 16192, "text": "import numpy as npimport tensorflow.kerasfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Activationfrom tensorflow.keras.callbacks import EarlyStoppingmodel = Sequential()model.add(InputLayer(input_shape=(scaled_features.shape[1])))model.add(Dense(num_nodes, activation=activation, kernel_initializer='random_normal'))model.add(Dense(labels.shape[1], activation='softmax', kernel_initializer='random_normal'))optimizer = Adam(lr=learning_rate) model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])monitor = EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=20, verbose=1, mode='auto', restore_best_weights=True)histories = model.fit(X_train,y_train, validation_data=(X_test,y_test), callbacks=[monitor],verbose=2,epochs=100)" }, { "code": null, "e": 17082, "s": 17040, "text": "let’s see the model accuracy development:" }, { "code": null, "e": 17351, "s": 17082, "text": "plt.plot(histories.history['accuracy'], 'bo')plt.plot(histories.history['val_accuracy'],'b' )plt.title('Training and validation accuracy')plt.ylabel('accuracy')plt.xlabel('epoch')plt.legend(['train', 'test'], loc='upper left')plt.savefig(\"accu.png\", dpi=400)plt.show()" }, { "code": null, "e": 17539, "s": 17351, "text": "Training and validation accuracy plot shows that almost after 80% accuracy (iteration 10), the model starts to overfit because we can not see improvement in test data prediction accuracy." }, { "code": null, "e": 17833, "s": 17539, "text": "Let’s evaluate model performance with a dataset that has not seen yet (blind well). We always predict that Machine Learning models will predict with blind data by less accuracy than training process if dataset is small or features are not big enough to cover all complexity of data dimensions." }, { "code": null, "e": 17957, "s": 17833, "text": "result = model.evaluate(scaled_features_blind, labels_blind)print(\"{0}: {1:.2%}\".format(model.metrics_names[1], result[1]))" }, { "code": null, "e": 18160, "s": 17957, "text": "y_pred = model.predict(scaled_features_blind) # result is probability arrayy_pred_idx = np.argmax(y_pred, axis=1) + 1# +1 becuase facies starts from 1 not zero like indexblind['Pred_Facies']= y_pred_idx" }, { "code": null, "e": 18178, "s": 18160, "text": "function to plot:" }, { "code": null, "e": 20546, "s": 18178, "text": "def compare_facies_plot(logs, compadre, facies_colors): #make sure logs are sorted by depth logs = logs.sort_values(by='Depth') cmap_facies = colors.ListedColormap( facies_colors[0:len(facies_colors)], 'indexed') ztop=logs.Depth.min(); zbot=logs.Depth.max() cluster1 = np.repeat(np.expand_dims(logs['Facies'].values,1), 100, 1) cluster2 = np.repeat(np.expand_dims(logs[compadre].values,1), 100, 1) f, ax = plt.subplots(nrows=1, ncols=7, figsize=(12, 6)) ax[0].plot(logs.GR, logs.Depth, '-g', alpha=0.8, lw = 0.9) ax[1].plot(logs.ILD_log10, logs.Depth, '-b', alpha=0.8, lw = 0.9) ax[2].plot(logs.DeltaPHI, logs.Depth, '-k', alpha=0.8, lw = 0.9) ax[3].plot(logs.PHIND, logs.Depth, '-r', alpha=0.8, lw = 0.9) ax[4].plot(logs.PE, logs.Depth, '-c', alpha=0.8, lw = 0.9) im1 = ax[5].imshow(cluster1, interpolation='none', aspect='auto', cmap=cmap_facies,vmin=1,vmax=9) im2 = ax[6].imshow(cluster2, interpolation='none', aspect='auto', cmap=cmap_facies,vmin=1,vmax=9) divider = make_axes_locatable(ax[6]) cax = divider.append_axes(\"right\", size=\"20%\", pad=0.05) cbar=plt.colorbar(im2, cax=cax) cbar.set_label((5*' ').join([' SS ', 'CSiS', 'FSiS', 'SiSh', ' MS ', ' WS ', ' D ', ' PS ', ' BS '])) cbar.set_ticks(range(0,1)); cbar.set_ticklabels('') for i in range(len(ax)-2): ax[i].set_ylim(ztop,zbot) ax[i].invert_yaxis() ax[i].grid() ax[i].locator_params(axis='x', nbins=3) ax[0].set_xlabel(\"GR\") ax[0].set_xlim(logs.GR.min(),logs.GR.max()) ax[1].set_xlabel(\"ILD_log10\") ax[1].set_xlim(logs.ILD_log10.min(),logs.ILD_log10.max()) ax[2].set_xlabel(\"DeltaPHI\") ax[2].set_xlim(logs.DeltaPHI.min(),logs.DeltaPHI.max()) ax[3].set_xlabel(\"PHIND\") ax[3].set_xlim(logs.PHIND.min(),logs.PHIND.max()) ax[4].set_xlabel(\"PE\") ax[4].set_xlim(logs.PE.min(),logs.PE.max()) ax[5].set_xlabel('Facies') ax[6].set_xlabel(compadre) ax[1].set_yticklabels([]); ax[2].set_yticklabels([]); ax[3].set_yticklabels([]) ax[4].set_yticklabels([]); ax[5].set_yticklabels([]); ax[6].set_yticklabels([]) ax[5].set_xticklabels([]) ax[6].set_xticklabels([]) f.suptitle('Well: %s'%logs.iloc[0]['Well Name'], fontsize=14,y=0.94)" }, { "code": null, "e": 20551, "s": 20546, "text": "Run:" }, { "code": null, "e": 20641, "s": 20551, "text": "compare_facies_plot(blind, 'Pred_Facies', facies_colors)plt.savefig(\"Compo.png\", dpi=400)" } ]
TELNET and SSH on Adaptive Security Appliance (ASA) - GeeksforGeeks
22 Nov, 2021 Prerequisite – Adaptive security appliance (ASA) A user can take management access of a device through a console or remote access by using telnet or SSH. In the same way, ASA (Adaptive Security Appliance) CLI access can take through a console or by using Telnet or SSH and GUI access can be taken through (ASDM-a tool). 1. Telnet on ASA: Telnet is an application layer protocol that uses TCP port number 23. It is used to remote access a device but it is less used as it is less secure. The packets exchanged between the client and the server are in cleartext. If we want to configure Telnet on ASA, 3 steps have to be followed. Enable Telnet services – By default, a login password is configured on ASA as “cisco”. If we want to change it, use the command. asa(config)#password GeeksforGeeks Or by using command asa(config)#passwd GeeksforGeeks Where GeeksforGeeks is the password we have set. Assign IP addresses who can initiate Telnet connection – In the router, if we have enabled telnet services and not applied any ACL, any IP address can make a telnet connection to the router but in ASA, we have to assign the IP address that can make use of telnet services of ASA. It can be done by the command: asa(config)#telnet {source_IP_address} {subnet_ask} {source_interface} Here, we have to first mention the {source_IP_address} by which ASA can accept telnet connection. Of course, it can be one IP address or a whole network. Then the subnet mask of {source_IP_address}. Then, we have to mention {source_interface}. It is the interface of ASA through which ASA will be expecting a telnet connection. Set telnet timeout – It is the time for which the telnet session can be idle before the ASA terminates the session. It can range from 1 to 2440 minutes. The default timeout is 5 minutes. The command used for it is: asa(config)#telnet timeout {minutes} Limitations – The ASA, having more than one interface Configured, doesn’t allow telnet from the interface having the lowest security level. Configuration example – Here, is a small topology in which three routers namely Router1 (IP address-10.1.1.1/24),Router2 (IP address-10.1.2.1/24),Router3 (IP address-10.1.3.1/24) is connected to ASA (IP address-10.1.1.2/24 on INSIDE interface and security level – 100, IP address-10.1.2.2/24 on OUTSIDE interface and security level – 0,10.1.3.2/24 on DMZ and security level – 50). In this task, we will allow telnet on all interfaces (INSIDE, OUTSIDE, DMZ) from Router1 (10.1.1.1/24), Router2 (10.1.2.1/24), and Router3 (10.1.3.1/24) respectively. Assuming that the IP addressing has already been done on all routers and ASA. Now, enabling telnet for all the router’s IP addresses on ASA and giving passwords as GeeksforGeeks. asa(config)#password GeeksforGeeks asa(config)#telnet 10.1.1.1 255.255.255.255 INSIDE asa(config)#telnet timeout 10 asa(config)#telnet 10.1.2.1 255.255.255.255 OUTSIDE asa(config)#telnet timeout 10 asa(config)#telnet 10.1.3.1 255.255.255.255 DMZ asa(config)#telnet timeout 10 And telnet ASA by using command Router#telnet {ASA_interface_IP_address} Example – Router1#telnet 10.1.1.2 Similarly, on Router2 and Router3. Now, in this scenario, Router1 and Router3 will be able to telnet ASA but Router2 will not be able to telnet because the ASA interface (OUTSIDE) has the lowest security level. Note – If we want to use the local database of the ASA then first we have to create a local database by command. asa(config)#username Cisco password GeeksforGeeks And then force the ASA to use the local database for login by the command. asa(config)#aaa authentication telnet console LOCAL Note that LOCAL is case-sensitive. 2. SSH on ASA: SSH is an application layer protocol used to take remote access to a device. It uses TCP port number 22 and is more secured than Telnet as its packets are encrypted. SSH is also configured in the same way as telnet but commands are different. To enable SSH on ASA, there are 2 steps: Enable SSH services – To enable SSH on ASA first generate the crypto key by command. asa(config)#crypto key generate rsa modulus {modulus_value} After generating the crypto key, create a local database on ASA by command. asa(config)#username cisco password GeeksforGeeks Where cisco is username and password is GeeksforGeeks. Tell IP addresses of devices which can access ssh on ASA – Just like in Telnet, we have to allow some IP addresses that are allowed to access ASA through ssh. It can be done by command:- asa(config)#ssh {source_IP_address} {subnet_ask} {source_interface} Here, we have to first mention the {source_IP_address} by which ASA can accept ssh connection. Then the subnet mask of {source_IP_address}. Then, we have to mention {source_interface}. It is the interface of ASA through which ASA will be expecting ssh traffic. Set SSH timeout – It is the time for which the ssh session can be idle before the ASA terminates the session. It can range from 1 to 2440 minutes. The default timeout is 5 minutes. The command used for it is: asa(config)#ssh timeout {minutes} If we want to use a local database for ssh login then use a command asa(config)#aaa authentication ssh console LOCAL Configuration example – Using the same topology in which three routers namely Router1 (IP address-10.1.1.1/24),Router2 (IP address-10.1.2.1/24),Router3 (IP address-10.1.3.1/24) is connected to ASA (IP address-10.1.1.2/24 on INSIDE interface and security level – 100, IP address-10.1.2.2/24 on OUTSIDE interface and security level – 0,10.1.3.2/24 on DMZ and security level – 50). In this task, we will allow ssh on all interfaces (INSIDE, DMZ) from Router1 (10.1.1.1/24) and Router3 (10.1.3.1/24) respectively. Assuming that the IP addressing has already been done on all routers and ASA. Now, enabling ssh for all the router’s IP addresses on ASA and giving username as Saurabh and password as GeeksforGeeks. asa(config)#crypto key generate rsa modulus 1024 asa(config)#username saurabh password GeeksforGeeks asa(config)#aaa authentication ssh console LOCAL asa(config)#ssh 10.1.1.1 255.255.255.255 INSIDE asa(config)#ssh timeout 10 asa(config)#ssh 10.1.3.1 255.255.255.255 DMZ asa(config)#telnet timeout 10 And SSH, ASA from Router1 by using a command. Router1#ssh -l saurabh 10.1.1.2 SSH, ASA from Router2 by using a command. Router3#ssh -l saurabh 10.1.3.2 Both will be able to ssh ASA and there are no restrictions with ASA like there are, using with telnet. ManasChhabra2 tanwarsinghvaibhav Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Differences between IPv4 and IPv6 Socket Programming in Java Advanced Encryption Standard (AES) Implementation of Diffie-Hellman Algorithm Distance Vector Routing (DVR) Protocol Introduction of Classful IP Addressing Simple Chat Room using Python Active and Passive attacks in Information Security Cryptography and its Types Transmission Modes in Computer Networks (Simplex, Half-Duplex and Full-Duplex)
[ { "code": null, "e": 24309, "s": 24281, "text": "\n22 Nov, 2021" }, { "code": null, "e": 24630, "s": 24309, "text": "Prerequisite – Adaptive security appliance (ASA) A user can take management access of a device through a console or remote access by using telnet or SSH. In the same way, ASA (Adaptive Security Appliance) CLI access can take through a console or by using Telnet or SSH and GUI access can be taken through (ASDM-a tool). " }, { "code": null, "e": 24940, "s": 24630, "text": "1. Telnet on ASA: Telnet is an application layer protocol that uses TCP port number 23. It is used to remote access a device but it is less used as it is less secure. The packets exchanged between the client and the server are in cleartext. If we want to configure Telnet on ASA, 3 steps have to be followed. " }, { "code": null, "e": 25070, "s": 24940, "text": "Enable Telnet services – By default, a login password is configured on ASA as “cisco”. If we want to change it, use the command. " }, { "code": null, "e": 25106, "s": 25070, "text": "asa(config)#password GeeksforGeeks " }, { "code": null, "e": 25127, "s": 25106, "text": "Or by using command " }, { "code": null, "e": 25161, "s": 25127, "text": "asa(config)#passwd GeeksforGeeks " }, { "code": null, "e": 25211, "s": 25161, "text": "Where GeeksforGeeks is the password we have set. " }, { "code": null, "e": 25523, "s": 25211, "text": "Assign IP addresses who can initiate Telnet connection – In the router, if we have enabled telnet services and not applied any ACL, any IP address can make a telnet connection to the router but in ASA, we have to assign the IP address that can make use of telnet services of ASA. It can be done by the command: " }, { "code": null, "e": 25598, "s": 25523, "text": "asa(config)#telnet {source_IP_address} {subnet_ask} {source_interface} " }, { "code": null, "e": 25927, "s": 25598, "text": "Here, we have to first mention the {source_IP_address} by which ASA can accept telnet connection. Of course, it can be one IP address or a whole network. Then the subnet mask of {source_IP_address}. Then, we have to mention {source_interface}. It is the interface of ASA through which ASA will be expecting a telnet connection. " }, { "code": null, "e": 26143, "s": 25927, "text": "Set telnet timeout – It is the time for which the telnet session can be idle before the ASA terminates the session. It can range from 1 to 2440 minutes. The default timeout is 5 minutes. The command used for it is: " }, { "code": null, "e": 26181, "s": 26143, "text": "asa(config)#telnet timeout {minutes} " }, { "code": null, "e": 26322, "s": 26181, "text": "Limitations – The ASA, having more than one interface Configured, doesn’t allow telnet from the interface having the lowest security level. " }, { "code": null, "e": 26348, "s": 26322, "text": "Configuration example – " }, { "code": null, "e": 26706, "s": 26348, "text": "Here, is a small topology in which three routers namely Router1 (IP address-10.1.1.1/24),Router2 (IP address-10.1.2.1/24),Router3 (IP address-10.1.3.1/24) is connected to ASA (IP address-10.1.1.2/24 on INSIDE interface and security level – 100, IP address-10.1.2.2/24 on OUTSIDE interface and security level – 0,10.1.3.2/24 on DMZ and security level – 50). " }, { "code": null, "e": 27053, "s": 26706, "text": "In this task, we will allow telnet on all interfaces (INSIDE, OUTSIDE, DMZ) from Router1 (10.1.1.1/24), Router2 (10.1.2.1/24), and Router3 (10.1.3.1/24) respectively. Assuming that the IP addressing has already been done on all routers and ASA. Now, enabling telnet for all the router’s IP addresses on ASA and giving passwords as GeeksforGeeks. " }, { "code": null, "e": 27329, "s": 27053, "text": "asa(config)#password GeeksforGeeks\nasa(config)#telnet 10.1.1.1 255.255.255.255 INSIDE\nasa(config)#telnet timeout 10\nasa(config)#telnet 10.1.2.1 255.255.255.255 OUTSIDE\nasa(config)#telnet timeout 10\nasa(config)#telnet 10.1.3.1 255.255.255.255 DMZ\nasa(config)#telnet timeout 10" }, { "code": null, "e": 27363, "s": 27329, "text": "And telnet ASA by using command " }, { "code": null, "e": 27405, "s": 27363, "text": "Router#telnet {ASA_interface_IP_address} " }, { "code": null, "e": 27417, "s": 27405, "text": "Example – " }, { "code": null, "e": 27441, "s": 27417, "text": "Router1#telnet 10.1.1.2" }, { "code": null, "e": 27653, "s": 27441, "text": "Similarly, on Router2 and Router3. Now, in this scenario, Router1 and Router3 will be able to telnet ASA but Router2 will not be able to telnet because the ASA interface (OUTSIDE) has the lowest security level. " }, { "code": null, "e": 27767, "s": 27653, "text": "Note – If we want to use the local database of the ASA then first we have to create a local database by command. " }, { "code": null, "e": 27818, "s": 27767, "text": "asa(config)#username Cisco password GeeksforGeeks " }, { "code": null, "e": 27895, "s": 27818, "text": "And then force the ASA to use the local database for login by the command. " }, { "code": null, "e": 27947, "s": 27895, "text": "asa(config)#aaa authentication telnet console LOCAL" }, { "code": null, "e": 27983, "s": 27947, "text": "Note that LOCAL is case-sensitive. " }, { "code": null, "e": 28242, "s": 27983, "text": "2. SSH on ASA: SSH is an application layer protocol used to take remote access to a device. It uses TCP port number 22 and is more secured than Telnet as its packets are encrypted. SSH is also configured in the same way as telnet but commands are different. " }, { "code": null, "e": 28284, "s": 28242, "text": "To enable SSH on ASA, there are 2 steps: " }, { "code": null, "e": 28370, "s": 28284, "text": "Enable SSH services – To enable SSH on ASA first generate the crypto key by command. " }, { "code": null, "e": 28431, "s": 28370, "text": "asa(config)#crypto key generate rsa modulus {modulus_value} " }, { "code": null, "e": 28508, "s": 28431, "text": "After generating the crypto key, create a local database on ASA by command. " }, { "code": null, "e": 28559, "s": 28508, "text": "asa(config)#username cisco password GeeksforGeeks " }, { "code": null, "e": 28615, "s": 28559, "text": "Where cisco is username and password is GeeksforGeeks. " }, { "code": null, "e": 28803, "s": 28615, "text": "Tell IP addresses of devices which can access ssh on ASA – Just like in Telnet, we have to allow some IP addresses that are allowed to access ASA through ssh. It can be done by command:- " }, { "code": null, "e": 28874, "s": 28803, "text": "asa(config)#ssh {source_IP_address} {subnet_ask} {source_interface} " }, { "code": null, "e": 29136, "s": 28874, "text": "Here, we have to first mention the {source_IP_address} by which ASA can accept ssh connection. Then the subnet mask of {source_IP_address}. Then, we have to mention {source_interface}. It is the interface of ASA through which ASA will be expecting ssh traffic. " }, { "code": null, "e": 29346, "s": 29136, "text": "Set SSH timeout – It is the time for which the ssh session can be idle before the ASA terminates the session. It can range from 1 to 2440 minutes. The default timeout is 5 minutes. The command used for it is: " }, { "code": null, "e": 29381, "s": 29346, "text": "asa(config)#ssh timeout {minutes} " }, { "code": null, "e": 29450, "s": 29381, "text": "If we want to use a local database for ssh login then use a command " }, { "code": null, "e": 29499, "s": 29450, "text": "asa(config)#aaa authentication ssh console LOCAL" }, { "code": null, "e": 29525, "s": 29499, "text": "Configuration example – " }, { "code": null, "e": 29881, "s": 29525, "text": "Using the same topology in which three routers namely Router1 (IP address-10.1.1.1/24),Router2 (IP address-10.1.2.1/24),Router3 (IP address-10.1.3.1/24) is connected to ASA (IP address-10.1.1.2/24 on INSIDE interface and security level – 100, IP address-10.1.2.2/24 on OUTSIDE interface and security level – 0,10.1.3.2/24 on DMZ and security level – 50). " }, { "code": null, "e": 30212, "s": 29881, "text": "In this task, we will allow ssh on all interfaces (INSIDE, DMZ) from Router1 (10.1.1.1/24) and Router3 (10.1.3.1/24) respectively. Assuming that the IP addressing has already been done on all routers and ASA. Now, enabling ssh for all the router’s IP addresses on ASA and giving username as Saurabh and password as GeeksforGeeks. " }, { "code": null, "e": 30514, "s": 30212, "text": "asa(config)#crypto key generate rsa modulus 1024\nasa(config)#username saurabh password GeeksforGeeks \nasa(config)#aaa authentication ssh console LOCAL \nasa(config)#ssh 10.1.1.1 255.255.255.255 INSIDE\nasa(config)#ssh timeout 10\nasa(config)#ssh 10.1.3.1 255.255.255.255 DMZ\nasa(config)#telnet timeout 10" }, { "code": null, "e": 30562, "s": 30514, "text": "And SSH, ASA from Router1 by using a command. " }, { "code": null, "e": 30595, "s": 30562, "text": "Router1#ssh -l saurabh 10.1.1.2 " }, { "code": null, "e": 30639, "s": 30595, "text": "SSH, ASA from Router2 by using a command. " }, { "code": null, "e": 30672, "s": 30639, "text": "Router3#ssh -l saurabh 10.1.3.2 " }, { "code": null, "e": 30777, "s": 30672, "text": "Both will be able to ssh ASA and there are no restrictions with ASA like there are, using with telnet. " }, { "code": null, "e": 30791, "s": 30777, "text": "ManasChhabra2" }, { "code": null, "e": 30810, "s": 30791, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 30828, "s": 30810, "text": "Computer Networks" }, { "code": null, "e": 30846, "s": 30828, "text": "Computer Networks" }, { "code": null, "e": 30944, "s": 30846, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30953, "s": 30944, "text": "Comments" }, { "code": null, "e": 30966, "s": 30953, "text": "Old Comments" }, { "code": null, "e": 31000, "s": 30966, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 31027, "s": 31000, "text": "Socket Programming in Java" }, { "code": null, "e": 31062, "s": 31027, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 31105, "s": 31062, "text": "Implementation of Diffie-Hellman Algorithm" }, { "code": null, "e": 31144, "s": 31105, "text": "Distance Vector Routing (DVR) Protocol" }, { "code": null, "e": 31183, "s": 31144, "text": "Introduction of Classful IP Addressing" }, { "code": null, "e": 31213, "s": 31183, "text": "Simple Chat Room using Python" }, { "code": null, "e": 31264, "s": 31213, "text": "Active and Passive attacks in Information Security" }, { "code": null, "e": 31291, "s": 31264, "text": "Cryptography and its Types" } ]
How to Install Golang in VScode? - GeeksforGeeks
30 Sep, 2021 GO is a compiled programming language developed by Robert Griesemer, Rob Pike, and Ken Thompson at Google. It was introduced in 2009 and is also known as golang. In this article, we are going to see how you can set up Visual Code Studio for Go language Development. We are going to install the necessary tools for it. GO language in Windows Visual Studio Code GO Extension for Visual Studio Code First Navigate to this link, it will redirect you to the official download page of GO Language. Click the Download button to download the installer for Windows. After downloading the installer, start the installation. It will install GO language in your Windows system easily. You can check the version of the language by typing the following command in the terminal. go version GOPATH is an Environment variable and it specifies the root of your Go Workspace. By default, the workspace is located at %USERPROFILE%/go for Windows. Configure GOPATH: Create a folder called “C:\Projects\Go” in your C drive. Press win(Windows) + r to open the run dialog. Press win + r for run dialog Type sysdm.cpl ,3 in the dialog box and click Ok. It will open the following Window of system properties. Click the Environment Variables button at the bottom. Now, in the System Variables section, click on the New button Set the variable name as GOPATH and its value as C:\Projects\Go and then hit OK. Now you have successfully configured GOPATH for your Windows system. If you want to check, just open the run dialog by pressing win + r and type %GOPATH%, if it takes you to the root directory that we have set(C:\Projects\Go) then the configuration was successful. Visual Studio Code is a lightweight but Powerful IDE & Code editor for Windows, macOS, and Linux. Follow these steps to install Visual Studio Code; First, Navigate to this URL. Click Download VS Code for Your Operating system. You can easily install it on Windows, Mac or Linux. After installation, open VS code and click on the Extension manager button in the left side panel, you can also do it by pressing Ctrl + Shift + x. In the Search panel simply type Go or golang. Now in the search results, you will see the GO extension by the GO team at Google, open it and hit the install button. Let the installation process finish. GO Extension After this, press Ctrl + Shift + p to open the command palette and run the following command – Go: Install/Update Tools You will see the list of tools to install, select everything, and hit Install Now you can start developing in Golang. how-to-install Picked How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Set Git Username and Password in GitBash? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS? How to Check the OS Version in Linux? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS?
[ { "code": null, "e": 24952, "s": 24924, "text": "\n30 Sep, 2021" }, { "code": null, "e": 25271, "s": 24952, "text": "GO is a compiled programming language developed by Robert Griesemer, Rob Pike, and Ken Thompson at Google. It was introduced in 2009 and is also known as golang. In this article, we are going to see how you can set up Visual Code Studio for Go language Development. We are going to install the necessary tools for it." }, { "code": null, "e": 25294, "s": 25271, "text": "GO language in Windows" }, { "code": null, "e": 25313, "s": 25294, "text": "Visual Studio Code" }, { "code": null, "e": 25349, "s": 25313, "text": "GO Extension for Visual Studio Code" }, { "code": null, "e": 25447, "s": 25351, "text": "First Navigate to this link, it will redirect you to the official download page of GO Language." }, { "code": null, "e": 25512, "s": 25447, "text": "Click the Download button to download the installer for Windows." }, { "code": null, "e": 25721, "s": 25514, "text": "After downloading the installer, start the installation. It will install GO language in your Windows system easily. You can check the version of the language by typing the following command in the terminal." }, { "code": null, "e": 25732, "s": 25721, "text": "go version" }, { "code": null, "e": 25884, "s": 25732, "text": "GOPATH is an Environment variable and it specifies the root of your Go Workspace. By default, the workspace is located at %USERPROFILE%/go for Windows." }, { "code": null, "e": 25902, "s": 25884, "text": "Configure GOPATH:" }, { "code": null, "e": 25959, "s": 25902, "text": "Create a folder called “C:\\Projects\\Go” in your C drive." }, { "code": null, "e": 26006, "s": 25959, "text": "Press win(Windows) + r to open the run dialog." }, { "code": null, "e": 26035, "s": 26006, "text": "Press win + r for run dialog" }, { "code": null, "e": 26085, "s": 26035, "text": "Type sysdm.cpl ,3 in the dialog box and click Ok." }, { "code": null, "e": 26195, "s": 26085, "text": "It will open the following Window of system properties. Click the Environment Variables button at the bottom." }, { "code": null, "e": 26257, "s": 26195, "text": "Now, in the System Variables section, click on the New button" }, { "code": null, "e": 26338, "s": 26257, "text": "Set the variable name as GOPATH and its value as C:\\Projects\\Go and then hit OK." }, { "code": null, "e": 26603, "s": 26338, "text": "Now you have successfully configured GOPATH for your Windows system. If you want to check, just open the run dialog by pressing win + r and type %GOPATH%, if it takes you to the root directory that we have set(C:\\Projects\\Go) then the configuration was successful." }, { "code": null, "e": 26753, "s": 26605, "text": "Visual Studio Code is a lightweight but Powerful IDE & Code editor for Windows, macOS, and Linux. Follow these steps to install Visual Studio Code;" }, { "code": null, "e": 26782, "s": 26753, "text": "First, Navigate to this URL." }, { "code": null, "e": 26884, "s": 26782, "text": "Click Download VS Code for Your Operating system. You can easily install it on Windows, Mac or Linux." }, { "code": null, "e": 27034, "s": 26886, "text": "After installation, open VS code and click on the Extension manager button in the left side panel, you can also do it by pressing Ctrl + Shift + x." }, { "code": null, "e": 27080, "s": 27034, "text": "In the Search panel simply type Go or golang." }, { "code": null, "e": 27236, "s": 27080, "text": "Now in the search results, you will see the GO extension by the GO team at Google, open it and hit the install button. Let the installation process finish." }, { "code": null, "e": 27249, "s": 27236, "text": "GO Extension" }, { "code": null, "e": 27344, "s": 27249, "text": "After this, press Ctrl + Shift + p to open the command palette and run the following command –" }, { "code": null, "e": 27369, "s": 27344, "text": "Go: Install/Update Tools" }, { "code": null, "e": 27447, "s": 27369, "text": "You will see the list of tools to install, select everything, and hit Install" }, { "code": null, "e": 27487, "s": 27447, "text": "Now you can start developing in Golang." }, { "code": null, "e": 27502, "s": 27487, "text": "how-to-install" }, { "code": null, "e": 27509, "s": 27502, "text": "Picked" }, { "code": null, "e": 27516, "s": 27509, "text": "How To" }, { "code": null, "e": 27535, "s": 27516, "text": "Installation Guide" }, { "code": null, "e": 27633, "s": 27535, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27667, "s": 27633, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 27716, "s": 27667, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 27774, "s": 27716, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 27816, "s": 27774, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 27854, "s": 27816, "text": "How to Check the OS Version in Linux?" }, { "code": null, "e": 27887, "s": 27854, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27921, "s": 27887, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 27956, "s": 27921, "text": "How to Install Pygame on Windows ?" }, { "code": null, "e": 28014, "s": 27956, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" } ]
Simple Substitution Cipher
Simple substitution cipher is the most commonly used cipher and includes an algorithm of substituting every plain text character for every cipher text character. In this process, alphabets are jumbled in comparison with Caesar cipher algorithm. Keys for a simple substitution cipher usually consists of 26 letters. An example key is − plain alphabet : abcdefghijklmnopqrstuvwxyz cipher alphabet: phqgiumeaylnofdxjkrcvstzwb An example encryption using the above key is− plaintext : defend the east wall of the castle ciphertext: giuifg cei iprc tpnn du cei qprcni The following code shows a program to implement simple substitution cipher − import random, sys LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def main(): message = '' if len(sys.argv) > 1: with open(sys.argv[1], 'r') as f: message = f.read() else: message = raw_input("Enter your message: ") mode = raw_input("E for Encrypt, D for Decrypt: ") key = '' while checkKey(key) is False: key = raw_input("Enter 26 ALPHA key (leave blank for random key): ") if key == '': key = getRandomKey() if checkKey(key) is False: print('There is an error in the key or symbol set.') translated = translateMessage(message, key, mode) print('Using key: %s' % (key)) if len(sys.argv) > 1: fileOut = 'enc.' + sys.argv[1] with open(fileOut, 'w') as f: f.write(translated) print('Success! File written to: %s' % (fileOut)) else: print('Result: ' + translated) # Store the key into list, sort it, convert back, compare to alphabet. def checkKey(key): keyString = ''.join(sorted(list(key))) return keyString == LETTERS def translateMessage(message, key, mode): translated = '' charsA = LETTERS charsB = key # If decrypt mode is detected, swap A and B if mode == 'D': charsA, charsB = charsB, charsA for symbol in message: if symbol.upper() in charsA: symIndex = charsA.find(symbol.upper()) if symbol.isupper(): translated += charsB[symIndex].upper() else: translated += charsB[symIndex].lower() else: translated += symbol return translated def getRandomKey(): randomList = list(LETTERS) random.shuffle(randomList) return ''.join(randomList) if __name__ == '__main__': main() You can observe the following output when you implement the code given above − 10 Lectures 2 hours Total Seminars 10 Lectures 2 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2537, "s": 2292, "text": "Simple substitution cipher is the most commonly used cipher and includes an algorithm of substituting every plain text character for every cipher text character. In this process, alphabets are jumbled in comparison with Caesar cipher algorithm." }, { "code": null, "e": 2627, "s": 2537, "text": "Keys for a simple substitution cipher usually consists of 26 letters. An example key is −" }, { "code": null, "e": 2716, "s": 2627, "text": "plain alphabet : abcdefghijklmnopqrstuvwxyz\ncipher alphabet: phqgiumeaylnofdxjkrcvstzwb\n" }, { "code": null, "e": 2762, "s": 2716, "text": "An example encryption using the above key is−" }, { "code": null, "e": 2857, "s": 2762, "text": "plaintext : defend the east wall of the castle\nciphertext: giuifg cei iprc tpnn du cei qprcni\n" }, { "code": null, "e": 2934, "s": 2857, "text": "The following code shows a program to implement simple substitution cipher −" }, { "code": null, "e": 4648, "s": 2934, "text": "import random, sys\n\nLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\ndef main():\n message = ''\n if len(sys.argv) > 1:\n with open(sys.argv[1], 'r') as f:\n message = f.read()\n else:\n message = raw_input(\"Enter your message: \")\n mode = raw_input(\"E for Encrypt, D for Decrypt: \")\n key = ''\n \n while checkKey(key) is False:\n key = raw_input(\"Enter 26 ALPHA key (leave blank for random key): \")\n if key == '':\n key = getRandomKey()\n if checkKey(key) is False:\n\t\tprint('There is an error in the key or symbol set.')\n translated = translateMessage(message, key, mode)\n print('Using key: %s' % (key))\n \n if len(sys.argv) > 1:\n fileOut = 'enc.' + sys.argv[1]\n with open(fileOut, 'w') as f:\n f.write(translated)\n print('Success! File written to: %s' % (fileOut))\n else: print('Result: ' + translated)\n\n# Store the key into list, sort it, convert back, compare to alphabet.\ndef checkKey(key):\n keyString = ''.join(sorted(list(key)))\n return keyString == LETTERS\ndef translateMessage(message, key, mode):\n translated = ''\n charsA = LETTERS\n charsB = key\n \n # If decrypt mode is detected, swap A and B\n if mode == 'D':\n charsA, charsB = charsB, charsA\n for symbol in message:\n if symbol.upper() in charsA:\n symIndex = charsA.find(symbol.upper())\n if symbol.isupper():\n translated += charsB[symIndex].upper()\n else:\n translated += charsB[symIndex].lower()\n\t\t\t\telse:\n translated += symbol\n return translated\ndef getRandomKey():\n randomList = list(LETTERS)\n random.shuffle(randomList)\n return ''.join(randomList)\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 4727, "s": 4648, "text": "You can observe the following output when you implement the code given above −" }, { "code": null, "e": 4760, "s": 4727, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4776, "s": 4760, "text": " Total Seminars" }, { "code": null, "e": 4809, "s": 4776, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4832, "s": 4809, "text": " Stone River ELearning" }, { "code": null, "e": 4839, "s": 4832, "text": " Print" }, { "code": null, "e": 4850, "s": 4839, "text": " Add Notes" } ]
AWT MouseMotionAdapter Class
The class MouseMotionAdapter is an abstract (adapter) class for receiving mouse motion events. All methods of this class are empty. This class is convenience class for creating listener objects. Following is the declaration for java.awt.event.MouseMotionAdapter class: public abstract class MouseMotionAdapter extends Object implements MouseMotionListener MouseMotionAdapter() void mouseDragged(MouseEvent e) Invoked when a mouse button is pressed on a component and then dragged. void mouseMoved(MouseEvent e) Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed. This class inherits methods from the following classes: java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; public class AwtAdapterDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; public AwtAdapterDemo(){ prepareGUI(); } public static void main(String[] args){ AwtAdapterDemo awtAdapterDemo = new AwtAdapterDemo(); awtAdapterDemo.showMouseMotionAdapterDemo(); } private void prepareGUI(){ mainFrame = new Frame("Java AWT Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new Label(); headerLabel.setAlignment(Label.CENTER); statusLabel = new Label(); statusLabel.setAlignment(Label.CENTER); statusLabel.setSize(350,100); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showMouseMotionAdapterDemo(){ headerLabel.setText("Listener in action: MouseMotionAdapter"); Panel panel = new Panel(); panel.setBackground(Color.magenta); panel.setLayout(new FlowLayout()); panel.addMouseMotionListener(new MouseMotionAdapter(){ public void mouseMoved(MouseEvent e) { statusLabel.setText("Mouse Moved: ("+e.getX()+", "+e.getY() +")"); } }); Label msglabel = new Label(); msglabel.setAlignment(Label.CENTER); msglabel.setText("Welcome to TutorialsPoint AWT Tutorial."); panel.add(msglabel); controlPanel.add(panel); mainFrame.setVisible(true); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1942, "s": 1747, "text": "The class MouseMotionAdapter is an abstract (adapter) class for receiving mouse motion events. All methods of this class are empty. This class is convenience class for creating listener objects." }, { "code": null, "e": 2016, "s": 1942, "text": "Following is the declaration for java.awt.event.MouseMotionAdapter class:" }, { "code": null, "e": 2112, "s": 2016, "text": "public abstract class MouseMotionAdapter\n extends Object\n implements MouseMotionListener" }, { "code": null, "e": 2134, "s": 2112, "text": "MouseMotionAdapter() " }, { "code": null, "e": 2167, "s": 2134, "text": "void mouseDragged(MouseEvent e) " }, { "code": null, "e": 2239, "s": 2167, "text": "Invoked when a mouse button is pressed on a component and then dragged." }, { "code": null, "e": 2270, "s": 2239, "text": "void mouseMoved(MouseEvent e) " }, { "code": null, "e": 2365, "s": 2270, "text": "Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed." }, { "code": null, "e": 2421, "s": 2365, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 2438, "s": 2421, "text": "java.lang.Object" }, { "code": null, "e": 2455, "s": 2438, "text": "java.lang.Object" }, { "code": null, "e": 2569, "s": 2455, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 4519, "s": 2569, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtAdapterDemo {\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n\n public AwtAdapterDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtAdapterDemo awtAdapterDemo = new AwtAdapterDemo(); \n awtAdapterDemo.showMouseMotionAdapterDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showMouseMotionAdapterDemo(){\n headerLabel.setText(\"Listener in action: MouseMotionAdapter\"); \n\n Panel panel = new Panel(); \n panel.setBackground(Color.magenta);\n panel.setLayout(new FlowLayout()); \n panel.addMouseMotionListener(new MouseMotionAdapter(){\n public void mouseMoved(MouseEvent e) {\n statusLabel.setText(\"Mouse Moved: (\"+e.getX()+\", \"+e.getY() +\")\");\n } \n });\n\n Label msglabel = new Label();\n msglabel.setAlignment(Label.CENTER);\n msglabel.setText(\"Welcome to TutorialsPoint AWT Tutorial.\");\n panel.add(msglabel);\n\n controlPanel.add(panel);\n\n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 4610, "s": 4519, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 4666, "s": 4610, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtAdapterDemo.java" }, { "code": null, "e": 4763, "s": 4666, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 4813, "s": 4763, "text": "D:\\AWT>java com.tutorialspoint.gui.AwtAdapterDemo" }, { "code": null, "e": 4841, "s": 4813, "text": "Verify the following output" }, { "code": null, "e": 4874, "s": 4841, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 4882, "s": 4874, "text": " EduOLC" }, { "code": null, "e": 4889, "s": 4882, "text": " Print" }, { "code": null, "e": 4900, "s": 4889, "text": " Add Notes" } ]
Interpret Linear Regression in 10 mins (Non-Technical) | by Anish Mahapatra | Towards Data Science
When there are so many great articles and interpretations of the most common algorithm out there, why take the effort to write this? How does an executive or a non-technical person interpret linear regression? All of the articles are heavy on the technicality. I like to understand things for what they are minus the extra-effort. Linear Regression is said to be the most basic algorithm that one can implement. Even though going through a tutorial on linear regression will enable even a high school student to understand and implement a model in Python in about five minutes, there are more nuances when applying machine learning algorithms in a production environment. The agenda of this blog and the upcoming series is to capture and explain the subtleties of linear regression in layman terms (read non-technical). You can follow me here for more. Do you remember the equation of a straight line that we learned in school? Mathematically, the representation of a straight line is represented as y = MX + b. y = mx + bWhere, if you were to imagine a straight line (as shown above),m: The slope of the line (The angle at which the line is turned)b: The intercept (On the Y-Axis, how much higher or lower is the line)y: The dependent/ target variable (The value we want to predict)x: The independent/ predictor variable (The variable that we use to make the prediction) Let us look at models from the lens of an executive, not a technically savvy person. A machine learning model is simply a way to be able to represent or guess what is going to happen next, where something belongs or what combination of features will work best to know what is going to happen next. A machine learning model is not magic. It is simply a mathematical best-fit representation of the data. Linear in linear model stands for the straight line. The data has to be such that there is a linear trend in the data to be able to use linear regression. Let us look at one of the classic examples of a linear model — Newton’s first law of motion. Force = Mass x Acceleration ( F = m x a ) Let us now interpret this. If the mass of the object is constant, then, as we increase the acceleration of an object, the force applied increases. To compare this to the previous formula, y = mx + bFor this case, y = mxand, there is no intercept: 'b' here. This means that the graph will pass through the origin. (when x = 0, y = 0) Let us now look at what regression is in Linear Regression. In machine learning, The dependent variable is represented as ‘y’ The independent variable(s) that will be used is/ are represented as ‘X’ Regression is simply establishing a relationship between the independent variables and the dependent variable. Linear regression is establishing a relationship between the features and dependent variable that can be best represented by a straight line. Linear regression can be of two types: simple and multiple linear regression.- Simple Linear Regression: Using one independent variable to predict one dependent variable- Multiple Linear Regression: Using multiple independent variables to predict one dependent variable So, if you have a data scientist that says: I shall be running a multiple linear regression model on the independent features and the predictor, understand that he is going to try to make a straight line through the data where the line is close to as many input data points as possible. A line can be drawn through the data in various ways. Q. What do you think the best-fit line means? A. This is where you will hear the data scientists say that they are trying to minimize the cost function. Q. What does the cost function/ error function mean?A. A function that sums up the errors. As a user, you would want an optimal cost function as this would mean that you have the least possible errors. A best-fit line would have the tilt and intercept such that it passes through or as close to the data points as possible. To be able to explain the simplicity and execution of models, you have to understand the implementation in depth. Feel free to leverage the same here on my Github. Do raise issues there or comment below if you are stuck anywhere through the flow of the machine learning notebooks. I strongly suggest you follow me here on Medium or LinkedIn to get maximum exposure to the bleeding edge in technology. In case you would like to run the latest models on old hardware, you can refer to the link here to run it for free on the cloud. https://towardsdatascience.com/running-jupyter-notebook-on-the-cloud-in-15-mins-azure-79b7797e4ef6 As a passive observer looking at various models that a data scientist is showing you, it is imperative that you are able to judge if a model is suitable for your needs. Notice how very delicately I have avoided using the word good or bad here. It is a conscious decision as it varies from case to case. However, on that note, I have heard this too many times and am determined to provide you with use-cases and intuition, so that you can evaluate if the model is right for you. I shall stress here on pointers that an executive-level person can look at a Data Science Jupyter Notebook (code) or ask questions on, as mentioned below. I shall explain the questions, but, not the answers as that is the role of the data scientist. If the data scientist is not able to answer, the data scientist requires further training, before you decide to trust the results. Did you clean the data? What are the steps you took for it and why? What are the columns that are affected? By rows and columns, what is the percentage of missing values/ corrupted data? How did you handle the missing data? Did you perform outlier analysis on the data? Can you show me the box-plots and explain them to me along with your reasoning as to why you decided to keep the outliers (or remove them)? Show me the univariate plots and explain them to me in detail. Please make sure you explicitly document and mention the interesting trends. Show me the bivariate plots and explain the interesting trends with respect to the dependent variable. Make sure you talk about the top correlated variables along with business backing. (Ask for heatmaps) Has feature engineering been done on the data? What are the derived/ new features? What is the test-train split? Why? Is there a spill-over in the train-test data? How have you handled the categorical variables and generating gummy variables? Have you considered the dummy variable trap? When plotting the models, variables should be dropped one by one and the statistics and VIF scores should be analyzed after every variable is dropped. Was this followed? Have you considered the F-statistic or p-values (generally less than 0.05) for the statistics model? Have you considered the possibility of multicollinearity? Can you please show me the VIF (Variable Inflation Factor)? (VIF >10 might indicate multicollinearity) Have you validated the results on the test data? What is the R-Squared value? (The closer to 1, the better) What is the adjusted R-Squared value? This can be used to compare models where there are a different number of features (The closer to 1, the better) It’s admirable if you have got to this point. This means that you have a genuine interest and you deserve to understand the nuances of model-building. Provided we are dealing with mostly clean data, asking the above questions will help us interpret a linear regression model. To understand further on how to evaluate a linear regression model you can refer to the link here. While the above questions may help you understand the work a data scientist has done, the best way to interpret Data Science is to simply do it yourself! Whether it’s code or interpretation of the same, the best way to gain an understanding, get your hands dirty and look through a few industry-standard implementations on Kaggle and ProjectPro. www.linkedin.com I spent a lot of time researching and thoroughly enjoyed writing this article. Show me some love if this helped you! 😄 I also write about the millennial lifestyle, consulting, chatbots and finance! If you have any questions or recommendations on this, please feel free to reach out to me on LinkedIn or follow me here, I’d love to hear your thoughts!
[ { "code": null, "e": 433, "s": 172, "text": "When there are so many great articles and interpretations of the most common algorithm out there, why take the effort to write this? How does an executive or a non-technical person interpret linear regression? All of the articles are heavy on the technicality." }, { "code": null, "e": 503, "s": 433, "text": "I like to understand things for what they are minus the extra-effort." }, { "code": null, "e": 844, "s": 503, "text": "Linear Regression is said to be the most basic algorithm that one can implement. Even though going through a tutorial on linear regression will enable even a high school student to understand and implement a model in Python in about five minutes, there are more nuances when applying machine learning algorithms in a production environment." }, { "code": null, "e": 1025, "s": 844, "text": "The agenda of this blog and the upcoming series is to capture and explain the subtleties of linear regression in layman terms (read non-technical). You can follow me here for more." }, { "code": null, "e": 1184, "s": 1025, "text": "Do you remember the equation of a straight line that we learned in school? Mathematically, the representation of a straight line is represented as y = MX + b." }, { "code": null, "e": 1544, "s": 1184, "text": "y = mx + bWhere, if you were to imagine a straight line (as shown above),m: The slope of the line (The angle at which the line is turned)b: The intercept (On the Y-Axis, how much higher or lower is the line)y: The dependent/ target variable (The value we want to predict)x: The independent/ predictor variable (The variable that we use to make the prediction)" }, { "code": null, "e": 1629, "s": 1544, "text": "Let us look at models from the lens of an executive, not a technically savvy person." }, { "code": null, "e": 1842, "s": 1629, "text": "A machine learning model is simply a way to be able to represent or guess what is going to happen next, where something belongs or what combination of features will work best to know what is going to happen next." }, { "code": null, "e": 1946, "s": 1842, "text": "A machine learning model is not magic. It is simply a mathematical best-fit representation of the data." }, { "code": null, "e": 2194, "s": 1946, "text": "Linear in linear model stands for the straight line. The data has to be such that there is a linear trend in the data to be able to use linear regression. Let us look at one of the classic examples of a linear model — Newton’s first law of motion." }, { "code": null, "e": 2236, "s": 2194, "text": "Force = Mass x Acceleration ( F = m x a )" }, { "code": null, "e": 2383, "s": 2236, "text": "Let us now interpret this. If the mass of the object is constant, then, as we increase the acceleration of an object, the force applied increases." }, { "code": null, "e": 2424, "s": 2383, "text": "To compare this to the previous formula," }, { "code": null, "e": 2569, "s": 2424, "text": "y = mx + bFor this case, y = mxand, there is no intercept: 'b' here. This means that the graph will pass through the origin. (when x = 0, y = 0)" }, { "code": null, "e": 2650, "s": 2569, "text": "Let us now look at what regression is in Linear Regression. In machine learning," }, { "code": null, "e": 2695, "s": 2650, "text": "The dependent variable is represented as ‘y’" }, { "code": null, "e": 2768, "s": 2695, "text": "The independent variable(s) that will be used is/ are represented as ‘X’" }, { "code": null, "e": 3021, "s": 2768, "text": "Regression is simply establishing a relationship between the independent variables and the dependent variable. Linear regression is establishing a relationship between the features and dependent variable that can be best represented by a straight line." }, { "code": null, "e": 3291, "s": 3021, "text": "Linear regression can be of two types: simple and multiple linear regression.- Simple Linear Regression: Using one independent variable to predict one dependent variable- Multiple Linear Regression: Using multiple independent variables to predict one dependent variable" }, { "code": null, "e": 3335, "s": 3291, "text": "So, if you have a data scientist that says:" }, { "code": null, "e": 3578, "s": 3335, "text": "I shall be running a multiple linear regression model on the independent features and the predictor, understand that he is going to try to make a straight line through the data where the line is close to as many input data points as possible." }, { "code": null, "e": 3632, "s": 3578, "text": "A line can be drawn through the data in various ways." }, { "code": null, "e": 3785, "s": 3632, "text": "Q. What do you think the best-fit line means? A. This is where you will hear the data scientists say that they are trying to minimize the cost function." }, { "code": null, "e": 3987, "s": 3785, "text": "Q. What does the cost function/ error function mean?A. A function that sums up the errors. As a user, you would want an optimal cost function as this would mean that you have the least possible errors." }, { "code": null, "e": 4109, "s": 3987, "text": "A best-fit line would have the tilt and intercept such that it passes through or as close to the data points as possible." }, { "code": null, "e": 4510, "s": 4109, "text": "To be able to explain the simplicity and execution of models, you have to understand the implementation in depth. Feel free to leverage the same here on my Github. Do raise issues there or comment below if you are stuck anywhere through the flow of the machine learning notebooks. I strongly suggest you follow me here on Medium or LinkedIn to get maximum exposure to the bleeding edge in technology." }, { "code": null, "e": 4639, "s": 4510, "text": "In case you would like to run the latest models on old hardware, you can refer to the link here to run it for free on the cloud." }, { "code": null, "e": 4738, "s": 4639, "text": "https://towardsdatascience.com/running-jupyter-notebook-on-the-cloud-in-15-mins-azure-79b7797e4ef6" }, { "code": null, "e": 5041, "s": 4738, "text": "As a passive observer looking at various models that a data scientist is showing you, it is imperative that you are able to judge if a model is suitable for your needs. Notice how very delicately I have avoided using the word good or bad here. It is a conscious decision as it varies from case to case." }, { "code": null, "e": 5371, "s": 5041, "text": "However, on that note, I have heard this too many times and am determined to provide you with use-cases and intuition, so that you can evaluate if the model is right for you. I shall stress here on pointers that an executive-level person can look at a Data Science Jupyter Notebook (code) or ask questions on, as mentioned below." }, { "code": null, "e": 5466, "s": 5371, "text": "I shall explain the questions, but, not the answers as that is the role of the data scientist." }, { "code": null, "e": 5597, "s": 5466, "text": "If the data scientist is not able to answer, the data scientist requires further training, before you decide to trust the results." }, { "code": null, "e": 5705, "s": 5597, "text": "Did you clean the data? What are the steps you took for it and why? What are the columns that are affected?" }, { "code": null, "e": 5821, "s": 5705, "text": "By rows and columns, what is the percentage of missing values/ corrupted data? How did you handle the missing data?" }, { "code": null, "e": 6007, "s": 5821, "text": "Did you perform outlier analysis on the data? Can you show me the box-plots and explain them to me along with your reasoning as to why you decided to keep the outliers (or remove them)?" }, { "code": null, "e": 6147, "s": 6007, "text": "Show me the univariate plots and explain them to me in detail. Please make sure you explicitly document and mention the interesting trends." }, { "code": null, "e": 6352, "s": 6147, "text": "Show me the bivariate plots and explain the interesting trends with respect to the dependent variable. Make sure you talk about the top correlated variables along with business backing. (Ask for heatmaps)" }, { "code": null, "e": 6435, "s": 6352, "text": "Has feature engineering been done on the data? What are the derived/ new features?" }, { "code": null, "e": 6516, "s": 6435, "text": "What is the test-train split? Why? Is there a spill-over in the train-test data?" }, { "code": null, "e": 6640, "s": 6516, "text": "How have you handled the categorical variables and generating gummy variables? Have you considered the dummy variable trap?" }, { "code": null, "e": 6810, "s": 6640, "text": "When plotting the models, variables should be dropped one by one and the statistics and VIF scores should be analyzed after every variable is dropped. Was this followed?" }, { "code": null, "e": 6911, "s": 6810, "text": "Have you considered the F-statistic or p-values (generally less than 0.05) for the statistics model?" }, { "code": null, "e": 7072, "s": 6911, "text": "Have you considered the possibility of multicollinearity? Can you please show me the VIF (Variable Inflation Factor)? (VIF >10 might indicate multicollinearity)" }, { "code": null, "e": 7180, "s": 7072, "text": "Have you validated the results on the test data? What is the R-Squared value? (The closer to 1, the better)" }, { "code": null, "e": 7330, "s": 7180, "text": "What is the adjusted R-Squared value? This can be used to compare models where there are a different number of features (The closer to 1, the better)" }, { "code": null, "e": 7705, "s": 7330, "text": "It’s admirable if you have got to this point. This means that you have a genuine interest and you deserve to understand the nuances of model-building. Provided we are dealing with mostly clean data, asking the above questions will help us interpret a linear regression model. To understand further on how to evaluate a linear regression model you can refer to the link here." }, { "code": null, "e": 8051, "s": 7705, "text": "While the above questions may help you understand the work a data scientist has done, the best way to interpret Data Science is to simply do it yourself! Whether it’s code or interpretation of the same, the best way to gain an understanding, get your hands dirty and look through a few industry-standard implementations on Kaggle and ProjectPro." }, { "code": null, "e": 8068, "s": 8051, "text": "www.linkedin.com" } ]
Calculate pressure of a real gas using Van der Waal's Equation - GeeksforGeeks
21 Apr, 2021 Given integers V, T, and n representing the volume, temperature and the number of moles of a real gas, the task is to calculate the pressure P of the gas using Van der Waal’s Equation for real gas. Van der Waal’s Equation for Real Gas:( P + a * n2 / V2 ) * (V – n * b) = n R T) where, average attraction between particles (a) = 1.360, volume excluded by a mole of particles (b) = 0.03186, Universal Gas constant (R) = 8.314 Examples: Input: V = 5, T = 275, n = 6Output: 2847.64 Input: V = 7, T = 300, n = 10Output: 3725.43 Approach: To solve the problem, simply calculate the pressure P of real gas by using the equation P = ((n * R * T) / (V — n * b)) — (a* n * n) / (V * V) and print the result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate the pressure of a// real gas using Van der Wall's equationvoid pressure_using_vanderwall(double V, double T, double n){ double a = 1.382; double b = 0.031; double R = 8.314; // Calculating pressure double P = ((n * R * T) / (V - n * b)) - (a * n * n) / (V * V); // Print the obtained result cout << P << endl;} // Driver codeint main(){ double V = 7, T = 300, n = 10; pressure_using_vanderwall(V, T, n); return 0;} // Java program to implement// the above approachclass GFG{ // Function to calculate the pressure of a// real gas using Van der Wall's equationpublic static void pressure_using_vanderwall(double V, double T, double n){ double a = 1.382; double b = 0.031; double R = 8.314; // Calculating pressure double P = ((n * R * T) / (V - n * b)) - (a * n * n) / (V * V); // Print the obtained result System.out.println(String.format("%.2f", P));} // Driver Codepublic static void main(String[] args){ double V = 7, T = 300, n = 10; pressure_using_vanderwall(V, T, n);}} // This code is contributed by divyesh072019 # Python3 Program to implement# the above approach # Function to calculate the pressure of a# real gas using Van der Wall's equationdef pressure_using_vanderwall(V, T, n): a = 1.382 b = 0.031 R = 8.314 # Calculating pressure P = ((n * R * T) / (V - n * b)) - (a * n * n) / (V * V) # Print the obtained result print(round(P, 2)) # Driver codeV, T, n = 7, 300, 10pressure_using_vanderwall(V, T, n) # This code is contributed by divyeshrabadiya07 // C# program to implement// the above approachusing System; class GFG{ // Function to calculate the pressure of a // real gas using Van der Wall's equation public static void pressure_using_vanderwall(double V, double T, double n) { double a = 1.382; double b = 0.031; double R = 8.314; // Calculating pressure double P = ((n * R * T) / (V - n * b)) - (a * n * n) / (V * V); // Print the obtained result Console.WriteLine(Math.Round(P, 2)); } // Driver Code public static void Main(String[] args) { double V = 7, T = 300, n = 10; pressure_using_vanderwall(V, T, n); }} // This code is contributed by AnkitRai01 <script> // Javascript program to implement the above approach // Function to calculate the pressure of a // real gas using Van der Wall's equation function pressure_using_vanderwall(V, T, n) { let a = 1.382; let b = 0.031; let R = 8.314; // Calculating pressure let P = ((n * R * T) / (V - n * b)) - (a * n * n) / (V * V); // Print the obtained result document.write(P.toFixed(2)); } let V = 7, T = 300, n = 10; pressure_using_vanderwall(V, T, n); // This code is contributed by decode2207.</script> 3725.43 Time Complexity: O(1)Auxiliary Space: O(1) divyeshrabadiya07 divyesh072019 ankthon decode2207 Articles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity Docker - COPY Instruction Time complexities of different data structures SQL | Date functions Difference between Min Heap and Max Heap Implementation of LinkedList in Javascript Difference between Class and Object Deploy Python Flask App on Heroku How compare() method works in Java SQL | Functions (Aggregate and Scalar Functions)
[ { "code": null, "e": 24420, "s": 24392, "text": "\n21 Apr, 2021" }, { "code": null, "e": 24618, "s": 24420, "text": "Given integers V, T, and n representing the volume, temperature and the number of moles of a real gas, the task is to calculate the pressure P of the gas using Van der Waal’s Equation for real gas." }, { "code": null, "e": 24844, "s": 24618, "text": "Van der Waal’s Equation for Real Gas:( P + a * n2 / V2 ) * (V – n * b) = n R T) where, average attraction between particles (a) = 1.360, volume excluded by a mole of particles (b) = 0.03186, Universal Gas constant (R) = 8.314" }, { "code": null, "e": 24854, "s": 24844, "text": "Examples:" }, { "code": null, "e": 24898, "s": 24854, "text": "Input: V = 5, T = 275, n = 6Output: 2847.64" }, { "code": null, "e": 24943, "s": 24898, "text": "Input: V = 7, T = 300, n = 10Output: 3725.43" }, { "code": null, "e": 25119, "s": 24943, "text": "Approach: To solve the problem, simply calculate the pressure P of real gas by using the equation P = ((n * R * T) / (V — n * b)) — (a* n * n) / (V * V) and print the result. " }, { "code": null, "e": 25170, "s": 25119, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25174, "s": 25170, "text": "C++" }, { "code": null, "e": 25179, "s": 25174, "text": "Java" }, { "code": null, "e": 25187, "s": 25179, "text": "Python3" }, { "code": null, "e": 25190, "s": 25187, "text": "C#" }, { "code": null, "e": 25201, "s": 25190, "text": "Javascript" }, { "code": "// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate the pressure of a// real gas using Van der Wall's equationvoid pressure_using_vanderwall(double V, double T, double n){ double a = 1.382; double b = 0.031; double R = 8.314; // Calculating pressure double P = ((n * R * T) / (V - n * b)) - (a * n * n) / (V * V); // Print the obtained result cout << P << endl;} // Driver codeint main(){ double V = 7, T = 300, n = 10; pressure_using_vanderwall(V, T, n); return 0;}", "e": 25813, "s": 25201, "text": null }, { "code": "// Java program to implement// the above approachclass GFG{ // Function to calculate the pressure of a// real gas using Van der Wall's equationpublic static void pressure_using_vanderwall(double V, double T, double n){ double a = 1.382; double b = 0.031; double R = 8.314; // Calculating pressure double P = ((n * R * T) / (V - n * b)) - (a * n * n) / (V * V); // Print the obtained result System.out.println(String.format(\"%.2f\", P));} // Driver Codepublic static void main(String[] args){ double V = 7, T = 300, n = 10; pressure_using_vanderwall(V, T, n);}} // This code is contributed by divyesh072019", "e": 26561, "s": 25813, "text": null }, { "code": "# Python3 Program to implement# the above approach # Function to calculate the pressure of a# real gas using Van der Wall's equationdef pressure_using_vanderwall(V, T, n): a = 1.382 b = 0.031 R = 8.314 # Calculating pressure P = ((n * R * T) / (V - n * b)) - (a * n * n) / (V * V) # Print the obtained result print(round(P, 2)) # Driver codeV, T, n = 7, 300, 10pressure_using_vanderwall(V, T, n) # This code is contributed by divyeshrabadiya07", "e": 27029, "s": 26561, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to calculate the pressure of a // real gas using Van der Wall's equation public static void pressure_using_vanderwall(double V, double T, double n) { double a = 1.382; double b = 0.031; double R = 8.314; // Calculating pressure double P = ((n * R * T) / (V - n * b)) - (a * n * n) / (V * V); // Print the obtained result Console.WriteLine(Math.Round(P, 2)); } // Driver Code public static void Main(String[] args) { double V = 7, T = 300, n = 10; pressure_using_vanderwall(V, T, n); }} // This code is contributed by AnkitRai01", "e": 27883, "s": 27029, "text": null }, { "code": "<script> // Javascript program to implement the above approach // Function to calculate the pressure of a // real gas using Van der Wall's equation function pressure_using_vanderwall(V, T, n) { let a = 1.382; let b = 0.031; let R = 8.314; // Calculating pressure let P = ((n * R * T) / (V - n * b)) - (a * n * n) / (V * V); // Print the obtained result document.write(P.toFixed(2)); } let V = 7, T = 300, n = 10; pressure_using_vanderwall(V, T, n); // This code is contributed by decode2207.</script>", "e": 28493, "s": 27883, "text": null }, { "code": null, "e": 28501, "s": 28493, "text": "3725.43" }, { "code": null, "e": 28546, "s": 28503, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 28566, "s": 28548, "text": "divyeshrabadiya07" }, { "code": null, "e": 28580, "s": 28566, "text": "divyesh072019" }, { "code": null, "e": 28588, "s": 28580, "text": "ankthon" }, { "code": null, "e": 28599, "s": 28588, "text": "decode2207" }, { "code": null, "e": 28608, "s": 28599, "text": "Articles" }, { "code": null, "e": 28706, "s": 28608, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28743, "s": 28706, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 28769, "s": 28743, "text": "Docker - COPY Instruction" }, { "code": null, "e": 28816, "s": 28769, "text": "Time complexities of different data structures" }, { "code": null, "e": 28837, "s": 28816, "text": "SQL | Date functions" }, { "code": null, "e": 28878, "s": 28837, "text": "Difference between Min Heap and Max Heap" }, { "code": null, "e": 28921, "s": 28878, "text": "Implementation of LinkedList in Javascript" }, { "code": null, "e": 28957, "s": 28921, "text": "Difference between Class and Object" }, { "code": null, "e": 28991, "s": 28957, "text": "Deploy Python Flask App on Heroku" }, { "code": null, "e": 29026, "s": 28991, "text": "How compare() method works in Java" } ]
Python – Ascending Order Sort grouped Pandas dataframe by group size?
To group Pandas dataframe, we use groupby(). To sort grouped dataframe in ascending order, use sort_values(). The size() method is used to get the dataframe size. For ascending order sort, use the following in sort_values() − ascending=True At first, create a pandas dataframe − dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'], "Reg_Price": [1000, 1400, 1000, 900, 1700, 900] } ) Next, group according to Reg_Price column and sort in ascending order − dataFrame.groupby('Reg_Price').size().sort_values(ascending=True) Following is the code − import pandas as pd # dataframe with one of the columns as Reg_Price dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'], "Reg_Price": [1000, 1400, 1000, 900, 1700, 900] } ) print"DataFrame...\n",dataFrame # group according to Reg_Price column and sort in ascending order print"\nSorted in Ascending order..."; print(dataFrame.groupby('Reg_Price').size().sort_values(ascending=True)) This will produce the following output− DataFrame... Car Reg_Price 0 BMW 1000 1 Lexus 1400 2 Audi 1000 3 Mercedes 900 4 Jaguar 1700 5 Bentley 900 Sorted in Ascending order... Reg_Price 1400 1 1700 1 900 2 1000 2 dtype: int64
[ { "code": null, "e": 1225, "s": 1062, "text": "To group Pandas dataframe, we use groupby(). To sort grouped dataframe in ascending order, use sort_values(). The size() method is used to get the dataframe size." }, { "code": null, "e": 1288, "s": 1225, "text": "For ascending order sort, use the following in sort_values() −" }, { "code": null, "e": 1303, "s": 1288, "text": "ascending=True" }, { "code": null, "e": 1341, "s": 1303, "text": "At first, create a pandas dataframe −" }, { "code": null, "e": 1506, "s": 1341, "text": "dataFrame = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],\n\n \"Reg_Price\": [1000, 1400, 1000, 900, 1700, 900]\n }\n)" }, { "code": null, "e": 1578, "s": 1506, "text": "Next, group according to Reg_Price column and sort in ascending order −" }, { "code": null, "e": 1644, "s": 1578, "text": "dataFrame.groupby('Reg_Price').size().sort_values(ascending=True)" }, { "code": null, "e": 1668, "s": 1644, "text": "Following is the code −" }, { "code": null, "e": 2115, "s": 1668, "text": "import pandas as pd\n\n# dataframe with one of the columns as Reg_Price\ndataFrame = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],\n\n \"Reg_Price\": [1000, 1400, 1000, 900, 1700, 900]\n }\n)\n\nprint\"DataFrame...\\n\",dataFrame\n\n# group according to Reg_Price column and sort in ascending order\nprint\"\\nSorted in Ascending order...\";\nprint(dataFrame.groupby('Reg_Price').size().sort_values(ascending=True))" }, { "code": null, "e": 2155, "s": 2115, "text": "This will produce the following output−" }, { "code": null, "e": 2415, "s": 2155, "text": "DataFrame...\n Car Reg_Price\n0 BMW 1000\n1 Lexus 1400\n2 Audi 1000\n3 Mercedes 900\n4 Jaguar 1700\n5 Bentley 900\n\nSorted in Ascending order...\nReg_Price\n1400 1\n1700 1\n900 2\n1000 2\ndtype: int64" } ]
How to find time difference using Python?
It is very easy to do date and time maths in Python using time delta objects. Whenever you want to add or subtract to a date/time, use a DateTime.datetime(), then add or subtract date time.time delta() instances. A time delta object represents a duration, the difference between two dates or times. The time delta constructor has the following function signature DateTime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])¶ Note: All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative. You can read more about it here https://docs.python.org/2/library/datetime.html#timedelta-objects An example of using the time delta objects and dates import datetime old_time = datetime.datetime.now() print(old_time) new_time = old_time - datetime.timedelta(hours=2, minutes=10) print(new_time) This will give the output 2018-01-04 11:09:00.694602 2018-01-04 08:59:00.694602 time delta() arithmetic is not supported for date time.time() objects; if you need to use offsets from an existing date time.time() object, just use date time.datetime.combine() to form a date time.date time() instance, do your calculations, and 'extract' the time again with the .time() method. Subtracting 2 date time objects gives a time delta object. This time delta object can be used to find the exact difference between the 2 date times. t1 = datetime.datetime.now() t2 = datetime.datetime.now() print(t1 - t2) print(type(t1 - t2)) This will give the output -1 day, 23:59:56.653627 <class 'datetime.timedelta'>
[ { "code": null, "e": 1425, "s": 1062, "text": "It is very easy to do date and time maths in Python using time delta objects. Whenever you want to add or subtract to a date/time, use a DateTime.datetime(), then add or subtract date time.time delta() instances. A time delta object represents a duration, the difference between two dates or times. The time delta constructor has the following function signature" }, { "code": null, "e": 1525, "s": 1425, "text": "DateTime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])¶" }, { "code": null, "e": 1748, "s": 1525, "text": "Note: All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative. You can read more about it here https://docs.python.org/2/library/datetime.html#timedelta-objects" }, { "code": null, "e": 1801, "s": 1748, "text": "An example of using the time delta objects and dates" }, { "code": null, "e": 1946, "s": 1801, "text": "import datetime\nold_time = datetime.datetime.now()\nprint(old_time)\nnew_time = old_time - datetime.timedelta(hours=2, minutes=10)\nprint(new_time)" }, { "code": null, "e": 1972, "s": 1946, "text": "This will give the output" }, { "code": null, "e": 2026, "s": 1972, "text": "2018-01-04 11:09:00.694602\n2018-01-04 08:59:00.694602" }, { "code": null, "e": 2322, "s": 2026, "text": "time delta() arithmetic is not supported for date time.time() objects; if you need to use offsets from an existing date time.time() object, just use date time.datetime.combine() to form a date time.date time() instance, do your calculations, and 'extract' the time again with the .time() method." }, { "code": null, "e": 2472, "s": 2322, "text": "Subtracting 2 date time objects gives a time delta object. This time delta object can be used to find the exact difference between the 2 date times. " }, { "code": null, "e": 2566, "s": 2472, "text": "t1 = datetime.datetime.now()\nt2 = datetime.datetime.now()\nprint(t1 - t2)\nprint(type(t1 - t2))" }, { "code": null, "e": 2592, "s": 2566, "text": "This will give the output" }, { "code": null, "e": 2645, "s": 2592, "text": "-1 day, 23:59:56.653627\n<class 'datetime.timedelta'>" } ]
Get the item that appears the most times in an array JavaScript
Let’s say, we are required to write a function that takes in an array of string / number literals and returns the index of the item that appears for the most number of times. We will iterate over the array and prepare a frequencyMap and from that map we will return the index that makes most appearances. The code for doing so will be − const arr1 = [12, 5, 6, 76, 23, 12, 34, 5, 23, 34, 65, 34, 22, 67, 34]; const arr2 = [12, 5, 6, 76, 23, 12, 34, 5, 23, 34]; const mostAppearances = (arr) => { const frequencyMap = {}; arr.forEach(el => { if(frequencyMap[el]){ frequencyMap[el]++; }else{ frequencyMap[el] = 1; }; }); let highest, frequency = 0; Object.keys(frequencyMap).forEach(key => { if(frequencyMap[key] > frequency){ highest = parseInt(key, 10); frequency = frequencyMap[key]; }; }); return arr.indexOf(highest); }; console.log(mostAppearances(arr1)); console.log(mostAppearances(arr2)); The output in the console will be − 6 1
[ { "code": null, "e": 1367, "s": 1062, "text": "Let’s say, we are required to write a function that takes in an array of string / number literals and\nreturns the index of the item that appears for the most number of times. We will iterate over the\narray and prepare a frequencyMap and from that map we will return the index that makes most\nappearances." }, { "code": null, "e": 1399, "s": 1367, "text": "The code for doing so will be −" }, { "code": null, "e": 2045, "s": 1399, "text": "const arr1 = [12, 5, 6, 76, 23, 12, 34, 5, 23, 34, 65, 34, 22, 67, 34];\nconst arr2 = [12, 5, 6, 76, 23, 12, 34, 5, 23, 34];\nconst mostAppearances = (arr) => {\n const frequencyMap = {};\n arr.forEach(el => {\n if(frequencyMap[el]){\n frequencyMap[el]++;\n }else{\n frequencyMap[el] = 1;\n };\n });\n let highest, frequency = 0;\n Object.keys(frequencyMap).forEach(key => {\n if(frequencyMap[key] > frequency){\n highest = parseInt(key, 10);\n frequency = frequencyMap[key];\n };\n });\n return arr.indexOf(highest);\n};\nconsole.log(mostAppearances(arr1));\nconsole.log(mostAppearances(arr2));" }, { "code": null, "e": 2081, "s": 2045, "text": "The output in the console will be −" }, { "code": null, "e": 2085, "s": 2081, "text": "6\n1" } ]
How to create a histogram using weights in R?
A histogram using weights represent the weighted distribution of the values. In R, we can use weighted.hist function of plotrix package to create this type of histogram and we just need the values and weights corresponding to each value. Since plotrix is not frequently used, we must make sure that we install this package using install.packages("plotrix") then load it in R environment. Loading plotrix package − library("plotrix") Consider the below vector and the weight associated with that vector − x<-sort(rpois(5000,5)) weight<-seq(1,5000) Creating weighted histogram for x − Let’s have a look at another example − y<-sort(sample(0:100,2000,replace=TRUE)) weight<-seq(1,2000) \ weighted.hist(y,weight)
[ { "code": null, "e": 1450, "s": 1062, "text": "A histogram using weights represent the weighted distribution of the values. In R, we can use weighted.hist function of plotrix package to create this type of histogram and we just need the values and weights corresponding to each value. Since plotrix is not frequently used, we must make sure that we install this package using install.packages(\"plotrix\") then load it in R environment." }, { "code": null, "e": 1476, "s": 1450, "text": "Loading plotrix package −" }, { "code": null, "e": 1495, "s": 1476, "text": "library(\"plotrix\")" }, { "code": null, "e": 1566, "s": 1495, "text": "Consider the below vector and the weight associated with that vector −" }, { "code": null, "e": 1609, "s": 1566, "text": "x<-sort(rpois(5000,5))\nweight<-seq(1,5000)" }, { "code": null, "e": 1645, "s": 1609, "text": "Creating weighted histogram for x −" }, { "code": null, "e": 1684, "s": 1645, "text": "Let’s have a look at another example −" }, { "code": null, "e": 1772, "s": 1684, "text": "y<-sort(sample(0:100,2000,replace=TRUE)) \nweight<-seq(1,2000) \\\nweighted.hist(y,weight)" } ]
How to visualise massive 3D point clouds in Python | Towards Data Science
Data visualisation is a big enchilada 🌶️: by making a graphical representation of information using visual elements, we can best present and understand trends, outliers, and patterns in data. And you guessed it: with 3D point cloud datasets representing real-world shapes, it is mandatory 🙂. However, when collected from a laser scanner or 3D reconstruction techniques such as Photogrammetry, point clouds are usually too dense for classical rendering. In many cases, the datasets will far exceed the 10+ million mark, making them impractical for classical visualisation libraries such as Matplotlib. This means that we often need to go out of our Python script (thus using an I/O function to write our data to a file) and visualise it externally, which can become a super cumbersome process 🤯. I will not lie, that is pretty much what I did the first year of my thesis to try and guess the outcome of specific algorithms🥴. Would it not be neat to visualise these point clouds directly within your script? Even better, connecting the visual feedback to the script? Imagine, now with the iPhone 12 Pro having a LiDAR; you could create a full online application! Good news, there is a way to accomplish this, without leaving the comfort of your Python Environment and IDE. ☕ and ready? In the previous article below, we saw how to set up an environment with Anaconda easily and how to use the IDE Spyder to manage your code. I recommend continuing in this fashion if you set yourself up to becoming a fully-fledge python app developer 😆. towardsdatascience.com If you are using Jupyter Notebook or Google Colab, the script may need some tweaking to make the visualisation back-end work, but deliver unstable performances. If you want to stay on these IDE, I recommend looking at the alternatives to the chosen libraries given in Step 4. I illustrated point cloud processing and meshing over a 3D dataset obtained by using photogrammetry and aerial LiDAR from Open Topography in previous tutorials. I will skip the details on LiDAR I/O covered in the article below, and jump right to using the efficient .las file format. towardsdatascience.com Only this time, we will use an aerial Drone dataset. It was obtained through photogrammetry making a small DJI Phantom Pro 4 fly on our University campus, gathering some images and running a photogrammetric reconstruction as explained here. 🤓 Note: For this how-to guide, you can use the point cloud in this repository, that I already filtered and translated so that you are in the optimal conditions. If you want to visualize and play with it beforehand without installing anything, you can check out the webGL version. We first import necessary libraries within the script (NumPy and LasPy), and load the .las file in a variable called point_cloud. import numpy as npimport laspy as lpinput_path="D:/CLOUD/POUX/ALL_DATA/"dataname="2020_Drone_M"point_cloud=lp.file.File(input_path+dataname+".las", mode="r") Nice, we are almost ready! What is great, is that the LasPy library also give a structure to the point_cloud variable, and we can use straightforward methods to get, for example, X, Y, Z, Red, Blue and Green fields. Let us do this to separate coordinates from colours, and put them in NumPy arrays: points = np.vstack((point_cloud.x, point_cloud.y, point_cloud.z)).transpose()colors = np.vstack((point_cloud.red, point_cloud.green, point_cloud.blue)).transpose() 🤓 Note: We use a vertical stack method from NumPy, and we have to transpose it to get from (n x 3) to a (3 x n) matrix of the point cloud. If your dataset is too heavy, or you feel like you want to experiment on a subsampled version, I encourage you the check out the article below that give you several ways to achieve such a task: towardsdatascience.com Or the following formation for extensive point cloud training: learngeodata.eu For convenience, and if you have a point cloud that exceeds 100 million points, we can just quickly slice your dataset using: factor=10decimated_points_random = points[::factor] 🤓 Note: Running this will keep 1 row every 10 rows, thus dividing the original point cloud's size by 10. Now, let us choose how we want to visualise our point cloud. I will be honest, here: while visualisation alone is great to avoid cumbersome I/O operations, having the ability to include some visual interaction and processing tools within Python is a great addition! Therefore, the solution that I push is using a point cloud processing toolkit that permits exactly this and more. I will still give you alternatives if you want to explore other possibilities ⚖️. The PPTK package has a 3-d point cloud viewer that directly takes a 3-column NumPy array as input and can interactively visualize 10 to 100 million points. It reduces the number of points that needs rendering in each frame by using an octree to cull points outside the view frustum and to approximate groups of faraway points as single points. To get started, you can simply install the library using the Pip manager: pip install pptk Then you can visualise your previously createdpointsvariable from the point cloud by typing: import pptkimport numpy as npv = pptk.viewer(points) Don’t you think we are missing some colours? Let us solve this by typing in the console: v.attributes(colors/65535) 🤓 Note: Our colour values are coded on 16bits from the .las file. We need the values in a [0,1] interval; thus, we divide by 65535. That is way better! But what if we also want to visualise additional attributes? Well, you just link your attributes to your path, and it will update on the fly. 💡 Hint: Do not maximize the size of the window to keep a nice framerate over 30 FPS. The goal is to have the best execution runtime while having a readable script You can also parameterize your window to show each attributes regarding a certain colour ramp, managing the point size, putting the background black and not displaying the grid and axis information: v.color_map('cool')v.set(point_size=0.001,bg_color=[0,0,0,0],show_axis=0,show_grid=0) For anybody wondering for an excellent alternative to read and display point clouds in Python, I recommend Open3D. You can use the Pip package manager as well to install the necessary library: pip install open3d We already used Open3d in the tutorial below, if you want to extend your knowledge on 3D meshing operations: towardsdatascience.com This will install Open3D on your machine, and you will then be able to read and display your point clouds by executing the following script: import open3d as o3dpcd = o3d.geometry.PointCloud()pcd.points = o3d.utility.Vector3dVector(points)pcd.colors = o3d.utility.Vector3dVector(colors/65535)pcd.normals = o3d.utility.Vector3dVector(normals)o3d.visualization.draw_geometries([pcd]) Open3D is actually growing, and you can have some fun ways to display your point cloud to fill eventual holes like creating a voxel structure: voxel_grid = o3d.geometry.VoxelGrid.create_from_point_cloud(pcd,voxel_size=0.40)o3d.visualization.draw_geometries([voxel_grid]) 🤓 Note: Why is Open3d not the choice at this point? If you work with datasets under 50 million points, then it is what I would recommend. If you need to have interactive visualization above this threshold, I recommend either sampling the dataset for visual purposes, or using PPTK which is more efficient for visualizing as you have the octree structure created for this purpose. If you would like to enable simple and interactive exploration of point cloud data, regardless of which sensor was used to generate it or what the use case is, I suggest you look into Pyntcloud, or PyPotree. These will allow you to visualise the point cloud in your notebook, but beware of the performances! Pyntcloud actually rely on Matplotlib, and PyPotree demands I/O operations; thus, both are actually not super-efficient. Nevertheless, I wanted to mention them because for small point clouds and simple experiment in Google Colab, you can integrate the visualisation. Some examples: ### PyntCloud ###conda install pyntcloud -c conda-forgefrom pyntcloud import PyntCloudpointcloud = PyntCloud.from_file("example.ply")pointcloud.plot()### PyntCloud ###pip install pypotreeimport pypotree import numpy as npxyz = np.random.random((100000,3))cloudpath = pypotree.generate_cloud_for_display(xyz)pypotree.display_cloud_colab(cloudpath) Back to PPTK. To make an interactive selection, say the car on the parking lot, I will move my camera top view (shortcut is 7), and I will make a selection dragging a rectangle selection holding Ctrl+LMB. 💡 Hint: If you are unhappy with the selection, a simple RMB will erase your current selection(s). Yes, you can make multiple selections 😀. Once the selection is made, you can return to your Python Console and then get the assignment's point identifiers. selection=v.get('selected') This will actually returns a 1D array like this: You can actually extend the process to select more than one element at once (Ctrl+LMB) while refining the selection removing specific points (Ctrl+Shift+LMB ). After this, it becomes effortless to apply a bunch of processes interactively over your selection variable that holds the index of selected points. Let us replicate a scenario where you automatically refine your initial selection (the car) between ground and non-ground elements. In the viewer that contain the full point cloud, stored in the variable v, I make the following selection selection=v.get('selected') : Then I compute normals for each points. For this, I want to illustrate another key takeaway of using PPTK: The function estimate_normals, which can be used to get a normal for each point based on either a radius search or the k-nearest neighbours. Don’t worry, I will illustrate in-depth these concepts in another guide, but for now, I will run it by using the 6 nearest neighbours to estimate my normals: normals=pptk.estimate_normals(points[selection],k=6,r=np.inf) 💡 Hint: Remember that the selection variable holds the indexes of the points, i.e. the “line number” in our point cloud, starting at 0. Thus, if I want to work only on this point subset, I will pass it as points[selection] . Then, I choose the k-NN method using only the 6 nearest neighbours for each point, by also setting the radius parameter to np.inf which make sure I don’t use it. I could also use both constraints, or set k to -1 if I want to do a pure radius search. This will basically return this: Then, I want to filter AND return the original points' indexes that have a normal not colinear to the Z-axis. I propose to use the following line of code: idx_normals=np.where(abs(normals[...,2])<0.9) 🤓 Note: The normals[...,2], is a NumPy way of saying that I work only on the 3rd column of my 3 x n point matrix, holding the Z attribute of the normals. It is equivalent to normals[:,2]. Then, I take the absolute value as the comparing point because my normals are not oriented (thus can point toward the sky or towards the earth centre), and will only keep the one that answer the condition <0.9, using the function np.where(). To visualise the results, I create a new viewer window object: viewer1=pptk.viewer(points[idx_normals],colors[idx_normals]/65535) As you can see, we also filtered some points part of the car. This is not good 🤨. Thus, we should combine the filtering with another filter that makes sure only the points close to the ground are chosen as host of the normals filtering: idx_ground=np.where(points[...,2]>np.min(points[...,2]+0.3))idx_wronglyfiltered=np.setdiff1d(idx_ground, idx_normals)idx_retained=np.append(idx_normals, idx_wronglyfiltered)viewer2=pptk.viewer(points[idx_retained],colors[idx_retained]/65535) This is nice! And now, you can just explore this powerful way of thinking and combine any filtering (for example playing on the RGB to get away with the remaining grass ...) to create a fully interactive segmentation application. Even better, you can combine it with 3D Deep Learning Classification! Ho-ho! But that is for another time 😉. Finally, I suggest packaging your script into functions so that you can directly reuse part of it as blocks. We can first define a preparedata(), that will take as input any .laspoint cloud, and format it : def preparedata(): input_path="D:/CLOUD/OneDrive/ALL_DATA/GEODATA-ACADEMY/" dataname="2020_Drone_M_Features" point_cloud=lp.file.File(input_path+dataname+".las", mode="r") points = np.vstack((point_cloud.x, point_cloud.y, point_cloud.z) ).transpose() colors = np.vstack((point_cloud.red, point_cloud.green, point_cloud.blue)).transpose() normals = np.vstack((point_cloud.normalx, point_cloud.normaly, point_cloud.normalz)).transpose() return point_cloud,points,colors,normals Then, we write a display function pptkviz, that return a viewer object: def pptkviz(points,colors): v = pptk.viewer(points) v.attributes(colors/65535) v.set(point_size=0.001,bg_color= [0,0,0,0],show_axis=0, show_grid=0) return v Additionally, and as a bonus, here is the function cameraSelector, to get the current parameters of your camera from the opened viewer: def cameraSelector(v): camera=[] camera.append(v.get('eye')) camera.append(v.get('phi')) camera.append(v.get('theta')) camera.append(v.get('r')) return np.concatenate(camera).tolist() And we define the computePCFeatures function to automate the refinement of your interactive segmentation: def computePCFeatures(points, colors, knn=10, radius=np.inf): normals=pptk.estimate_normals(points,knn,radius) idx_ground=np.where(points[...,2]>np.min(points[...,2]+0.3)) idx_normals=np.where(abs(normals[...,2])<0.9) idx_wronglyfiltered=np.setdiff1d(idx_ground, idx_normals) common_filtering=np.append(idx_normals, idx_wronglyfiltered) return points[common_filtering],colors[common_filtering] Et voilà 😁, you now just need to launch your script containing the functions above and start interacting on your selections using computePCFeatures, cameraSelector, and more of your creations: import numpy as npimport laspy as lpimport pptk#Declare all your functions hereif __name__ == "__main__": point_cloud,points,colors,normals=preparedata() viewer1=pptkviz(points,colors,normals) It is then easy to call the script and then use the console as the bench for your experiments. For example, I could save several camera positions and create an animation: cam1=cameraSelector(v)#Change your viewpoint then -->cam2=cameraSelector(v)#Change your viewpoint then -->cam3=cameraSelector(v)#Change your viewpoint then -->cam4=cameraSelector(v)poses = []poses.append(cam1)poses.append(cam2)poses.append(cam3)poses.append(cam4)v.play(poses, 2 * np.arange(4), repeat=True, interp='linear') You just learned how to import, visualize and segment a point cloud composed of 30+ million points! Well done! Interestingly, the interactive selection of point cloud fragments and individual points performed directly on GPU can now be used for point cloud editing and segmentation in real-time. But the path does not end here, and future posts will dive deeper into point cloud spatial analysis, file formats, data structures, segmentation [2–4], animation and deep learning [1]. We will especially look into how to manage big point cloud data as defined in the article below. towardsdatascience.com My contributions aim to condense actionable information so you can start from scratch to build 3D automation systems for your projects. You can get started today by taking a formation at the Geodata Academy. learngeodata.eu 1. Poux, F., & J.-J Ponciano. (2020). Self-Learning Ontology For Instance Segmentation Of 3d Indoor Point Cloud. ISPRS Int. Arch. of Pho. & Rem. XLIII-B2, 309–316; https://doi.org/10.5194/isprs-archives-XLIII-B2–2020–309–2020 2. Poux, F., & Billen, R. (2019). Voxel-based 3D point cloud semantic segmentation: unsupervised geometric and relationship featuring vs deep learning methods. ISPRS International Journal of Geo-Information. 8(5), 213; https://doi.org/10.3390/ijgi8050213 3. Poux, F., Neuville, R., Nys, G.-A., & Billen, R. (2018). 3D Point Cloud Semantic Modelling: Integrated Framework for Indoor Spaces and Furniture. Remote Sensing, 10(9), 1412. https://doi.org/10.3390/rs10091412 4. Poux, F., Neuville, R., Van Wersch, L., Nys, G.-A., & Billen, R. (2017). 3D Point Clouds in Archaeology: Advances in Acquisition, Processing and Knowledge Integration Applied to Quasi-Planar Objects. Geosciences, 7(4), 96. https://doi.org/10.3390/GEOSCIENCES7040096
[ { "code": null, "e": 464, "s": 172, "text": "Data visualisation is a big enchilada 🌶️: by making a graphical representation of information using visual elements, we can best present and understand trends, outliers, and patterns in data. And you guessed it: with 3D point cloud datasets representing real-world shapes, it is mandatory 🙂." }, { "code": null, "e": 773, "s": 464, "text": "However, when collected from a laser scanner or 3D reconstruction techniques such as Photogrammetry, point clouds are usually too dense for classical rendering. In many cases, the datasets will far exceed the 10+ million mark, making them impractical for classical visualisation libraries such as Matplotlib." }, { "code": null, "e": 1096, "s": 773, "text": "This means that we often need to go out of our Python script (thus using an I/O function to write our data to a file) and visualise it externally, which can become a super cumbersome process 🤯. I will not lie, that is pretty much what I did the first year of my thesis to try and guess the outcome of specific algorithms🥴." }, { "code": null, "e": 1456, "s": 1096, "text": "Would it not be neat to visualise these point clouds directly within your script? Even better, connecting the visual feedback to the script? Imagine, now with the iPhone 12 Pro having a LiDAR; you could create a full online application! Good news, there is a way to accomplish this, without leaving the comfort of your Python Environment and IDE. ☕ and ready?" }, { "code": null, "e": 1708, "s": 1456, "text": "In the previous article below, we saw how to set up an environment with Anaconda easily and how to use the IDE Spyder to manage your code. I recommend continuing in this fashion if you set yourself up to becoming a fully-fledge python app developer 😆." }, { "code": null, "e": 1731, "s": 1708, "text": "towardsdatascience.com" }, { "code": null, "e": 2007, "s": 1731, "text": "If you are using Jupyter Notebook or Google Colab, the script may need some tweaking to make the visualisation back-end work, but deliver unstable performances. If you want to stay on these IDE, I recommend looking at the alternatives to the chosen libraries given in Step 4." }, { "code": null, "e": 2291, "s": 2007, "text": "I illustrated point cloud processing and meshing over a 3D dataset obtained by using photogrammetry and aerial LiDAR from Open Topography in previous tutorials. I will skip the details on LiDAR I/O covered in the article below, and jump right to using the efficient .las file format." }, { "code": null, "e": 2314, "s": 2291, "text": "towardsdatascience.com" }, { "code": null, "e": 2555, "s": 2314, "text": "Only this time, we will use an aerial Drone dataset. It was obtained through photogrammetry making a small DJI Phantom Pro 4 fly on our University campus, gathering some images and running a photogrammetric reconstruction as explained here." }, { "code": null, "e": 2835, "s": 2555, "text": "🤓 Note: For this how-to guide, you can use the point cloud in this repository, that I already filtered and translated so that you are in the optimal conditions. If you want to visualize and play with it beforehand without installing anything, you can check out the webGL version." }, { "code": null, "e": 2965, "s": 2835, "text": "We first import necessary libraries within the script (NumPy and LasPy), and load the .las file in a variable called point_cloud." }, { "code": null, "e": 3123, "s": 2965, "text": "import numpy as npimport laspy as lpinput_path=\"D:/CLOUD/POUX/ALL_DATA/\"dataname=\"2020_Drone_M\"point_cloud=lp.file.File(input_path+dataname+\".las\", mode=\"r\")" }, { "code": null, "e": 3422, "s": 3123, "text": "Nice, we are almost ready! What is great, is that the LasPy library also give a structure to the point_cloud variable, and we can use straightforward methods to get, for example, X, Y, Z, Red, Blue and Green fields. Let us do this to separate coordinates from colours, and put them in NumPy arrays:" }, { "code": null, "e": 3586, "s": 3422, "text": "points = np.vstack((point_cloud.x, point_cloud.y, point_cloud.z)).transpose()colors = np.vstack((point_cloud.red, point_cloud.green, point_cloud.blue)).transpose()" }, { "code": null, "e": 3725, "s": 3586, "text": "🤓 Note: We use a vertical stack method from NumPy, and we have to transpose it to get from (n x 3) to a (3 x n) matrix of the point cloud." }, { "code": null, "e": 3919, "s": 3725, "text": "If your dataset is too heavy, or you feel like you want to experiment on a subsampled version, I encourage you the check out the article below that give you several ways to achieve such a task:" }, { "code": null, "e": 3942, "s": 3919, "text": "towardsdatascience.com" }, { "code": null, "e": 4005, "s": 3942, "text": "Or the following formation for extensive point cloud training:" }, { "code": null, "e": 4021, "s": 4005, "text": "learngeodata.eu" }, { "code": null, "e": 4147, "s": 4021, "text": "For convenience, and if you have a point cloud that exceeds 100 million points, we can just quickly slice your dataset using:" }, { "code": null, "e": 4199, "s": 4147, "text": "factor=10decimated_points_random = points[::factor]" }, { "code": null, "e": 4304, "s": 4199, "text": "🤓 Note: Running this will keep 1 row every 10 rows, thus dividing the original point cloud's size by 10." }, { "code": null, "e": 4766, "s": 4304, "text": "Now, let us choose how we want to visualise our point cloud. I will be honest, here: while visualisation alone is great to avoid cumbersome I/O operations, having the ability to include some visual interaction and processing tools within Python is a great addition! Therefore, the solution that I push is using a point cloud processing toolkit that permits exactly this and more. I will still give you alternatives if you want to explore other possibilities ⚖️." }, { "code": null, "e": 5110, "s": 4766, "text": "The PPTK package has a 3-d point cloud viewer that directly takes a 3-column NumPy array as input and can interactively visualize 10 to 100 million points. It reduces the number of points that needs rendering in each frame by using an octree to cull points outside the view frustum and to approximate groups of faraway points as single points." }, { "code": null, "e": 5184, "s": 5110, "text": "To get started, you can simply install the library using the Pip manager:" }, { "code": null, "e": 5201, "s": 5184, "text": "pip install pptk" }, { "code": null, "e": 5294, "s": 5201, "text": "Then you can visualise your previously createdpointsvariable from the point cloud by typing:" }, { "code": null, "e": 5347, "s": 5294, "text": "import pptkimport numpy as npv = pptk.viewer(points)" }, { "code": null, "e": 5436, "s": 5347, "text": "Don’t you think we are missing some colours? Let us solve this by typing in the console:" }, { "code": null, "e": 5463, "s": 5436, "text": "v.attributes(colors/65535)" }, { "code": null, "e": 5595, "s": 5463, "text": "🤓 Note: Our colour values are coded on 16bits from the .las file. We need the values in a [0,1] interval; thus, we divide by 65535." }, { "code": null, "e": 5757, "s": 5595, "text": "That is way better! But what if we also want to visualise additional attributes? Well, you just link your attributes to your path, and it will update on the fly." }, { "code": null, "e": 5920, "s": 5757, "text": "💡 Hint: Do not maximize the size of the window to keep a nice framerate over 30 FPS. The goal is to have the best execution runtime while having a readable script" }, { "code": null, "e": 6119, "s": 5920, "text": "You can also parameterize your window to show each attributes regarding a certain colour ramp, managing the point size, putting the background black and not displaying the grid and axis information:" }, { "code": null, "e": 6205, "s": 6119, "text": "v.color_map('cool')v.set(point_size=0.001,bg_color=[0,0,0,0],show_axis=0,show_grid=0)" }, { "code": null, "e": 6398, "s": 6205, "text": "For anybody wondering for an excellent alternative to read and display point clouds in Python, I recommend Open3D. You can use the Pip package manager as well to install the necessary library:" }, { "code": null, "e": 6417, "s": 6398, "text": "pip install open3d" }, { "code": null, "e": 6526, "s": 6417, "text": "We already used Open3d in the tutorial below, if you want to extend your knowledge on 3D meshing operations:" }, { "code": null, "e": 6549, "s": 6526, "text": "towardsdatascience.com" }, { "code": null, "e": 6690, "s": 6549, "text": "This will install Open3D on your machine, and you will then be able to read and display your point clouds by executing the following script:" }, { "code": null, "e": 6931, "s": 6690, "text": "import open3d as o3dpcd = o3d.geometry.PointCloud()pcd.points = o3d.utility.Vector3dVector(points)pcd.colors = o3d.utility.Vector3dVector(colors/65535)pcd.normals = o3d.utility.Vector3dVector(normals)o3d.visualization.draw_geometries([pcd])" }, { "code": null, "e": 7074, "s": 6931, "text": "Open3D is actually growing, and you can have some fun ways to display your point cloud to fill eventual holes like creating a voxel structure:" }, { "code": null, "e": 7202, "s": 7074, "text": "voxel_grid = o3d.geometry.VoxelGrid.create_from_point_cloud(pcd,voxel_size=0.40)o3d.visualization.draw_geometries([voxel_grid])" }, { "code": null, "e": 7582, "s": 7202, "text": "🤓 Note: Why is Open3d not the choice at this point? If you work with datasets under 50 million points, then it is what I would recommend. If you need to have interactive visualization above this threshold, I recommend either sampling the dataset for visual purposes, or using PPTK which is more efficient for visualizing as you have the octree structure created for this purpose." }, { "code": null, "e": 8172, "s": 7582, "text": "If you would like to enable simple and interactive exploration of point cloud data, regardless of which sensor was used to generate it or what the use case is, I suggest you look into Pyntcloud, or PyPotree. These will allow you to visualise the point cloud in your notebook, but beware of the performances! Pyntcloud actually rely on Matplotlib, and PyPotree demands I/O operations; thus, both are actually not super-efficient. Nevertheless, I wanted to mention them because for small point clouds and simple experiment in Google Colab, you can integrate the visualisation. Some examples:" }, { "code": null, "e": 8519, "s": 8172, "text": "### PyntCloud ###conda install pyntcloud -c conda-forgefrom pyntcloud import PyntCloudpointcloud = PyntCloud.from_file(\"example.ply\")pointcloud.plot()### PyntCloud ###pip install pypotreeimport pypotree import numpy as npxyz = np.random.random((100000,3))cloudpath = pypotree.generate_cloud_for_display(xyz)pypotree.display_cloud_colab(cloudpath)" }, { "code": null, "e": 8724, "s": 8519, "text": "Back to PPTK. To make an interactive selection, say the car on the parking lot, I will move my camera top view (shortcut is 7), and I will make a selection dragging a rectangle selection holding Ctrl+LMB." }, { "code": null, "e": 8863, "s": 8724, "text": "💡 Hint: If you are unhappy with the selection, a simple RMB will erase your current selection(s). Yes, you can make multiple selections 😀." }, { "code": null, "e": 8978, "s": 8863, "text": "Once the selection is made, you can return to your Python Console and then get the assignment's point identifiers." }, { "code": null, "e": 9006, "s": 8978, "text": "selection=v.get('selected')" }, { "code": null, "e": 9055, "s": 9006, "text": "This will actually returns a 1D array like this:" }, { "code": null, "e": 9215, "s": 9055, "text": "You can actually extend the process to select more than one element at once (Ctrl+LMB) while refining the selection removing specific points (Ctrl+Shift+LMB )." }, { "code": null, "e": 9363, "s": 9215, "text": "After this, it becomes effortless to apply a bunch of processes interactively over your selection variable that holds the index of selected points." }, { "code": null, "e": 9495, "s": 9363, "text": "Let us replicate a scenario where you automatically refine your initial selection (the car) between ground and non-ground elements." }, { "code": null, "e": 9631, "s": 9495, "text": "In the viewer that contain the full point cloud, stored in the variable v, I make the following selection selection=v.get('selected') :" }, { "code": null, "e": 10037, "s": 9631, "text": "Then I compute normals for each points. For this, I want to illustrate another key takeaway of using PPTK: The function estimate_normals, which can be used to get a normal for each point based on either a radius search or the k-nearest neighbours. Don’t worry, I will illustrate in-depth these concepts in another guide, but for now, I will run it by using the 6 nearest neighbours to estimate my normals:" }, { "code": null, "e": 10099, "s": 10037, "text": "normals=pptk.estimate_normals(points[selection],k=6,r=np.inf)" }, { "code": null, "e": 10574, "s": 10099, "text": "💡 Hint: Remember that the selection variable holds the indexes of the points, i.e. the “line number” in our point cloud, starting at 0. Thus, if I want to work only on this point subset, I will pass it as points[selection] . Then, I choose the k-NN method using only the 6 nearest neighbours for each point, by also setting the radius parameter to np.inf which make sure I don’t use it. I could also use both constraints, or set k to -1 if I want to do a pure radius search." }, { "code": null, "e": 10607, "s": 10574, "text": "This will basically return this:" }, { "code": null, "e": 10762, "s": 10607, "text": "Then, I want to filter AND return the original points' indexes that have a normal not colinear to the Z-axis. I propose to use the following line of code:" }, { "code": null, "e": 10808, "s": 10762, "text": "idx_normals=np.where(abs(normals[...,2])<0.9)" }, { "code": null, "e": 11238, "s": 10808, "text": "🤓 Note: The normals[...,2], is a NumPy way of saying that I work only on the 3rd column of my 3 x n point matrix, holding the Z attribute of the normals. It is equivalent to normals[:,2]. Then, I take the absolute value as the comparing point because my normals are not oriented (thus can point toward the sky or towards the earth centre), and will only keep the one that answer the condition <0.9, using the function np.where()." }, { "code": null, "e": 11301, "s": 11238, "text": "To visualise the results, I create a new viewer window object:" }, { "code": null, "e": 11368, "s": 11301, "text": "viewer1=pptk.viewer(points[idx_normals],colors[idx_normals]/65535)" }, { "code": null, "e": 11605, "s": 11368, "text": "As you can see, we also filtered some points part of the car. This is not good 🤨. Thus, we should combine the filtering with another filter that makes sure only the points close to the ground are chosen as host of the normals filtering:" }, { "code": null, "e": 11847, "s": 11605, "text": "idx_ground=np.where(points[...,2]>np.min(points[...,2]+0.3))idx_wronglyfiltered=np.setdiff1d(idx_ground, idx_normals)idx_retained=np.append(idx_normals, idx_wronglyfiltered)viewer2=pptk.viewer(points[idx_retained],colors[idx_retained]/65535)" }, { "code": null, "e": 12186, "s": 11847, "text": "This is nice! And now, you can just explore this powerful way of thinking and combine any filtering (for example playing on the RGB to get away with the remaining grass ...) to create a fully interactive segmentation application. Even better, you can combine it with 3D Deep Learning Classification! Ho-ho! But that is for another time 😉." }, { "code": null, "e": 12393, "s": 12186, "text": "Finally, I suggest packaging your script into functions so that you can directly reuse part of it as blocks. We can first define a preparedata(), that will take as input any .laspoint cloud, and format it :" }, { "code": null, "e": 12901, "s": 12393, "text": "def preparedata(): input_path=\"D:/CLOUD/OneDrive/ALL_DATA/GEODATA-ACADEMY/\" dataname=\"2020_Drone_M_Features\" point_cloud=lp.file.File(input_path+dataname+\".las\", mode=\"r\") points = np.vstack((point_cloud.x, point_cloud.y, point_cloud.z) ).transpose() colors = np.vstack((point_cloud.red, point_cloud.green, point_cloud.blue)).transpose() normals = np.vstack((point_cloud.normalx, point_cloud.normaly, point_cloud.normalz)).transpose() return point_cloud,points,colors,normals" }, { "code": null, "e": 12973, "s": 12901, "text": "Then, we write a display function pptkviz, that return a viewer object:" }, { "code": null, "e": 13145, "s": 12973, "text": "def pptkviz(points,colors): v = pptk.viewer(points) v.attributes(colors/65535) v.set(point_size=0.001,bg_color= [0,0,0,0],show_axis=0, show_grid=0) return v" }, { "code": null, "e": 13281, "s": 13145, "text": "Additionally, and as a bonus, here is the function cameraSelector, to get the current parameters of your camera from the opened viewer:" }, { "code": null, "e": 13483, "s": 13281, "text": "def cameraSelector(v): camera=[] camera.append(v.get('eye')) camera.append(v.get('phi')) camera.append(v.get('theta')) camera.append(v.get('r')) return np.concatenate(camera).tolist()" }, { "code": null, "e": 13589, "s": 13483, "text": "And we define the computePCFeatures function to automate the refinement of your interactive segmentation:" }, { "code": null, "e": 14001, "s": 13589, "text": "def computePCFeatures(points, colors, knn=10, radius=np.inf): normals=pptk.estimate_normals(points,knn,radius) idx_ground=np.where(points[...,2]>np.min(points[...,2]+0.3)) idx_normals=np.where(abs(normals[...,2])<0.9) idx_wronglyfiltered=np.setdiff1d(idx_ground, idx_normals) common_filtering=np.append(idx_normals, idx_wronglyfiltered) return points[common_filtering],colors[common_filtering]" }, { "code": null, "e": 14195, "s": 14001, "text": "Et voilà 😁, you now just need to launch your script containing the functions above and start interacting on your selections using computePCFeatures, cameraSelector, and more of your creations:" }, { "code": null, "e": 14394, "s": 14195, "text": "import numpy as npimport laspy as lpimport pptk#Declare all your functions hereif __name__ == \"__main__\": point_cloud,points,colors,normals=preparedata() viewer1=pptkviz(points,colors,normals)" }, { "code": null, "e": 14565, "s": 14394, "text": "It is then easy to call the script and then use the console as the bench for your experiments. For example, I could save several camera positions and create an animation:" }, { "code": null, "e": 14890, "s": 14565, "text": "cam1=cameraSelector(v)#Change your viewpoint then -->cam2=cameraSelector(v)#Change your viewpoint then -->cam3=cameraSelector(v)#Change your viewpoint then -->cam4=cameraSelector(v)poses = []poses.append(cam1)poses.append(cam2)poses.append(cam3)poses.append(cam4)v.play(poses, 2 * np.arange(4), repeat=True, interp='linear')" }, { "code": null, "e": 15468, "s": 14890, "text": "You just learned how to import, visualize and segment a point cloud composed of 30+ million points! Well done! Interestingly, the interactive selection of point cloud fragments and individual points performed directly on GPU can now be used for point cloud editing and segmentation in real-time. But the path does not end here, and future posts will dive deeper into point cloud spatial analysis, file formats, data structures, segmentation [2–4], animation and deep learning [1]. We will especially look into how to manage big point cloud data as defined in the article below." }, { "code": null, "e": 15491, "s": 15468, "text": "towardsdatascience.com" }, { "code": null, "e": 15699, "s": 15491, "text": "My contributions aim to condense actionable information so you can start from scratch to build 3D automation systems for your projects. You can get started today by taking a formation at the Geodata Academy." }, { "code": null, "e": 15715, "s": 15699, "text": "learngeodata.eu" }, { "code": null, "e": 15941, "s": 15715, "text": "1. Poux, F., & J.-J Ponciano. (2020). Self-Learning Ontology For Instance Segmentation Of 3d Indoor Point Cloud. ISPRS Int. Arch. of Pho. & Rem. XLIII-B2, 309–316; https://doi.org/10.5194/isprs-archives-XLIII-B2–2020–309–2020" }, { "code": null, "e": 16196, "s": 15941, "text": "2. Poux, F., & Billen, R. (2019). Voxel-based 3D point cloud semantic segmentation: unsupervised geometric and relationship featuring vs deep learning methods. ISPRS International Journal of Geo-Information. 8(5), 213; https://doi.org/10.3390/ijgi8050213" }, { "code": null, "e": 16409, "s": 16196, "text": "3. Poux, F., Neuville, R., Nys, G.-A., & Billen, R. (2018). 3D Point Cloud Semantic Modelling: Integrated Framework for Indoor Spaces and Furniture. Remote Sensing, 10(9), 1412. https://doi.org/10.3390/rs10091412" } ]
How to Extend an Array After Initialisation in Java? - GeeksforGeeks
05 Aug, 2021 In java, the arrays are immutable i.e if the array is once assigned or instantiated the memory allocated for the array can’t be decreased or increased. But there is one form of a solution in which we can extend the array. Extending an array after initialization: As we can’t modify the array size after the declaration of the array, we can only extend it by initializing a new array and copying the values of the old array to the new array, and then we can assign new values to the array according to the size of the array declared. Below are the examples to show extending the array after initialization. Example 1: Java // java program to demonstrate// extending an arrayimport java.lang.*; class ExtendingArray { public static void main(String[] args) { // initializing string array String[] words = new String[] { "G", "E", "E" }; // allocating space for 5 strings // in the extended array String[] extendWords = new String[5]; // adding new string // at index 3 and 4 extendWords[3] = "K"; extendWords[4] = "S"; // copying the array elements // to new extended array System.arraycopy(words, 0, extendWords, 0, words.length); // printing the extended array // elements for (String str : extendWords) { System.out.print(str); } }} GEEKS Example 2: Java // Java program to demonstrate// extending an array import java.lang.*; class ExtendingArray { public static void extendedArray() { // initializing integers to array int int[] num = new int[] { 1, 2, 3, 4, 5, 6 }; // allocating space for 10 integers int[] extendnum = new int[10]; // adding new integers // at index 6,7,8,9 extendnum[6] = 7; extendnum[7] = 8; extendnum[8] = 9; extendnum[9] = 10; // copying old array to new array System.arraycopy(num, 0, extendnum, 0, num.length); // print the elements of // extended array using for-each for (int str : extendnum) System.out.println(str); } public static void main(String[] args) { // create an instance ExtendingArray exarr = new ExtendingArray(); // extend an array and print them exarr.extendedArray(); }} 1 2 3 4 5 6 7 8 9 10 surinderdawra388 as5853535 Java-Array-Programs Java-Arrays Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java Convert a String to Character array in Java Initializing a List in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 24647, "s": 24619, "text": "\n05 Aug, 2021" }, { "code": null, "e": 24869, "s": 24647, "text": "In java, the arrays are immutable i.e if the array is once assigned or instantiated the memory allocated for the array can’t be decreased or increased. But there is one form of a solution in which we can extend the array." }, { "code": null, "e": 25180, "s": 24869, "text": "Extending an array after initialization: As we can’t modify the array size after the declaration of the array, we can only extend it by initializing a new array and copying the values of the old array to the new array, and then we can assign new values to the array according to the size of the array declared." }, { "code": null, "e": 25253, "s": 25180, "text": "Below are the examples to show extending the array after initialization." }, { "code": null, "e": 25264, "s": 25253, "text": "Example 1:" }, { "code": null, "e": 25269, "s": 25264, "text": "Java" }, { "code": "// java program to demonstrate// extending an arrayimport java.lang.*; class ExtendingArray { public static void main(String[] args) { // initializing string array String[] words = new String[] { \"G\", \"E\", \"E\" }; // allocating space for 5 strings // in the extended array String[] extendWords = new String[5]; // adding new string // at index 3 and 4 extendWords[3] = \"K\"; extendWords[4] = \"S\"; // copying the array elements // to new extended array System.arraycopy(words, 0, extendWords, 0, words.length); // printing the extended array // elements for (String str : extendWords) { System.out.print(str); } }}", "e": 26045, "s": 25269, "text": null }, { "code": null, "e": 26051, "s": 26045, "text": "GEEKS" }, { "code": null, "e": 26063, "s": 26051, "text": "Example 2: " }, { "code": null, "e": 26068, "s": 26063, "text": "Java" }, { "code": "// Java program to demonstrate// extending an array import java.lang.*; class ExtendingArray { public static void extendedArray() { // initializing integers to array int int[] num = new int[] { 1, 2, 3, 4, 5, 6 }; // allocating space for 10 integers int[] extendnum = new int[10]; // adding new integers // at index 6,7,8,9 extendnum[6] = 7; extendnum[7] = 8; extendnum[8] = 9; extendnum[9] = 10; // copying old array to new array System.arraycopy(num, 0, extendnum, 0, num.length); // print the elements of // extended array using for-each for (int str : extendnum) System.out.println(str); } public static void main(String[] args) { // create an instance ExtendingArray exarr = new ExtendingArray(); // extend an array and print them exarr.extendedArray(); }}", "e": 27002, "s": 26068, "text": null }, { "code": null, "e": 27023, "s": 27002, "text": "1\n2\n3\n4\n5\n6\n7\n8\n9\n10" }, { "code": null, "e": 27042, "s": 27025, "text": "surinderdawra388" }, { "code": null, "e": 27052, "s": 27042, "text": "as5853535" }, { "code": null, "e": 27072, "s": 27052, "text": "Java-Array-Programs" }, { "code": null, "e": 27084, "s": 27072, "text": "Java-Arrays" }, { "code": null, "e": 27089, "s": 27084, "text": "Java" }, { "code": null, "e": 27103, "s": 27089, "text": "Java Programs" }, { "code": null, "e": 27108, "s": 27103, "text": "Java" }, { "code": null, "e": 27206, "s": 27108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27215, "s": 27206, "text": "Comments" }, { "code": null, "e": 27228, "s": 27215, "text": "Old Comments" }, { "code": null, "e": 27279, "s": 27228, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27309, "s": 27279, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27340, "s": 27309, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27359, "s": 27340, "text": "Interfaces in Java" }, { "code": null, "e": 27391, "s": 27359, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27435, "s": 27391, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 27463, "s": 27435, "text": "Initializing a List in Java" }, { "code": null, "e": 27489, "s": 27463, "text": "Java Programming Examples" }, { "code": null, "e": 27523, "s": 27489, "text": "Convert Double to Integer in Java" } ]
GATE | GATE CS 2012 | Question 51 - GeeksforGeeks
28 Jun, 2021 Table A Id Name Age ---------------- 12 Arun 60 15 Shreya 24 99 Rohit 11 Table B Id Name Age ---------------- 15 Shreya 24 25 Hari 40 98 Rohit 20 99 Rohit 11 Table C Id Phone Area ----------------- 10 2200 02 99 2100 01 Consider the above tables A, B and C. How many tuples does the result of the following SQL query contains? SELECT A.id FROM A WHERE A.age > ALL (SELECT B.age FROM B WHERE B. name = "arun") (A) 4(B) 3(C) 0(D) 1Answer: (B)Explanation: The meaning of “ALL” is the A.Age should be greater than all the values returned by the subquery. There is no entry with name “arun” in table B. So the subquery will return NULL. If a subquery returns NULL, then the condition becomes true for all rows of A (See this for details). So all rows of table A are selected. Source: https://www.geeksforgeeks.org/database-management-system-set-3/Quiz of this Question GATE-CS-2012 GATE-GATE CS 2012 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-IT-2004 | Question 66 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2010 | Question 24 GATE | GATE CS 2011 | Question 65 GATE | GATE CS 2011 | Question 7 GATE | GATE-CS-2004 | Question 3 GATE | GATE-IT-2004 | Question 71 GATE | GATE-CS-2006 | Question 49 GATE | GATE CS 2019 | Question 27
[ { "code": null, "e": 24352, "s": 24324, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24626, "s": 24352, "text": "Table A\nId Name Age\n----------------\n12 Arun 60\n15 Shreya 24\n99 Rohit 11\n\n\nTable B\nId Name Age\n----------------\n15 Shreya 24\n25 Hari 40\n98 Rohit 20\n99 Rohit 11\n\n\nTable C\nId Phone Area\n-----------------\n10 2200 02 \n99 2100 01" }, { "code": null, "e": 24733, "s": 24626, "text": "Consider the above tables A, B and C. How many tuples does the result of the following SQL query contains?" }, { "code": null, "e": 24867, "s": 24733, "text": "SELECT A.id \nFROM A \nWHERE A.age > ALL (SELECT B.age \n FROM B \n WHERE B. name = \"arun\") \n" }, { "code": null, "e": 25229, "s": 24867, "text": "(A) 4(B) 3(C) 0(D) 1Answer: (B)Explanation: The meaning of “ALL” is the A.Age should be greater than all the values returned by the subquery. There is no entry with name “arun” in table B. So the subquery will return NULL. If a subquery returns NULL, then the condition becomes true for all rows of A (See this for details). So all rows of table A are selected." }, { "code": null, "e": 25322, "s": 25229, "text": "Source: https://www.geeksforgeeks.org/database-management-system-set-3/Quiz of this Question" }, { "code": null, "e": 25335, "s": 25322, "text": "GATE-CS-2012" }, { "code": null, "e": 25353, "s": 25335, "text": "GATE-GATE CS 2012" }, { "code": null, "e": 25358, "s": 25353, "text": "GATE" }, { "code": null, "e": 25456, "s": 25358, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25490, "s": 25456, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 25532, "s": 25490, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25574, "s": 25532, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 25608, "s": 25574, "text": "GATE | GATE CS 2010 | Question 24" }, { "code": null, "e": 25642, "s": 25608, "text": "GATE | GATE CS 2011 | Question 65" }, { "code": null, "e": 25675, "s": 25642, "text": "GATE | GATE CS 2011 | Question 7" }, { "code": null, "e": 25708, "s": 25675, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25742, "s": 25708, "text": "GATE | GATE-IT-2004 | Question 71" }, { "code": null, "e": 25776, "s": 25742, "text": "GATE | GATE-CS-2006 | Question 49" } ]
PHP date_create() Function
The date_create() function is an alias of the DateTime::__construct, a constructor of the DateTime class. Where, a DateTime class represents date and time in PHP. The date_create() function accepts a date time string and time zone (optional) as parameters and, creates a DateTime object accordingly. By default, this function creates an object of the current date/time date_create([$date_time, $timezone]); date_time (Optional) This is the date/time string (in supported formats) for which you need to create a DateTime object. timezone (Optional) This represents the timezone of the given time. PHP date_create() function returns the created DateTime object. This function was first introduced in PHP Version 5.2.0 and, works with all the later versions. Try out following example in here, we are creating a DateTime object, formatting it, and printing the result − <?php //Date string $date_string = "25-09-1989"; //Creating a DateTime object $date_time_Obj = date_create($date_string); //formatting the date to print it $format = date_format($date_time_Obj, "d-m-Y H:i:s"); print($format); ?> This will produce following result − 25-09-1989 00:00:00 Following example creates date formats it as date and time separately − <?php $dateString = '11-06-2012 12:50 GMT'; $dateTime = date_create($dateString); print("Date: ".$dateTime->format('d-m-y')); print("\n"); print("Time: ".$dateTime->format('H:i:s')); ?> This will produce following result − Date: 11-06-12 Time: 12:50:00 Following example creates a DateTime object by specifying both date string and time zone − <?php //Date string $date_string = "25-09-1989, 07:32:41 GMT"; //Creating a DateTime object $tz = 'Indian/Mahe'; $date_time_Obj = date_create($date_string, new DateTimeZone($tz)); //formatting the date to print it $format = date_format($date_time_Obj, "d-m-y H:i:s"); print($format); ?> This will produce following result − Array 25-09-89 07:32:41 In the following example we are invoking the date_create() function without any parameters. It creates the object of the current time − <?php //Creating a DateTime object $date_time_Obj = date_create(); //formatting the date to print it print(date_format($date_time_Obj, "d-m-y H:i:s")); ?> This produces the following result − 04-05-20 12:41:31 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 3057, "s": 2757, "text": "The date_create() function is an alias of the DateTime::__construct, a constructor of the DateTime class. Where, a DateTime class represents date and time in PHP. The date_create() function accepts a date time string and time zone (optional) as parameters and, creates a DateTime object accordingly." }, { "code": null, "e": 3126, "s": 3057, "text": "By default, this function creates an object of the current date/time" }, { "code": null, "e": 3165, "s": 3126, "text": "date_create([$date_time, $timezone]);\n" }, { "code": null, "e": 3186, "s": 3165, "text": "date_time (Optional)" }, { "code": null, "e": 3286, "s": 3186, "text": "This is the date/time string (in supported formats) for which you need to create a DateTime object." }, { "code": null, "e": 3306, "s": 3286, "text": "timezone (Optional)" }, { "code": null, "e": 3355, "s": 3306, "text": " This represents the timezone of the given time." }, { "code": null, "e": 3419, "s": 3355, "text": "PHP date_create() function returns the created DateTime object." }, { "code": null, "e": 3515, "s": 3419, "text": "This function was first introduced in PHP Version 5.2.0 and, works with all the later versions." }, { "code": null, "e": 3626, "s": 3515, "text": "Try out following example in here, we are creating a DateTime object, formatting it, and printing the result −" }, { "code": null, "e": 3876, "s": 3626, "text": "<?php\n //Date string\n $date_string = \"25-09-1989\";\n //Creating a DateTime object\n $date_time_Obj = date_create($date_string);\n //formatting the date to print it\n $format = date_format($date_time_Obj, \"d-m-Y H:i:s\");\n print($format);\n?>" }, { "code": null, "e": 3913, "s": 3876, "text": "This will produce following result −" }, { "code": null, "e": 3934, "s": 3913, "text": "25-09-1989 00:00:00\n" }, { "code": null, "e": 4006, "s": 3934, "text": "Following example creates date formats it as date and time separately −" }, { "code": null, "e": 4209, "s": 4006, "text": "<?php\n $dateString = '11-06-2012 12:50 GMT';\n $dateTime = date_create($dateString);\n print(\"Date: \".$dateTime->format('d-m-y')); \n print(\"\\n\");\n print(\"Time: \".$dateTime->format('H:i:s')); \n?>" }, { "code": null, "e": 4246, "s": 4209, "text": "This will produce following result −" }, { "code": null, "e": 4277, "s": 4246, "text": "Date: 11-06-12\nTime: 12:50:00\n" }, { "code": null, "e": 4368, "s": 4277, "text": "Following example creates a DateTime object by specifying both date string and time zone −" }, { "code": null, "e": 4682, "s": 4368, "text": "<?php\n //Date string\n $date_string = \"25-09-1989, 07:32:41 GMT\";\n //Creating a DateTime object\n $tz = 'Indian/Mahe'; \n $date_time_Obj = date_create($date_string, new DateTimeZone($tz));\n //formatting the date to print it\n $format = date_format($date_time_Obj, \"d-m-y H:i:s\");\n print($format);\n?>" }, { "code": null, "e": 4719, "s": 4682, "text": "This will produce following result −" }, { "code": null, "e": 4744, "s": 4719, "text": "Array\n25-09-89 07:32:41\n" }, { "code": null, "e": 4880, "s": 4744, "text": "In the following example we are invoking the date_create() function without any parameters. It creates the object of the current time −" }, { "code": null, "e": 5047, "s": 4880, "text": "<?php\n //Creating a DateTime object\n $date_time_Obj = date_create();\n //formatting the date to print it\n print(date_format($date_time_Obj, \"d-m-y H:i:s\"));\n?>" }, { "code": null, "e": 5084, "s": 5047, "text": "This produces the following result −" }, { "code": null, "e": 5103, "s": 5084, "text": "04-05-20 12:41:31\n" }, { "code": null, "e": 5136, "s": 5103, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 5152, "s": 5136, "text": " Malhar Lathkar" }, { "code": null, "e": 5185, "s": 5152, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 5196, "s": 5185, "text": " Syed Raza" }, { "code": null, "e": 5231, "s": 5196, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5248, "s": 5231, "text": " Frahaan Hussain" }, { "code": null, "e": 5281, "s": 5248, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 5296, "s": 5281, "text": " Nivedita Jain" }, { "code": null, "e": 5331, "s": 5296, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 5343, "s": 5331, "text": " Azaz Patel" }, { "code": null, "e": 5378, "s": 5343, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5406, "s": 5378, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5413, "s": 5406, "text": " Print" }, { "code": null, "e": 5424, "s": 5413, "text": " Add Notes" } ]
4-bit binary Adder-Subtractor - GeeksforGeeks
21 Oct, 2021 In Digital Circuits, A Binary Adder-Subtractor is one which is capable of both addition and subtraction of binary numbers in one circuit itself. The operation being performed depends upon the binary value the control signal holds. It is one of the components of the ALU (Arithmetic Logic Unit). This Circuit Requires prerequisite knowledge of Exor Gate, Binary Addition and Subtraction, Full Adder. Lets consider two 4-bit binary numbers A and B as inputs to the Digital Circuit for the operation with digits A0 A1 A2 A3 for A B0 B1 B2 B3 for B The circuit consists of 4 full adders since we are performing operation on 4-bit numbers. There is a control line K that holds a binary value of either 0 or 1 which determines that the operation being carried out is addition or subtraction. As shown in the figure, the first full adder has control line directly as its input(input carry Cin), The input A0 (The least significant bit of A) is directly input in the full adder. The third input is the exor of B0 and K. The two outputs produced are Sum/Difference (S0) and Carry (C0). If the value of K (Control line) is 1, the output of B0(exor)K=B0′(Complement B0). Thus the operation would be A+(B0′). Now 2’s complement subtraction for two numbers A and B is given by A+B’. This suggests that when K=1, the operation being performed on the four bit numbers is subtraction. Similarly If the Value of K=0, B0 (exor) K=B0. The operation is A+B which is simple binary addition. This suggests that When K=0, the operation being performed on the four bit numbers is addition. Then C0 is serially passed to the second full adder as one of it’s outputs. The sum/difference S0 is recorded as the least significant bit of the sum/difference. A1, A2, A3 are direct inputs to the second, third and fourth full adders. Then the third input is the B1, B2, B3 EXORed with K to the second, third and fourth full adder respectively. The carry C1, C2 are serially passed to the successive full adder as one of the inputs. C3 becomes the total carry to the sum/difference. S1, S2, S3 are recorded to form the result with S0. For an n-bit binary adder-subtractor, we use n number of full adders. Example: Lets take two 3 bit numbers A=010 and B=011 and input them in the full adder with both values of control lines. For K=0: B0(exor)K=B0 and C0=K=0 Thus from first full adder = A0+B0 = 0+1 = 1, S0=1 C1=0 Similarly, S1=0 with C2=1 S2=1 and C2=0 Thus, A = 010 =2 B = 011 = 3 Sum = 0101 = 5 For K=1 B0(exor)K=B0' and C0=k=1 Thus S0=1 and C1=0 Similarly S1=1 and C2=0 S2=1 and c3=0 Thus, A = 010 = 2 B = 011 = 3 Sum(Difference) = 1111 = -1 kevampatel moha20fcs12 Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Shift Registers in Digital Logic Difference between Unipolar, Polar and Bipolar Line Coding Schemes Shift Micro-Operations in Computer Architecture Flip-flop types, their Conversion and Applications Counters in Digital Logic Layers of OSI Model ACID Properties in DBMS TCP/IP Model Page Replacement Algorithms in Operating Systems Types of Operating Systems
[ { "code": null, "e": 23970, "s": 23942, "text": "\n21 Oct, 2021" }, { "code": null, "e": 24266, "s": 23970, "text": "In Digital Circuits, A Binary Adder-Subtractor is one which is capable of both addition and subtraction of binary numbers in one circuit itself. The operation being performed depends upon the binary value the control signal holds. It is one of the components of the ALU (Arithmetic Logic Unit). " }, { "code": null, "e": 24371, "s": 24266, "text": "This Circuit Requires prerequisite knowledge of Exor Gate, Binary Addition and Subtraction, Full Adder. " }, { "code": null, "e": 24482, "s": 24371, "text": "Lets consider two 4-bit binary numbers A and B as inputs to the Digital Circuit for the operation with digits " }, { "code": null, "e": 24519, "s": 24482, "text": "A0 A1 A2 A3 for A\nB0 B1 B2 B3 for B " }, { "code": null, "e": 24761, "s": 24519, "text": "The circuit consists of 4 full adders since we are performing operation on 4-bit numbers. There is a control line K that holds a binary value of either 0 or 1 which determines that the operation being carried out is addition or subtraction. " }, { "code": null, "e": 25055, "s": 24763, "text": "As shown in the figure, the first full adder has control line directly as its input(input carry Cin), The input A0 (The least significant bit of A) is directly input in the full adder. The third input is the exor of B0 and K. The two outputs produced are Sum/Difference (S0) and Carry (C0). " }, { "code": null, "e": 25348, "s": 25055, "text": "If the value of K (Control line) is 1, the output of B0(exor)K=B0′(Complement B0). Thus the operation would be A+(B0′). Now 2’s complement subtraction for two numbers A and B is given by A+B’. This suggests that when K=1, the operation being performed on the four bit numbers is subtraction. " }, { "code": null, "e": 25546, "s": 25348, "text": "Similarly If the Value of K=0, B0 (exor) K=B0. The operation is A+B which is simple binary addition. This suggests that When K=0, the operation being performed on the four bit numbers is addition. " }, { "code": null, "e": 26083, "s": 25546, "text": "Then C0 is serially passed to the second full adder as one of it’s outputs. The sum/difference S0 is recorded as the least significant bit of the sum/difference. A1, A2, A3 are direct inputs to the second, third and fourth full adders. Then the third input is the B1, B2, B3 EXORed with K to the second, third and fourth full adder respectively. The carry C1, C2 are serially passed to the successive full adder as one of the inputs. C3 becomes the total carry to the sum/difference. S1, S2, S3 are recorded to form the result with S0. " }, { "code": null, "e": 26154, "s": 26083, "text": "For an n-bit binary adder-subtractor, we use n number of full adders. " }, { "code": null, "e": 26277, "s": 26154, "text": "Example: Lets take two 3 bit numbers A=010 and B=011 and input them in the full adder with both values of control lines. " }, { "code": null, "e": 26618, "s": 26277, "text": "For K=0:\nB0(exor)K=B0 and C0=K=0\n\nThus from first full adder\n= A0+B0\n= 0+1\n= 1, \n\nS0=1\nC1=0\nSimilarly, \nS1=0 with C2=1\nS2=1 and C2=0\n \nThus, \nA = 010 =2 \nB = 011 = 3\nSum = 0101 = 5\n\n\nFor K=1\nB0(exor)K=B0' and C0=k=1\n\nThus \nS0=1 and C1=0\nSimilarly \nS1=1 and C2=0\nS2=1 and c3=0\n\nThus, \nA = 010 = 2\nB = 011 = 3 \nSum(Difference) = 1111 = -1 " }, { "code": null, "e": 26631, "s": 26620, "text": "kevampatel" }, { "code": null, "e": 26643, "s": 26631, "text": "moha20fcs12" }, { "code": null, "e": 26678, "s": 26643, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 26686, "s": 26678, "text": "GATE CS" }, { "code": null, "e": 26784, "s": 26686, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26817, "s": 26784, "text": "Shift Registers in Digital Logic" }, { "code": null, "e": 26884, "s": 26817, "text": "Difference between Unipolar, Polar and Bipolar Line Coding Schemes" }, { "code": null, "e": 26932, "s": 26884, "text": "Shift Micro-Operations in Computer Architecture" }, { "code": null, "e": 26983, "s": 26932, "text": "Flip-flop types, their Conversion and Applications" }, { "code": null, "e": 27009, "s": 26983, "text": "Counters in Digital Logic" }, { "code": null, "e": 27029, "s": 27009, "text": "Layers of OSI Model" }, { "code": null, "e": 27053, "s": 27029, "text": "ACID Properties in DBMS" }, { "code": null, "e": 27066, "s": 27053, "text": "TCP/IP Model" }, { "code": null, "e": 27115, "s": 27066, "text": "Page Replacement Algorithms in Operating Systems" } ]
How do we compare two dictionaries in Python?
dicts in python are also classes. These have the __eq__method overridden, so you can use the == operator to check if 2 dictionaries are equal or not. a = {'foo': 10, 'bar': 150} b = {'foo': 10, 'bar': 150} print(a == b) This will give the output − True If you want a list of shared items in the 2 dictionaries, you can use sets and the & operator on them to get that. a = {'foo': 10, 'bar': 150} b = {'foo': 10, 'baz': 50} shared = set(a.items()) & set(b.items()) print(shared) This will give the output − {('foo', 10)}
[ { "code": null, "e": 1213, "s": 1062, "text": "dicts in python are also classes. These have the __eq__method overridden, so you can use the == operator to check if 2 dictionaries are equal or not. " }, { "code": null, "e": 1283, "s": 1213, "text": "a = {'foo': 10, 'bar': 150}\nb = {'foo': 10, 'bar': 150}\nprint(a == b)" }, { "code": null, "e": 1311, "s": 1283, "text": "This will give the output −" }, { "code": null, "e": 1316, "s": 1311, "text": "True" }, { "code": null, "e": 1432, "s": 1316, "text": "If you want a list of shared items in the 2 dictionaries, you can use sets and the & operator on them to get that. " }, { "code": null, "e": 1543, "s": 1432, "text": "a = {'foo': 10, 'bar': 150}\nb = {'foo': 10, 'baz': 50}\n\nshared = set(a.items()) & set(b.items())\nprint(shared)" }, { "code": null, "e": 1571, "s": 1543, "text": "This will give the output −" }, { "code": null, "e": 1585, "s": 1571, "text": "{('foo', 10)}" } ]
Difference between Static Constructor and Instance Constructor in C#
A static constructor is a constructor declared using static modifier. It is the first block of code executed in a class. With that, a static constructor executes only once in the life cycle of class. Instance constructor initializes instance data. Instance constructor is called when an object of class is created. The following example shows the difference between static and instance constructor in C#. Live Demo using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Difference { class Demo { static int val1; int val2; static Demo() { Console.WriteLine("This is Static Constructor"); val1 = 70; } public Demo(int val3) { Console.WriteLine("This is Instance Constructor"); val2 = val3; } private void show() { Console.WriteLine("First Value = " + val1); Console.WriteLine("Second Value = " + val2); } static void Main(string[] args) { Demo d1 = new Demo(110); Demo d2 = new Demo(200); d1.show(); d2.show(); Console.ReadKey(); } } } This is Static Constructor This is Instance Constructor This is Instance Constructor First Value = 70 Second Value = 110 First Value = 70 Second Value = 200
[ { "code": null, "e": 1262, "s": 1062, "text": "A static constructor is a constructor declared using static modifier. It is the first block of code executed in a class. With that, a static constructor executes only once in the life cycle of class." }, { "code": null, "e": 1377, "s": 1262, "text": "Instance constructor initializes instance data. Instance constructor is called when an object of class is created." }, { "code": null, "e": 1467, "s": 1377, "text": "The following example shows the difference between static and instance constructor in C#." }, { "code": null, "e": 1478, "s": 1467, "text": " Live Demo" }, { "code": null, "e": 2204, "s": 1478, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nnamespace Difference {\n class Demo {\n static int val1;\n int val2;\n static Demo() {\n Console.WriteLine(\"This is Static Constructor\");\n val1 = 70;\n }\n public Demo(int val3) {\n Console.WriteLine(\"This is Instance Constructor\");\n val2 = val3;\n }\n private void show() {\n Console.WriteLine(\"First Value = \" + val1);\n Console.WriteLine(\"Second Value = \" + val2);\n }\n static void Main(string[] args) {\n Demo d1 = new Demo(110);\n Demo d2 = new Demo(200);\n d1.show();\n d2.show();\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 2361, "s": 2204, "text": "This is Static Constructor\nThis is Instance Constructor\nThis is Instance Constructor\nFirst Value = 70\nSecond Value = 110\nFirst Value = 70\nSecond Value = 200" } ]
Program for Bisection Method
06 Apr, 2021 Given a function f(x) on floating number x and two numbers ‘a’ and ‘b’ such that f(a)*f(b) < 0 and f(x) is continuous in [a, b]. Here f(x) represents algebraic or transcendental equation. Find root of function in interval [a, b] (Or find a value of x such that f(x) is 0). Example: Input: A function of x, for example x3 - x2 + 2. And two values: a = -200 and b = 300 such that f(a)*f(b) < 0, i.e., f(a) and f(b) have opposite signs. Output: The value of root is : -1.0025 OR any other value with allowed deviation from root. What are Algebraic and Transcendental functions? Algebraic function are the one which can be represented in the form of polynomials like f(x) = a1x3 + a2x2 + ..... + e where aa1, a2, ... are constants and x is a variable. Transcendental function are non algebraic functions, for example f(x) = sin(x)*x – 3 or f(x) = ex + x2 or f(x) = ln(x) + x .... What is Bisection Method? The method is also called the interval halving method, the binary search method or the dichotomy method. This method is used to find root of an equation in a given interval that is value of ‘x’ for which f(x) = 0 . The method is based on The Intermediate Value Theorem which states that if f(x) is a continuous function and there are two real numbers a and b such that f(a)*f(b) 0 and f(b) < 0), then it is guaranteed that it has at least one root between them.Assumptions: f(x) is a continuous function in interval [a, b]f(a) * f(b) < 0 f(x) is a continuous function in interval [a, b] f(a) * f(b) < 0 Steps: Find middle point c= (a + b)/2 .If f(c) == 0, then c is the root of the solution.Else f(c) != 0If value f(a)*f(c) < 0 then root lies between a and c. So we recur for a and cElse If f(b)*f(c) < 0 then root lies between b and c. So we recur b and c.Else given function doesn’t follow one of assumptions. Find middle point c= (a + b)/2 . If f(c) == 0, then c is the root of the solution. Else f(c) != 0If value f(a)*f(c) < 0 then root lies between a and c. So we recur for a and cElse If f(b)*f(c) < 0 then root lies between b and c. So we recur b and c.Else given function doesn’t follow one of assumptions. If value f(a)*f(c) < 0 then root lies between a and c. So we recur for a and cElse If f(b)*f(c) < 0 then root lies between b and c. So we recur b and c.Else given function doesn’t follow one of assumptions. If value f(a)*f(c) < 0 then root lies between a and c. So we recur for a and c Else If f(b)*f(c) < 0 then root lies between b and c. So we recur b and c. Else given function doesn’t follow one of assumptions. Since root may be a floating point number, we repeat above steps while difference between a and b is less than a value ? (A very small value). Below is implementation of above steps. C++ Java Python3 C# PHP Javascript // C++ program for implementation of Bisection Method for// solving equations#include<bits/stdc++.h>using namespace std;#define EPSILON 0.01 // An example function whose solution is determined using// Bisection Method. The function is x^3 - x^2 + 2double func(double x){ return x*x*x - x*x + 2;} // Prints root of func(x) with error of EPSILONvoid bisection(double a, double b){ if (func(a) * func(b) >= 0) { cout << "You have not assumed right a and b\n"; return; } double c = a; while ((b-a) >= EPSILON) { // Find middle point c = (a+b)/2; // Check if middle point is root if (func(c) == 0.0) break; // Decide the side to repeat the steps else if (func(c)*func(a) < 0) b = c; else a = c; } cout << "The value of root is : " << c;} // Driver program to test above functionint main(){ // Initial values assumed double a =-200, b = 300; bisection(a, b); return 0;} // Java program for implementation of Bisection Method// for solving equationsclass GFG{ static final float EPSILON = (float)0.01; // An example function whose solution is determined using // Bisection Method. The function is x^3 - x^2 + 2 static double func(double x) { return x*x*x - x*x + 2; } // Prints root of func(x) with error of EPSILON static void bisection(double a, double b) { if (func(a) * func(b) >= 0) { System.out.println("You have not assumed" + " right a and b"); return; } double c = a; while ((b-a) >= EPSILON) { // Find middle point c = (a+b)/2; // Check if middle point is root if (func(c) == 0.0) break; // Decide the side to repeat the steps else if (func(c)*func(a) < 0) b = c; else a = c; } //prints value of c upto 4 decimal places System.out.printf("The value of root is : %.4f" ,c); } // Driver program to test above function public static void main(String[] args) { // Initial values assumed double a =-200, b = 300; bisection(a, b); } // This code is contributed by Nirmal Patel} # Python program for implementation# of Bisection Method for# solving equations # An example function whose# solution is determined using# Bisection Method.# The function is x^3 - x^2 + 2def func(x): return x*x*x - x*x + 2 # Prints root of func(x)# with error of EPSILONdef bisection(a,b): if (func(a) * func(b) >= 0): print("You have not assumed right a and b\n") return c = a while ((b-a) >= 0.01): # Find middle point c = (a+b)/2 # Check if middle point is root if (func(c) == 0.0): break # Decide the side to repeat the steps if (func(c)*func(a) < 0): b = c else: a = c print("The value of root is : ","%.4f"%c) # Driver code# Initial values assumeda =-200b = 300bisection(a, b) # This code is contributed# by Anant Agarwal. // C# program for implementation// of Bisection Method for// solving equationsusing System; class GFG{static float EPSILON = (float)0.01; // An example function whose// solution is determined using// Bisection Method. The function// is x^3 - x^2 + 2static double func(double x){ return x * x * x - x * x + 2;} // Prints root of func(x)// with error of EPSILONstatic void bisection(double a, double b){ if (func(a) * func(b) >= 0) { Console.WriteLine("You have not assumed" + " right a and b"); return; } double c = a; while ((b - a) >= EPSILON) { // Find middle point c = (a + b) / 2; // Check if middle // point is root if (func(c) == 0.0) break; // Decide the side // to repeat the steps else if (func(c) * func(a) < 0) b = c; else a = c; } // prints value of c // upto 4 decimal places Console.WriteLine("The value of " + "root is : "+ c);} // Driver Codestatic public void Main (){ // Initial values assumed double a = -200, b = 300; bisection(a, b);}} // This code is contributed by ajit <?php// PHP program for implementation// of Bisection Method for solving// equations$EPSILON = 0.01; // An example function whose// solution is determined// using Bisection Method.// The function is x^3 - x^2 + 2function func($x){ return $x * $x * $x - $x * $x + 2;} // Prints root of func(x)// with error of EPSILONfunction bisection($a, $b){ global $EPSILON; if (func($a) * func($b) >= 0) { echo "You have not assumed " . "right a and b","\n"; return; } $c = $a; while (($b - $a) >= $EPSILON) { // Find middle point $c = ($a + $b) / 2; // Check if middle // point is root if (func($c) == 0.0) break; // Decide the side to // repeat the steps else if (func($c) * func($a) < 0) $b = $c; else $a = $c; } echo "The value of root is : " , $c;} // Driver Code // Initial values assumed$a =-200;$b = 300;bisection($a, $b); // This code is contributed by ajit?> <script> // JavaScript program for implementation// of Bisection Method for// solving equations let EPSILON = 0.01; // An example function whose solution is determined using // Bisection Method. The function is x^3 - x^2 + 2 function func(x) { return x*x*x - x*x + 2; } // Prints root of func(x) with error of EPSILON function bisection(a, b) { if (func(a) * func(b) >= 0) { document.write("You have not assumed" + " right a and b"); return; } let c = a; while ((b-a) >= EPSILON) { // Find middle point c = (a+b)/2; // Check if middle point is root if (func(c) == 0.0) break; // Decide the side to repeat the steps else if (func(c)*func(a) < 0) b = c; else a = c; } //prints value of c upto 4 decimal places document.write("The value of " + "root is : "+ c.toFixed(4)); } // Driver program // Initial values assumed let a =-200, b = 300; bisection(a, b); // This code is contributed by susmitakundugoaldanga.</script> Output: The value of root is : -1.0025 Time complexity :- Time complexity of this method depends on the assumed values and the function. What are pros and cons? Advantage of the bisection method is that it is guaranteed to be converged. Disadvantage of bisection method is that it cannot detect multiple roots.In general, Bisection method is used to get an initial rough approximation of solution. Then faster converging methods are used to find the solution. We will soon be discussing other methods to solve algebraic and transcendental equationsReferences: Introductory Methods of Numerical Analysis by S.S. Sastry https://en.wikipedia.org/wiki/Bisection_methodThis article is contributed by Abhiraj Smit. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Nims972 jit_t susmitakundugoaldanga Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes Prime Numbers Program to find GCD or HCF of two numbers Minimum number of jumps to reach end Find minimum number of coins that make a given value The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Program for Decimal to Binary Conversion
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Apr, 2021" }, { "code": null, "e": 338, "s": 54, "text": "Given a function f(x) on floating number x and two numbers ‘a’ and ‘b’ such that f(a)*f(b) < 0 and f(x) is continuous in [a, b]. Here f(x) represents algebraic or transcendental equation. Find root of function in interval [a, b] (Or find a value of x such that f(x) is 0). Example: " }, { "code": null, "e": 624, "s": 338, "text": "Input: A function of x, for example x3 - x2 + 2. \n And two values: a = -200 and b = 300 such that\n f(a)*f(b) < 0, i.e., f(a) and f(b) have\n opposite signs.\nOutput: The value of root is : -1.0025\n OR any other value with allowed\n deviation from root." }, { "code": null, "e": 1476, "s": 624, "text": "What are Algebraic and Transcendental functions? Algebraic function are the one which can be represented in the form of polynomials like f(x) = a1x3 + a2x2 + ..... + e where aa1, a2, ... are constants and x is a variable. Transcendental function are non algebraic functions, for example f(x) = sin(x)*x – 3 or f(x) = ex + x2 or f(x) = ln(x) + x .... What is Bisection Method? The method is also called the interval halving method, the binary search method or the dichotomy method. This method is used to find root of an equation in a given interval that is value of ‘x’ for which f(x) = 0 . The method is based on The Intermediate Value Theorem which states that if f(x) is a continuous function and there are two real numbers a and b such that f(a)*f(b) 0 and f(b) < 0), then it is guaranteed that it has at least one root between them.Assumptions: " }, { "code": null, "e": 1540, "s": 1476, "text": "f(x) is a continuous function in interval [a, b]f(a) * f(b) < 0" }, { "code": null, "e": 1589, "s": 1540, "text": "f(x) is a continuous function in interval [a, b]" }, { "code": null, "e": 1605, "s": 1589, "text": "f(a) * f(b) < 0" }, { "code": null, "e": 1614, "s": 1605, "text": "Steps: " }, { "code": null, "e": 1916, "s": 1614, "text": "Find middle point c= (a + b)/2 .If f(c) == 0, then c is the root of the solution.Else f(c) != 0If value f(a)*f(c) < 0 then root lies between a and c. So we recur for a and cElse If f(b)*f(c) < 0 then root lies between b and c. So we recur b and c.Else given function doesn’t follow one of assumptions." }, { "code": null, "e": 1949, "s": 1916, "text": "Find middle point c= (a + b)/2 ." }, { "code": null, "e": 1999, "s": 1949, "text": "If f(c) == 0, then c is the root of the solution." }, { "code": null, "e": 2220, "s": 1999, "text": "Else f(c) != 0If value f(a)*f(c) < 0 then root lies between a and c. So we recur for a and cElse If f(b)*f(c) < 0 then root lies between b and c. So we recur b and c.Else given function doesn’t follow one of assumptions." }, { "code": null, "e": 2427, "s": 2220, "text": "If value f(a)*f(c) < 0 then root lies between a and c. So we recur for a and cElse If f(b)*f(c) < 0 then root lies between b and c. So we recur b and c.Else given function doesn’t follow one of assumptions." }, { "code": null, "e": 2506, "s": 2427, "text": "If value f(a)*f(c) < 0 then root lies between a and c. So we recur for a and c" }, { "code": null, "e": 2581, "s": 2506, "text": "Else If f(b)*f(c) < 0 then root lies between b and c. So we recur b and c." }, { "code": null, "e": 2636, "s": 2581, "text": "Else given function doesn’t follow one of assumptions." }, { "code": null, "e": 2781, "s": 2636, "text": "Since root may be a floating point number, we repeat above steps while difference between a and b is less than a value ? (A very small value). " }, { "code": null, "e": 2823, "s": 2781, "text": "Below is implementation of above steps. " }, { "code": null, "e": 2827, "s": 2823, "text": "C++" }, { "code": null, "e": 2832, "s": 2827, "text": "Java" }, { "code": null, "e": 2840, "s": 2832, "text": "Python3" }, { "code": null, "e": 2843, "s": 2840, "text": "C#" }, { "code": null, "e": 2847, "s": 2843, "text": "PHP" }, { "code": null, "e": 2858, "s": 2847, "text": "Javascript" }, { "code": "// C++ program for implementation of Bisection Method for// solving equations#include<bits/stdc++.h>using namespace std;#define EPSILON 0.01 // An example function whose solution is determined using// Bisection Method. The function is x^3 - x^2 + 2double func(double x){ return x*x*x - x*x + 2;} // Prints root of func(x) with error of EPSILONvoid bisection(double a, double b){ if (func(a) * func(b) >= 0) { cout << \"You have not assumed right a and b\\n\"; return; } double c = a; while ((b-a) >= EPSILON) { // Find middle point c = (a+b)/2; // Check if middle point is root if (func(c) == 0.0) break; // Decide the side to repeat the steps else if (func(c)*func(a) < 0) b = c; else a = c; } cout << \"The value of root is : \" << c;} // Driver program to test above functionint main(){ // Initial values assumed double a =-200, b = 300; bisection(a, b); return 0;}", "e": 3861, "s": 2858, "text": null }, { "code": "// Java program for implementation of Bisection Method// for solving equationsclass GFG{ static final float EPSILON = (float)0.01; // An example function whose solution is determined using // Bisection Method. The function is x^3 - x^2 + 2 static double func(double x) { return x*x*x - x*x + 2; } // Prints root of func(x) with error of EPSILON static void bisection(double a, double b) { if (func(a) * func(b) >= 0) { System.out.println(\"You have not assumed\" + \" right a and b\"); return; } double c = a; while ((b-a) >= EPSILON) { // Find middle point c = (a+b)/2; // Check if middle point is root if (func(c) == 0.0) break; // Decide the side to repeat the steps else if (func(c)*func(a) < 0) b = c; else a = c; } //prints value of c upto 4 decimal places System.out.printf(\"The value of root is : %.4f\" ,c); } // Driver program to test above function public static void main(String[] args) { // Initial values assumed double a =-200, b = 300; bisection(a, b); } // This code is contributed by Nirmal Patel}", "e": 5213, "s": 3861, "text": null }, { "code": "# Python program for implementation# of Bisection Method for# solving equations # An example function whose# solution is determined using# Bisection Method.# The function is x^3 - x^2 + 2def func(x): return x*x*x - x*x + 2 # Prints root of func(x)# with error of EPSILONdef bisection(a,b): if (func(a) * func(b) >= 0): print(\"You have not assumed right a and b\\n\") return c = a while ((b-a) >= 0.01): # Find middle point c = (a+b)/2 # Check if middle point is root if (func(c) == 0.0): break # Decide the side to repeat the steps if (func(c)*func(a) < 0): b = c else: a = c print(\"The value of root is : \",\"%.4f\"%c) # Driver code# Initial values assumeda =-200b = 300bisection(a, b) # This code is contributed# by Anant Agarwal.", "e": 6082, "s": 5213, "text": null }, { "code": "// C# program for implementation// of Bisection Method for// solving equationsusing System; class GFG{static float EPSILON = (float)0.01; // An example function whose// solution is determined using// Bisection Method. The function// is x^3 - x^2 + 2static double func(double x){ return x * x * x - x * x + 2;} // Prints root of func(x)// with error of EPSILONstatic void bisection(double a, double b){ if (func(a) * func(b) >= 0) { Console.WriteLine(\"You have not assumed\" + \" right a and b\"); return; } double c = a; while ((b - a) >= EPSILON) { // Find middle point c = (a + b) / 2; // Check if middle // point is root if (func(c) == 0.0) break; // Decide the side // to repeat the steps else if (func(c) * func(a) < 0) b = c; else a = c; } // prints value of c // upto 4 decimal places Console.WriteLine(\"The value of \" + \"root is : \"+ c);} // Driver Codestatic public void Main (){ // Initial values assumed double a = -200, b = 300; bisection(a, b);}} // This code is contributed by ajit", "e": 7318, "s": 6082, "text": null }, { "code": "<?php// PHP program for implementation// of Bisection Method for solving// equations$EPSILON = 0.01; // An example function whose// solution is determined// using Bisection Method.// The function is x^3 - x^2 + 2function func($x){ return $x * $x * $x - $x * $x + 2;} // Prints root of func(x)// with error of EPSILONfunction bisection($a, $b){ global $EPSILON; if (func($a) * func($b) >= 0) { echo \"You have not assumed \" . \"right a and b\",\"\\n\"; return; } $c = $a; while (($b - $a) >= $EPSILON) { // Find middle point $c = ($a + $b) / 2; // Check if middle // point is root if (func($c) == 0.0) break; // Decide the side to // repeat the steps else if (func($c) * func($a) < 0) $b = $c; else $a = $c; } echo \"The value of root is : \" , $c;} // Driver Code // Initial values assumed$a =-200;$b = 300;bisection($a, $b); // This code is contributed by ajit?>", "e": 8350, "s": 7318, "text": null }, { "code": "<script> // JavaScript program for implementation// of Bisection Method for// solving equations let EPSILON = 0.01; // An example function whose solution is determined using // Bisection Method. The function is x^3 - x^2 + 2 function func(x) { return x*x*x - x*x + 2; } // Prints root of func(x) with error of EPSILON function bisection(a, b) { if (func(a) * func(b) >= 0) { document.write(\"You have not assumed\" + \" right a and b\"); return; } let c = a; while ((b-a) >= EPSILON) { // Find middle point c = (a+b)/2; // Check if middle point is root if (func(c) == 0.0) break; // Decide the side to repeat the steps else if (func(c)*func(a) < 0) b = c; else a = c; } //prints value of c upto 4 decimal places document.write(\"The value of \" + \"root is : \"+ c.toFixed(4)); } // Driver program // Initial values assumed let a =-200, b = 300; bisection(a, b); // This code is contributed by susmitakundugoaldanga.</script>", "e": 9614, "s": 8350, "text": null }, { "code": null, "e": 9623, "s": 9614, "text": "Output: " }, { "code": null, "e": 9654, "s": 9623, "text": "The value of root is : -1.0025" }, { "code": null, "e": 10449, "s": 9654, "text": "Time complexity :- Time complexity of this method depends on the assumed values and the function. What are pros and cons? Advantage of the bisection method is that it is guaranteed to be converged. Disadvantage of bisection method is that it cannot detect multiple roots.In general, Bisection method is used to get an initial rough approximation of solution. Then faster converging methods are used to find the solution. We will soon be discussing other methods to solve algebraic and transcendental equationsReferences: Introductory Methods of Numerical Analysis by S.S. Sastry https://en.wikipedia.org/wiki/Bisection_methodThis article is contributed by Abhiraj Smit. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 10457, "s": 10449, "text": "Nims972" }, { "code": null, "e": 10463, "s": 10457, "text": "jit_t" }, { "code": null, "e": 10485, "s": 10463, "text": "susmitakundugoaldanga" }, { "code": null, "e": 10498, "s": 10485, "text": "Mathematical" }, { "code": null, "e": 10511, "s": 10498, "text": "Mathematical" }, { "code": null, "e": 10609, "s": 10511, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10633, "s": 10609, "text": "Merge two sorted arrays" }, { "code": null, "e": 10654, "s": 10633, "text": "Operators in C / C++" }, { "code": null, "e": 10676, "s": 10654, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 10690, "s": 10676, "text": "Prime Numbers" }, { "code": null, "e": 10732, "s": 10690, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 10769, "s": 10732, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 10822, "s": 10769, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 10865, "s": 10822, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 10897, "s": 10865, "text": "Algorithm to solve Rubik's Cube" } ]
How to change font size depending on width of container?
03 Aug, 2021 There are various ways of putting some text in a container and having some size to fill that container.There are different methods such as using CSS and jQuery which are explained below. Using CSS property (Viewport width): The vw is a CSS property, to create responsive typography in the HTML file. The viewport is a browser window size. The “text-size” can be set with a “vw” units and you can find an exact number where the text pretty closely fits the container and doesn’t break as you resize the browser window. 1vw = 1% of viewport width. If the viewport is 100cm wide, 1vw is 10cm. Example: <!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title> How to change font size depending on the width of container? </title> <style> h1 { font-size: 8vw; color: green; font-weight: bold; } p { font-size: 3vw; } </style></head> <body> <h1>Geeks for Geeks</h1> <p> Resize the browser window to see how the font size changes. </p></body> </html> Output: On Desktop: On iPad: Using CSS property (Media Queries): You can also use media queries to change the font size of an element on specific screen sizes. The @media rule, which makes it possible to define different style rules for different media types. Example: <!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title> How to change font size depending on width of container? </title> <style> h1 { color: green; } @media screen and (min-width: 601px) { h1 { font-size: 80px; } p { font-size: 40px; } } @media screen and (max-width: 600px) { h1 { font-size: 40px; } p { font-size: 20px; } } </style></head> <body> <h1>Geeks for Geeks</h1> <p> Set the <em>font-size</em> of "h1" to "40px" and <em>paragraph</em> to "20px", when the window's width is "600px" wide or less and when it is "601px" or wider, set the <em>font-size</em> to "80px" and <em>paragraph</em> to "40px". Resize the browser window to see the effect. </p></body> </html> Output: On Desktop: On iPad: Using FitText jQuery plugin: There is a jquery plugin that can make font-sizes flexible on the responsive layout, namely FitText. For instance, one can use the plugin to do scalable text sizes with respect to the container’s width. Example: <!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>H ow to change font size depending on width of c ontainer? </title> <style> h1 { color: green; } </style></head> <body> <h1>Geeks for Geeks</h1> <p> Resize the browser window to see how the font size scales. </p> <script type="text/javascript" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/textFit.js"> </script> <script type="text/javascript"> textFit(document.querySelector("h1")); </script></body> </html> Output: On Desktop: On iPad: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. CSS-Misc HTML-Misc jQuery-Misc Picked CSS HTML JQuery Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Aug, 2021" }, { "code": null, "e": 240, "s": 53, "text": "There are various ways of putting some text in a container and having some size to fill that container.There are different methods such as using CSS and jQuery which are explained below." }, { "code": null, "e": 571, "s": 240, "text": "Using CSS property (Viewport width): The vw is a CSS property, to create responsive typography in the HTML file. The viewport is a browser window size. The “text-size” can be set with a “vw” units and you can find an exact number where the text pretty closely fits the container and doesn’t break as you resize the browser window." }, { "code": null, "e": 643, "s": 571, "text": "1vw = 1% of viewport width. If the viewport is 100cm wide, 1vw is 10cm." }, { "code": null, "e": 652, "s": 643, "text": "Example:" }, { "code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title> How to change font size depending on the width of container? </title> <style> h1 { font-size: 8vw; color: green; font-weight: bold; } p { font-size: 3vw; } </style></head> <body> <h1>Geeks for Geeks</h1> <p> Resize the browser window to see how the font size changes. </p></body> </html>", "e": 1171, "s": 652, "text": null }, { "code": null, "e": 1179, "s": 1171, "text": "Output:" }, { "code": null, "e": 1191, "s": 1179, "text": "On Desktop:" }, { "code": null, "e": 1200, "s": 1191, "text": "On iPad:" }, { "code": null, "e": 1431, "s": 1200, "text": "Using CSS property (Media Queries): You can also use media queries to change the font size of an element on specific screen sizes. The @media rule, which makes it possible to define different style rules for different media types." }, { "code": null, "e": 1440, "s": 1431, "text": "Example:" }, { "code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title> How to change font size depending on width of container? </title> <style> h1 { color: green; } @media screen and (min-width: 601px) { h1 { font-size: 80px; } p { font-size: 40px; } } @media screen and (max-width: 600px) { h1 { font-size: 40px; } p { font-size: 20px; } } </style></head> <body> <h1>Geeks for Geeks</h1> <p> Set the <em>font-size</em> of \"h1\" to \"40px\" and <em>paragraph</em> to \"20px\", when the window's width is \"600px\" wide or less and when it is \"601px\" or wider, set the <em>font-size</em> to \"80px\" and <em>paragraph</em> to \"40px\". Resize the browser window to see the effect. </p></body> </html>", "e": 2474, "s": 1440, "text": null }, { "code": null, "e": 2482, "s": 2474, "text": "Output:" }, { "code": null, "e": 2494, "s": 2482, "text": "On Desktop:" }, { "code": null, "e": 2503, "s": 2494, "text": "On iPad:" }, { "code": null, "e": 2735, "s": 2503, "text": "Using FitText jQuery plugin: There is a jquery plugin that can make font-sizes flexible on the responsive layout, namely FitText. For instance, one can use the plugin to do scalable text sizes with respect to the container’s width." }, { "code": null, "e": 2744, "s": 2735, "text": "Example:" }, { "code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title>H ow to change font size depending on width of c ontainer? </title> <style> h1 { color: green; } </style></head> <body> <h1>Geeks for Geeks</h1> <p> Resize the browser window to see how the font size scales. </p> <script type=\"text/javascript\" src=\"https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/textFit.js\"> </script> <script type=\"text/javascript\"> textFit(document.querySelector(\"h1\")); </script></body> </html>", "e": 3370, "s": 2744, "text": null }, { "code": null, "e": 3378, "s": 3370, "text": "Output:" }, { "code": null, "e": 3390, "s": 3378, "text": "On Desktop:" }, { "code": null, "e": 3399, "s": 3390, "text": "On iPad:" }, { "code": null, "e": 3667, "s": 3399, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 3676, "s": 3667, "text": "CSS-Misc" }, { "code": null, "e": 3686, "s": 3676, "text": "HTML-Misc" }, { "code": null, "e": 3698, "s": 3686, "text": "jQuery-Misc" }, { "code": null, "e": 3705, "s": 3698, "text": "Picked" }, { "code": null, "e": 3709, "s": 3705, "text": "CSS" }, { "code": null, "e": 3714, "s": 3709, "text": "HTML" }, { "code": null, "e": 3721, "s": 3714, "text": "JQuery" }, { "code": null, "e": 3738, "s": 3721, "text": "Web Technologies" }, { "code": null, "e": 3765, "s": 3738, "text": "Web technologies Questions" }, { "code": null, "e": 3770, "s": 3765, "text": "HTML" }, { "code": null, "e": 3868, "s": 3770, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3905, "s": 3868, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 3944, "s": 3905, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3983, "s": 3944, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 4047, "s": 3983, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 4108, "s": 4047, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 4132, "s": 4108, "text": "REST API (Introduction)" }, { "code": null, "e": 4185, "s": 4132, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 4245, "s": 4185, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 4306, "s": 4245, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Python | Tensorflow nn.tanh()
11 Jan, 2022 Tensorflow is an open-source machine learning library developed by Google. One of its applications is to develop deep neural networks. The module tensorflow.nn provides support for many basic neural network operations. One of the many activation functions is the hyperbolic tangent function (also known as tanh) which is defined as .The hyperbolic tangent function outputs in the range (-1, 1), thus mapping strongly negative inputs to negative values. Unlike the sigmoid function, only near-zero values are mapped to near-zero outputs, and this solves the “vanishing gradients” problem to some extent. The hyperbolic tangent function is differentiable at every point and its derivative comes out to be . Since the expression involves the tanh function, its value can be reused to make the backward propagation faster. Despite the lower chances of the network getting “stuck” when compared with the sigmoid function, the hyperbolic tangent function still suffers from “vanishing gradients”. Rectified Linear Unit (ReLU) can be used to overcome this problem. The function tf.nn.tanh() [alias tf.tanh] provides support for the hyperbolic tangent function in Tensorflow. Syntax: tf.nn.tanh(x, name=None) or tf.tanh(x, name=None)Parameters: x: A tensor of any of the following types: float16, float32, double, complex64, or complex128. name (optional): The name for the operation.Return : A tensor with the same type as that of x. Code #1: Python3 # Importing the Tensorflow libraryimport tensorflow as tf # A constant vector of size 6a = tf.constant([1.0, -0.5, 3.4, -2.1, 0.0, -6.5], dtype = tf.float32) # Applying the tanh function and# storing the result in 'b'b = tf.nn.tanh(a, name ='tanh') # Initiating a Tensorflow sessionwith tf.Session() as sess: print('Input type:', a) print('Input:', sess.run(a)) print('Return type:', b) print('Output:', sess.run(b)) Output: Input type: Tensor("Const_2:0", shape=(6, ), dtype=float32) Input: [ 1. -0.5 3.4000001 -2.0999999 0. -6.5 ] Return type: Tensor("tanh_2:0", shape=(6, ), dtype=float32) Output: [ 0.76159418 -0.46211717 0.9977749 -0.97045201 0. -0.99999547] Code #2: Visualization Python3 # Importing the Tensorflow libraryimport tensorflow as tf # Importing the NumPy libraryimport numpy as np # Importing the matplotlib.pyplot functionimport matplotlib.pyplot as plt # A vector of size 15 with values from -5 to 5a = np.linspace(-5, 5, 15) # Applying the tanh function and# storing the result in 'b'b = tf.nn.tanh(a, name ='tanh') # Initiating a Tensorflow sessionwith tf.Session() as sess: print('Input:', a) print('Output:', sess.run(b)) plt.plot(a, sess.run(b), color = 'red', marker = "o") plt.title("tensorflow.nn.tanh") plt.xlabel("X") plt.ylabel("Y") plt.show() Output: Input: [-5. -4.28571429 -3.57142857 -2.85714286 -2.14285714 -1.42857143 -0.71428571 0. 0.71428571 1.42857143 2.14285714 2.85714286 3.57142857 4.28571429 5. ] Output: [-0.9999092 -0.99962119 -0.99842027 -0.99342468 -0.97284617 -0.89137347 -0.61335726 0. 0.61335726 0.89137347 0.97284617 0.99342468 0.99842027 0.99962119 0.9999092 ] sanskar27jain sagar0719kumar sweetyty Tensorflow Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jan, 2022" }, { "code": null, "e": 164, "s": 28, "text": "Tensorflow is an open-source machine learning library developed by Google. One of its applications is to develop deep neural networks. " }, { "code": null, "e": 248, "s": 164, "text": "The module tensorflow.nn provides support for many basic neural network operations." }, { "code": null, "e": 848, "s": 248, "text": "One of the many activation functions is the hyperbolic tangent function (also known as tanh) which is defined as .The hyperbolic tangent function outputs in the range (-1, 1), thus mapping strongly negative inputs to negative values. Unlike the sigmoid function, only near-zero values are mapped to near-zero outputs, and this solves the “vanishing gradients” problem to some extent. The hyperbolic tangent function is differentiable at every point and its derivative comes out to be . Since the expression involves the tanh function, its value can be reused to make the backward propagation faster." }, { "code": null, "e": 1087, "s": 848, "text": "Despite the lower chances of the network getting “stuck” when compared with the sigmoid function, the hyperbolic tangent function still suffers from “vanishing gradients”. Rectified Linear Unit (ReLU) can be used to overcome this problem." }, { "code": null, "e": 1198, "s": 1087, "text": "The function tf.nn.tanh() [alias tf.tanh] provides support for the hyperbolic tangent function in Tensorflow. " }, { "code": null, "e": 1459, "s": 1198, "text": "Syntax: tf.nn.tanh(x, name=None) or tf.tanh(x, name=None)Parameters: x: A tensor of any of the following types: float16, float32, double, complex64, or complex128. name (optional): The name for the operation.Return : A tensor with the same type as that of x. " }, { "code": null, "e": 1470, "s": 1459, "text": "Code #1: " }, { "code": null, "e": 1478, "s": 1470, "text": "Python3" }, { "code": "# Importing the Tensorflow libraryimport tensorflow as tf # A constant vector of size 6a = tf.constant([1.0, -0.5, 3.4, -2.1, 0.0, -6.5], dtype = tf.float32) # Applying the tanh function and# storing the result in 'b'b = tf.nn.tanh(a, name ='tanh') # Initiating a Tensorflow sessionwith tf.Session() as sess: print('Input type:', a) print('Input:', sess.run(a)) print('Return type:', b) print('Output:', sess.run(b))", "e": 1907, "s": 1478, "text": null }, { "code": null, "e": 1916, "s": 1907, "text": "Output: " }, { "code": null, "e": 2193, "s": 1916, "text": "Input type: Tensor(\"Const_2:0\", shape=(6, ), dtype=float32)\nInput: [ 1. -0.5 3.4000001 -2.0999999 0. -6.5 ]\nReturn type: Tensor(\"tanh_2:0\", shape=(6, ), dtype=float32)\nOutput: [ 0.76159418 -0.46211717 0.9977749 -0.97045201 0. -0.99999547]" }, { "code": null, "e": 2218, "s": 2193, "text": "Code #2: Visualization " }, { "code": null, "e": 2226, "s": 2218, "text": "Python3" }, { "code": "# Importing the Tensorflow libraryimport tensorflow as tf # Importing the NumPy libraryimport numpy as np # Importing the matplotlib.pyplot functionimport matplotlib.pyplot as plt # A vector of size 15 with values from -5 to 5a = np.linspace(-5, 5, 15) # Applying the tanh function and# storing the result in 'b'b = tf.nn.tanh(a, name ='tanh') # Initiating a Tensorflow sessionwith tf.Session() as sess: print('Input:', a) print('Output:', sess.run(b)) plt.plot(a, sess.run(b), color = 'red', marker = \"o\") plt.title(\"tensorflow.nn.tanh\") plt.xlabel(\"X\") plt.ylabel(\"Y\") plt.show()", "e": 2830, "s": 2226, "text": null }, { "code": null, "e": 2839, "s": 2830, "text": "Output: " }, { "code": null, "e": 3222, "s": 2839, "text": "Input: [-5. -4.28571429 -3.57142857 -2.85714286 -2.14285714 -1.42857143\n -0.71428571 0. 0.71428571 1.42857143 2.14285714 2.85714286\n 3.57142857 4.28571429 5. ]\nOutput: [-0.9999092 -0.99962119 -0.99842027 -0.99342468 -0.97284617 -0.89137347\n -0.61335726 0. 0.61335726 0.89137347 0.97284617 0.99342468\n 0.99842027 0.99962119 0.9999092 ]" }, { "code": null, "e": 3238, "s": 3224, "text": "sanskar27jain" }, { "code": null, "e": 3253, "s": 3238, "text": "sagar0719kumar" }, { "code": null, "e": 3262, "s": 3253, "text": "sweetyty" }, { "code": null, "e": 3273, "s": 3262, "text": "Tensorflow" }, { "code": null, "e": 3280, "s": 3273, "text": "Python" }, { "code": null, "e": 3378, "s": 3280, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3396, "s": 3378, "text": "Python Dictionary" }, { "code": null, "e": 3438, "s": 3396, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3460, "s": 3438, "text": "Enumerate() in Python" }, { "code": null, "e": 3495, "s": 3460, "text": "Read a file line by line in Python" }, { "code": null, "e": 3521, "s": 3495, "text": "Python String | replace()" }, { "code": null, "e": 3553, "s": 3521, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3582, "s": 3553, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3609, "s": 3582, "text": "Python Classes and Objects" }, { "code": null, "e": 3639, "s": 3609, "text": "Iterate over a list in Python" } ]
Python | Pandas.apply()
03 Jul, 2018 Pandas.apply allow the users to pass a function and apply it on every single value of the Pandas series. It comes as a huge improvement for the pandas library as this function helps to segregate data according to the conditions required due to which it is efficiently used in data science and machine learning. Installation:Import the Pandas module into the python file using the following commands on the terminal: pip install pandas To read the csv file and squeezing it into a pandas series following commands are used: import pandas as pd s = pd.read_csv("stock.csv", squeeze=True) Syntax: s.apply(func, convert_dtype=True, args=()) Parameters: func: .apply takes a function and applies it to all values of pandas series.convert_dtype: Convert dtype as per the function’s operation.args=(): Additional arguments to pass to function instead of series.Return Type: Pandas Series after applied function/operation. For the dataset, click here to download. Example #1: The following example passes a function and checks the value of each element in series and returns low, normal or High accordingly. import pandas as pd # reading csvs = pd.read_csv("stock.csv", squeeze = True) # defining function to check pricedef fun(num): if num<200: return "Low" elif num>= 200 and num<400: return "Normal" else: return "High" # passing function to apply and storing returned series in newnew = s.apply(fun) # printing first 3 elementprint(new.head(3)) # printing elements somewhere near the middle of seriesprint(new[1400], new[1500], new[1600]) # printing last 3 elementsprint(new.tail(3)) Output: Example #2: In the following example, a temporary anonymous function is made in .apply itself using lambda. It adds 5 to each value in series and returns a new series. import pandas as pds = pd.read_csv("stock.csv", squeeze = True) # adding 5 to each valuenew = s.apply(lambda num : num + 5) # printing first 5 elements of old and new seriesprint(s.head(), '\n', new.head()) # printing last 5 elements of old and new seriesprint('\n\n', s.tail(), '\n', new.tail()) Output: 0 50.12 1 54.10 2 54.65 3 52.38 4 52.95 Name: Stock Price, dtype: float64 0 55.12 1 59.10 2 59.65 3 57.38 4 57.95 Name: Stock Price, dtype: float64 3007 772.88 3008 771.07 3009 773.18 3010 771.61 3011 782.22 Name: Stock Price, dtype: float64 3007 777.88 3008 776.07 3009 778.18 3010 776.61 3011 787.22 Name: Stock Price, dtype: float64 As observed, New values = old values + 5 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Jul, 2018" }, { "code": null, "e": 365, "s": 54, "text": "Pandas.apply allow the users to pass a function and apply it on every single value of the Pandas series. It comes as a huge improvement for the pandas library as this function helps to segregate data according to the conditions required due to which it is efficiently used in data science and machine learning." }, { "code": null, "e": 470, "s": 365, "text": "Installation:Import the Pandas module into the python file using the following commands on the terminal:" }, { "code": null, "e": 490, "s": 470, "text": "pip install pandas\n" }, { "code": null, "e": 578, "s": 490, "text": "To read the csv file and squeezing it into a pandas series following commands are used:" }, { "code": null, "e": 642, "s": 578, "text": "import pandas as pd\ns = pd.read_csv(\"stock.csv\", squeeze=True)\n" }, { "code": null, "e": 650, "s": 642, "text": "Syntax:" }, { "code": null, "e": 693, "s": 650, "text": "s.apply(func, convert_dtype=True, args=())" }, { "code": null, "e": 705, "s": 693, "text": "Parameters:" }, { "code": null, "e": 971, "s": 705, "text": "func: .apply takes a function and applies it to all values of pandas series.convert_dtype: Convert dtype as per the function’s operation.args=(): Additional arguments to pass to function instead of series.Return Type: Pandas Series after applied function/operation." }, { "code": null, "e": 1012, "s": 971, "text": "For the dataset, click here to download." }, { "code": null, "e": 1024, "s": 1012, "text": "Example #1:" }, { "code": null, "e": 1156, "s": 1024, "text": "The following example passes a function and checks the value of each element in series and returns low, normal or High accordingly." }, { "code": "import pandas as pd # reading csvs = pd.read_csv(\"stock.csv\", squeeze = True) # defining function to check pricedef fun(num): if num<200: return \"Low\" elif num>= 200 and num<400: return \"Normal\" else: return \"High\" # passing function to apply and storing returned series in newnew = s.apply(fun) # printing first 3 elementprint(new.head(3)) # printing elements somewhere near the middle of seriesprint(new[1400], new[1500], new[1600]) # printing last 3 elementsprint(new.tail(3))", "e": 1678, "s": 1156, "text": null }, { "code": null, "e": 1686, "s": 1678, "text": "Output:" }, { "code": null, "e": 1698, "s": 1686, "text": "Example #2:" }, { "code": null, "e": 1854, "s": 1698, "text": "In the following example, a temporary anonymous function is made in .apply itself using lambda. It adds 5 to each value in series and returns a new series." }, { "code": "import pandas as pds = pd.read_csv(\"stock.csv\", squeeze = True) # adding 5 to each valuenew = s.apply(lambda num : num + 5) # printing first 5 elements of old and new seriesprint(s.head(), '\\n', new.head()) # printing last 5 elements of old and new seriesprint('\\n\\n', s.tail(), '\\n', new.tail())", "e": 2154, "s": 1854, "text": null }, { "code": null, "e": 2162, "s": 2154, "text": "Output:" }, { "code": null, "e": 2564, "s": 2162, "text": "0 50.12\n1 54.10\n2 54.65\n3 52.38\n4 52.95\nName: Stock Price, dtype: float64 \n\n0 55.12\n1 59.10\n2 59.65\n3 57.38\n4 57.95\nName: Stock Price, dtype: float64\n\n3007 772.88\n3008 771.07\n3009 773.18\n3010 771.61\n3011 782.22\nName: Stock Price, dtype: float64\n \n3007 777.88\n3008 776.07\n3009 778.18\n3010 776.61\n3011 787.22\nName: Stock Price, dtype: float64\n" }, { "code": null, "e": 2605, "s": 2564, "text": "As observed, New values = old values + 5" }, { "code": null, "e": 2620, "s": 2605, "text": "python-modules" }, { "code": null, "e": 2627, "s": 2620, "text": "Python" }, { "code": null, "e": 2725, "s": 2627, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2743, "s": 2725, "text": "Python Dictionary" }, { "code": null, "e": 2785, "s": 2743, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2807, "s": 2785, "text": "Enumerate() in Python" }, { "code": null, "e": 2842, "s": 2807, "text": "Read a file line by line in Python" }, { "code": null, "e": 2874, "s": 2842, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2903, "s": 2874, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2933, "s": 2903, "text": "Iterate over a list in Python" }, { "code": null, "e": 2960, "s": 2933, "text": "Python Classes and Objects" }, { "code": null, "e": 2996, "s": 2960, "text": "Convert integer to string in Python" } ]
random.gauss() function in Python
26 May, 2020 random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined. gauss() is an inbuilt method of the random module. It is used to return a random floating point number with gaussian distribution. Syntax : random.gauss(mu, sigma) Parameters :mu : meansigma : standard deviation Returns : a random gaussian distribution floating number Example 1: # import the random moduleimport random # determining the values of the parametersmu = 100sigma = 50 # using the gauss() methodprint(random.gauss(mu, sigma)) Output : 127.80261974806497 Example 2: We can generate the number multiple times and plot a graph to observe the gaussian distribution. # import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a # list nums = [] mu = 100sigma = 50 for i in range(100): temp = random.gauss(mu, sigma) nums.append(temp) # plotting a graph plt.plot(nums) plt.show() Output : Example 3: We can create a histogram to observe the density of the gaussian distribution. # import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a list nums = [] mu = 100sigma = 50 for i in range(10000): temp = random.gauss(mu, sigma) nums.append(temp) # plotting a graph plt.hist(nums, bins = 200) plt.show() Output : Python-random Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2020" }, { "code": null, "e": 234, "s": 28, "text": "random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined." }, { "code": null, "e": 365, "s": 234, "text": "gauss() is an inbuilt method of the random module. It is used to return a random floating point number with gaussian distribution." }, { "code": null, "e": 398, "s": 365, "text": "Syntax : random.gauss(mu, sigma)" }, { "code": null, "e": 446, "s": 398, "text": "Parameters :mu : meansigma : standard deviation" }, { "code": null, "e": 503, "s": 446, "text": "Returns : a random gaussian distribution floating number" }, { "code": null, "e": 514, "s": 503, "text": "Example 1:" }, { "code": "# import the random moduleimport random # determining the values of the parametersmu = 100sigma = 50 # using the gauss() methodprint(random.gauss(mu, sigma))", "e": 674, "s": 514, "text": null }, { "code": null, "e": 683, "s": 674, "text": "Output :" }, { "code": null, "e": 702, "s": 683, "text": "127.80261974806497" }, { "code": null, "e": 810, "s": 702, "text": "Example 2: We can generate the number multiple times and plot a graph to observe the gaussian distribution." }, { "code": "# import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a # list nums = [] mu = 100sigma = 50 for i in range(100): temp = random.gauss(mu, sigma) nums.append(temp) # plotting a graph plt.plot(nums) plt.show()", "e": 1094, "s": 810, "text": null }, { "code": null, "e": 1103, "s": 1094, "text": "Output :" }, { "code": null, "e": 1193, "s": 1103, "text": "Example 3: We can create a histogram to observe the density of the gaussian distribution." }, { "code": "# import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a list nums = [] mu = 100sigma = 50 for i in range(10000): temp = random.gauss(mu, sigma) nums.append(temp) # plotting a graph plt.hist(nums, bins = 200) plt.show()", "e": 1489, "s": 1193, "text": null }, { "code": null, "e": 1498, "s": 1489, "text": "Output :" }, { "code": null, "e": 1512, "s": 1498, "text": "Python-random" }, { "code": null, "e": 1519, "s": 1512, "text": "Python" } ]
HTML Background Images - GeeksforGeeks
17 Aug, 2021 HTML stands for HyperText Markup Language. It is used to design or create web pages using a markup language. It is a combination of Hypertext and Markup language. Here, hypertext defines the link between the web pages whereas markup language is used to define the text document within tag which defines the structure of web pages. In HTML, we can make our web pages look more attractive and captivating by adding a background image to our HTML page. So, we can add background images in two different ways: Add a background image using the background image attribute inside the <body> tag.Add background image using the HTML style attribute. Add a background image using the background image attribute inside the <body> tag. Add background image using the HTML style attribute. In this article, we will learn these two methods for adding background images to web pages. In this method we will add a background image is using the background image attribute inside the <body> tag. Syntax: <body background=”image.png”> Example: HTML <!DOCTYPE html><html lang="en"><head> <title>Background Image</title></head><body background="gfg (2).png" > <h3>Welcome to GeeksforGeeks</h3></body></html> Output: In this method, we will add a background image using the HTML style attribute for a particular element in the webpage. Syntax: <div style=”background-image: url(‘img.jpg’);”> Example: HTML <!DOCTYPE html><html lang="en"><head> <title>Background Image</title></head><body> <h3>Welcome to GeeksforGeeks</h3> <div style="background-image: url('gfg (2).png');"> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> </div></body></html> In the above example we can see that there is no background image for the heading “Welcome to GeeksforGeeks”, but we have a background image for the div containing paragraphs. Output: In HTML, if the image is small in size as compared to the element then the image repeats itself horizontally and vertically. It repeats until it reaches the end of the element. If you don’t want to repeat the image then set the value of background-repeat property to no-repeat. Let us discuss this concept with the help of an example: HTML <!DOCTYPE html><html lang="en"><head> <style> body{ background-image: url('example.png'); } </style></head><body><h2>welcome</h2></body></html> Output: Picked class 7 School Learning School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Amazon Interview Experience (Off-Campus) 2022 How to Read Text Files with Pandas? Must Do Coding Questions for Product Based Companies TCS NQT Coding Sheet Inshackle - Tool for Instagram Hacks in Kali Linux Libraries in Python Cloud Deployment Models What is a Storage Device? Definition, Types, Examples Generations of Computers - Computer Fundamentals
[ { "code": null, "e": 24073, "s": 24045, "text": "\n17 Aug, 2021" }, { "code": null, "e": 24579, "s": 24073, "text": "HTML stands for HyperText Markup Language. It is used to design or create web pages using a markup language. It is a combination of Hypertext and Markup language. Here, hypertext defines the link between the web pages whereas markup language is used to define the text document within tag which defines the structure of web pages. In HTML, we can make our web pages look more attractive and captivating by adding a background image to our HTML page. So, we can add background images in two different ways:" }, { "code": null, "e": 24714, "s": 24579, "text": "Add a background image using the background image attribute inside the <body> tag.Add background image using the HTML style attribute." }, { "code": null, "e": 24797, "s": 24714, "text": "Add a background image using the background image attribute inside the <body> tag." }, { "code": null, "e": 24850, "s": 24797, "text": "Add background image using the HTML style attribute." }, { "code": null, "e": 24942, "s": 24850, "text": "In this article, we will learn these two methods for adding background images to web pages." }, { "code": null, "e": 25051, "s": 24942, "text": "In this method we will add a background image is using the background image attribute inside the <body> tag." }, { "code": null, "e": 25059, "s": 25051, "text": "Syntax:" }, { "code": null, "e": 25089, "s": 25059, "text": "<body background=”image.png”>" }, { "code": null, "e": 25098, "s": 25089, "text": "Example:" }, { "code": null, "e": 25103, "s": 25098, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Background Image</title></head><body background=\"gfg (2).png\" > <h3>Welcome to GeeksforGeeks</h3></body></html>", "e": 25262, "s": 25103, "text": null }, { "code": null, "e": 25270, "s": 25262, "text": "Output:" }, { "code": null, "e": 25389, "s": 25270, "text": "In this method, we will add a background image using the HTML style attribute for a particular element in the webpage." }, { "code": null, "e": 25397, "s": 25389, "text": "Syntax:" }, { "code": null, "e": 25445, "s": 25397, "text": "<div style=”background-image: url(‘img.jpg’);”>" }, { "code": null, "e": 25454, "s": 25445, "text": "Example:" }, { "code": null, "e": 25459, "s": 25454, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Background Image</title></head><body> <h3>Welcome to GeeksforGeeks</h3> <div style=\"background-image: url('gfg (2).png');\"> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> <p>A Computer Science portal for geeks.</p> </div></body></html>", "e": 26266, "s": 25459, "text": null }, { "code": null, "e": 26442, "s": 26266, "text": "In the above example we can see that there is no background image for the heading “Welcome to GeeksforGeeks”, but we have a background image for the div containing paragraphs." }, { "code": null, "e": 26450, "s": 26442, "text": "Output:" }, { "code": null, "e": 26785, "s": 26450, "text": "In HTML, if the image is small in size as compared to the element then the image repeats itself horizontally and vertically. It repeats until it reaches the end of the element. If you don’t want to repeat the image then set the value of background-repeat property to no-repeat. Let us discuss this concept with the help of an example:" }, { "code": null, "e": 26790, "s": 26785, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <style> body{ background-image: url('example.png'); } </style></head><body><h2>welcome</h2></body></html>", "e": 26965, "s": 26790, "text": null }, { "code": null, "e": 26973, "s": 26965, "text": "Output:" }, { "code": null, "e": 26980, "s": 26973, "text": "Picked" }, { "code": null, "e": 26988, "s": 26980, "text": "class 7" }, { "code": null, "e": 27004, "s": 26988, "text": "School Learning" }, { "code": null, "e": 27023, "s": 27004, "text": "School Programming" }, { "code": null, "e": 27121, "s": 27023, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27130, "s": 27121, "text": "Comments" }, { "code": null, "e": 27143, "s": 27130, "text": "Old Comments" }, { "code": null, "e": 27189, "s": 27143, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 27225, "s": 27189, "text": "How to Read Text Files with Pandas?" }, { "code": null, "e": 27278, "s": 27225, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 27299, "s": 27278, "text": "TCS NQT Coding Sheet" }, { "code": null, "e": 27350, "s": 27299, "text": "Inshackle - Tool for Instagram Hacks in Kali Linux" }, { "code": null, "e": 27370, "s": 27350, "text": "Libraries in Python" }, { "code": null, "e": 27394, "s": 27370, "text": "Cloud Deployment Models" }, { "code": null, "e": 27448, "s": 27394, "text": "What is a Storage Device? Definition, Types, Examples" } ]
How to use a custom png image marker in a plot (Matplotlib)?
To use custome png or jpg i.e an image as a marker in a plot, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Make a paths list to store the directories of images. Make a paths list to store the directories of images. Make a list (x and y) of points. Make a list (x and y) of points. Using subplots() method, create a figure and a set of subplots. Using subplots() method, create a figure and a set of subplots. To plot images instead of points, iterate zipped x, y and paths. To plot images instead of points, iterate zipped x, y and paths. Instantiate AnnotationBbox() with image and (x, y) points. Instantiate AnnotationBbox() with image and (x, y) points. Put xticks and yticks on both the axes. Put xticks and yticks on both the axes. To display the figure, use show() method. To display the figure, use show() method. import matplotlib.pyplot as plt from matplotlib.offsetbox import OffsetImage, AnnotationBbox plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True def getImage(path): return OffsetImage(plt.imread(path, format="jpg"), zoom=.1) paths = ['globe.jpg', 'settings.jpg', 'settings.jpg', 'globe.jpg'] x = [8, 4, 3, 6] y = [5, 3, 4, 7] fig, ax = plt.subplots() for x0, y0, path in zip(x, y, paths): ab = AnnotationBbox(getImage(path), (x0, y0), frameon=False) ax.add_artist(ab) plt.xticks(range(10)) plt.yticks(range(10)) plt.show()
[ { "code": null, "e": 1158, "s": 1062, "text": "To use custome png or jpg i.e an image as a marker in a plot, we can take the following steps −" }, { "code": null, "e": 1234, "s": 1158, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1310, "s": 1234, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1364, "s": 1310, "text": "Make a paths list to store the directories of images." }, { "code": null, "e": 1418, "s": 1364, "text": "Make a paths list to store the directories of images." }, { "code": null, "e": 1451, "s": 1418, "text": "Make a list (x and y) of points." }, { "code": null, "e": 1484, "s": 1451, "text": "Make a list (x and y) of points." }, { "code": null, "e": 1548, "s": 1484, "text": "Using subplots() method, create a figure and a set of subplots." }, { "code": null, "e": 1612, "s": 1548, "text": "Using subplots() method, create a figure and a set of subplots." }, { "code": null, "e": 1677, "s": 1612, "text": "To plot images instead of points, iterate zipped x, y and paths." }, { "code": null, "e": 1742, "s": 1677, "text": "To plot images instead of points, iterate zipped x, y and paths." }, { "code": null, "e": 1801, "s": 1742, "text": "Instantiate AnnotationBbox() with image and (x, y) points." }, { "code": null, "e": 1860, "s": 1801, "text": "Instantiate AnnotationBbox() with image and (x, y) points." }, { "code": null, "e": 1900, "s": 1860, "text": "Put xticks and yticks on both the axes." }, { "code": null, "e": 1940, "s": 1900, "text": "Put xticks and yticks on both the axes." }, { "code": null, "e": 1982, "s": 1940, "text": "To display the figure, use show() method." }, { "code": null, "e": 2024, "s": 1982, "text": "To display the figure, use show() method." }, { "code": null, "e": 2594, "s": 2024, "text": "import matplotlib.pyplot as plt\nfrom matplotlib.offsetbox import OffsetImage, AnnotationBbox\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndef getImage(path):\n return OffsetImage(plt.imread(path, format=\"jpg\"), zoom=.1)\n\npaths = ['globe.jpg', 'settings.jpg', 'settings.jpg', 'globe.jpg']\nx = [8, 4, 3, 6]\ny = [5, 3, 4, 7]\nfig, ax = plt.subplots()\nfor x0, y0, path in zip(x, y, paths):\n ab = AnnotationBbox(getImage(path), (x0, y0), frameon=False)\n ax.add_artist(ab)\nplt.xticks(range(10))\nplt.yticks(range(10))\nplt.show()" } ]
Perl seek Function
This function moves to a specified position in a file. You can move relative to the beginning of the file (WHENCE = 0), the current position (WHENCE = 1), or the end of the file (WHENCE = 2). This function is mainly used with fixed length records to randomly access specific records of the file. For WHENCE you may use the constants SEEK_SET , SEEK_CUR , and SEEK_END (start of the file, current position, end of the file) from the Fcntl module. This function is similar to Unix seek() system call. Following is the simple syntax for this function − seek FILEHANDLE,POSITION,WHENCE This function 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2516, "s": 2220, "text": "This function moves to a specified position in a file. You can move relative to the beginning of the file (WHENCE = 0), the current position (WHENCE = 1), or the end of the file (WHENCE = 2). This function is mainly used with fixed length records to randomly access specific records of the file." }, { "code": null, "e": 2666, "s": 2516, "text": "For WHENCE you may use the constants SEEK_SET , SEEK_CUR , and SEEK_END (start of the file, current position, end of the file) from the Fcntl module." }, { "code": null, "e": 2719, "s": 2666, "text": "This function is similar to Unix seek() system call." }, { "code": null, "e": 2770, "s": 2719, "text": "Following is the simple syntax for this function −" }, { "code": null, "e": 2803, "s": 2770, "text": "seek FILEHANDLE,POSITION,WHENCE\n" }, { "code": null, "e": 2817, "s": 2803, "text": "This function" }, { "code": null, "e": 2852, "s": 2817, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2866, "s": 2852, "text": " Devi Killada" }, { "code": null, "e": 2901, "s": 2866, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2921, "s": 2901, "text": " Harshit Srivastava" }, { "code": null, "e": 2954, "s": 2921, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 2970, "s": 2954, "text": " TELCOMA Global" }, { "code": null, "e": 3003, "s": 2970, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3020, "s": 3003, "text": " Mohammad Nauman" }, { "code": null, "e": 3053, "s": 3020, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 3076, "s": 3053, "text": " Stone River ELearning" }, { "code": null, "e": 3111, "s": 3076, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3134, "s": 3111, "text": " Stone River ELearning" }, { "code": null, "e": 3141, "s": 3134, "text": " Print" }, { "code": null, "e": 3152, "s": 3141, "text": " Add Notes" } ]
Deploying a Trained ML Model using Flask | by Harshit Tyagi | Towards Data Science
Continuing from my last post on End-to-End Machine Learning Project Tutorial where we discussed major tasks of building a robust ML model, this post offers you a simple and fast solution to deploying your ML model on the web. This is the last task in our End-to-End ML fuel consumption project which we started here. In order to deploy any trained model, you need the following: A trained model ready to deploy — save the model into a file to be further loaded and used by the web service. A web service — that gives a purpose for your model to be used in practice. For our fuel consumption model, it can be using the vehicle configuration to predict its efficiency. We’ll use Flask to develop this service. A cloud service provider — you need special cloud servers to deploy the application and for simplicity, we are going to use Heroku(there are going to be AWS and GCP covered in the Data Engineering series) for this. Let’s get started by looking at each one of these processes one by one. Once you’re confident enough to take your trained and tested model into the production-ready environment, the first step is to save it into a .h5 or .bin file using a library like pickle . Make sure you have pickle installed in your environment. Next, let’s import the module and dump the model into a .bin file: import pickle##dump the model into a filewith open("model.bin", 'wb') as f_out: pickle.dump(final_model, f_out) # write final_model in .bin file f_out.close() # close the file This will save your model in your present working directory unless you specify some other path. It’s time to test if we are able to use this file to load our model and make predictions, we are going to use the same(as defined in prev blog) vehicle config: ##vehicle configvehicle_config = { 'Cylinders': [4, 6, 8], 'Displacement': [155.0, 160.0, 165.5], 'Horsepower': [93.0, 130.0, 98.0], 'Weight': [2500.0, 3150.0, 2600.0], 'Acceleration': [15.0, 14.0, 16.0], 'Model Year': [81, 80, 78], 'Origin': [3, 2, 1]} Let’ load the model from the file: ##loading the model from the saved filewith open('model.bin', 'rb') as f_in: model = pickle.load(f_in) Make predictions on the vehicle_config ##defined in prev_blogpredict_mpg(vehicle_config, model)##output: array([34.83333333, 18.50666667, 20.56333333]) The output is the same as we predicted earlier using final_model. The next step is to package this model into a web service that when given the data through a POST request returns the MPG(Miles per Gallon) predictions as a response. I am using the Flask web framework, a commonly used lightweight framework for developing web services in Python. In my opinion, it is probably the easiest way to implement a web service. Flask requires gets you started with very little code and you don’t need to worry about the complexity of handling with HTTP requests and responses. Here are the steps: Create a new directory for your flask application. Set up a dedicated environment with dependencies installed using pip. Install the following packages: pandasnumpysklearnflaskgunicornseaborn The next step is to activate this environment and start developing a simple endpoint to test the application: Create a new file, main.py and import the flask module: from flask import Flask Create a Flask app by instantiating the Flask class: ##creating a flask app and naming it "app"app = Flask('app') Create a route and a function corresponding to it that will return a simple string: @app.route('/test', methods=['GET'])def test(): return 'Pinging Model Application!!' The above code makes use of decorators — an advanced python feature. You can read more about decorators here. We don’t need a deep understanding of decorators, just that adding a decorator @app.route on top of the test() function assigns that web service address to that function. Now, to run the application we need this last piece of code: if __name__ == ‘__main__’: app.run(debug=True, host=’0.0.0.0', port=9696) The run method starts our flask application service. The 3 parameters specify: debug=True — restarts the application automatically when it encounters any change in the code host=’0.0.0.0' — makes the web service public port=9696 — the port that we use to access the application Now, in your terminal run the main.py python main.py Opening the URL http://0.0.0.0:9696/test in your browser will print the response string on the webpage: With the application now, running, let’s run the model: Create a new directory model_files to store all the model-related code. In this directory, create a ml_model.py file which will contain the data preparation code and the predict function we wrote here. Copy and paste the libraries you imported in the first part and the preprocessing/transformation functions. The file should look like this: In the same directory, place your saved model.bin file as well. Now, in the main.py we are going to import the predict_mpg function to make predictions but to do that we are required to create an empty __init__.py file to tell Python that the directory is a package. Your directory should have this tree: Next up, define the predict/ route that will accept the vehicle_config from an HTTP POST request and return the predictions using the model and predict_mpg() method. In your main.py, first import: import picklefrom flask import Flask, request, jsonifyfrom model_files.ml_model import predict_mpg Then add the predict route and the corresponding function: Here, we’ll only be accepting POST request for our function and thus we have methods=[‘POST’] in the decorator. First, we capture the data(vehicle_config) from our request using get_json() method and stored it in the variable vehicle. Then we load the trained model into the model variable from the file we have in model_files folder. Now, we make the predictions by calling the predict_mpg function and passing the vehicle and model. We create a JSON response of this array returned in the predictions variable and return this JSON as the method response. We can test this route using Postman or the requests package, start the server running the main.py and then in your notebook, add this code to send a POST request with the vehicle_config: import requestsurl = “http://localhost:9696/predict"r = requests.post(url, json = vehicle_config)r.text.strip()##output: '{"mpg_predictions":[34.60333333333333,19.32333333333333,14.893333333333333]}' Great! Now, comes the last part, this same functionality should work when deployed on a remote server. To deploy this flask application on Heroku, you need to follow these very simple steps: Create a Procfile in the main directory — this contains the command to get the run the application on the server.Add the following in your Procfile: Create a Procfile in the main directory — this contains the command to get the run the application on the server. Add the following in your Procfile: web: gunicorn wsgi:app We are using gunicorn(installed earlier) to deploy the application: Gunicorn is a pure-Python HTTP server for WSGI applications. It allows you to run any Python application concurrently by running multiple Python processes within a single dyno. It provides a perfect balance of performance, flexibility, and configuration simplicity. 3. Create a wsgi.py file and add: ##importing the app from main filefrom main import appif __name__ == “__main__”: app.run() Make sure you delete the run code from the main.py . 4. Write all the python dependencies into requirements.txt: you can use pip freeze > requirements.txt or simply put the above-mentioned list of packages + any other package that your application is using. 5. Using the terminal, initialize an empty git repository, add the files to the staging area commit files to the local repository: $ git init $ git add .$ git commit -m "Initial Commit" 6. Create a Heroku account if you haven’t already, login to Heroku CLI: heroku login Approve the login from the browser as the page pops up: 7. Create a flask app: heroku create <name of your app> I named it mpg-flask-app. It will create a flask app and will give us a URL on which the app will be deployed. 8. Finally, push all your code to Heroku remote: $ git push heroku master And Voila! your web service is now deployed on https://mpg-flask-app.herokuapp.com/predict. Again, test the endpoint using request package by sending the same vehicle config: With that, you have all the major skills you need to get on to building more complex ML applications. You can refer to my GitHub repository for this project: github.com And you can develop this entire project along with me: This was still a simple project, for the next steps, I’d recommend you take up a more complex dataset, maybe pick up a classification problem and repeat these tasks till deployment. But if you don’t want to wait, here is the complete tutorial series(playlist) on my YouTube channel where you can follow me while working on this project. With this channel, I plan to roll out a couple of series covering the entire data science space. Here is why you should be subscribing to the channel: These series would cover all the required/demanded quality tutorials on each of the topics and subtopics like Python fundamentals for Data Science. Explained Mathematics and derivations of why we do what we do in ML and Deep Learning. Podcasts with Data Scientists and Engineers at Google, Microsoft, Amazon, etc, and CEOs of big data-driven companies. Projects and instructions to implement the topics learned so far. Learn about new certifications, Bootcamp, and resources to crack those certifications like this TensorFlow Developer Certificate Exam by Google.
[ { "code": null, "e": 398, "s": 172, "text": "Continuing from my last post on End-to-End Machine Learning Project Tutorial where we discussed major tasks of building a robust ML model, this post offers you a simple and fast solution to deploying your ML model on the web." }, { "code": null, "e": 489, "s": 398, "text": "This is the last task in our End-to-End ML fuel consumption project which we started here." }, { "code": null, "e": 551, "s": 489, "text": "In order to deploy any trained model, you need the following:" }, { "code": null, "e": 662, "s": 551, "text": "A trained model ready to deploy — save the model into a file to be further loaded and used by the web service." }, { "code": null, "e": 880, "s": 662, "text": "A web service — that gives a purpose for your model to be used in practice. For our fuel consumption model, it can be using the vehicle configuration to predict its efficiency. We’ll use Flask to develop this service." }, { "code": null, "e": 1095, "s": 880, "text": "A cloud service provider — you need special cloud servers to deploy the application and for simplicity, we are going to use Heroku(there are going to be AWS and GCP covered in the Data Engineering series) for this." }, { "code": null, "e": 1167, "s": 1095, "text": "Let’s get started by looking at each one of these processes one by one." }, { "code": null, "e": 1356, "s": 1167, "text": "Once you’re confident enough to take your trained and tested model into the production-ready environment, the first step is to save it into a .h5 or .bin file using a library like pickle ." }, { "code": null, "e": 1413, "s": 1356, "text": "Make sure you have pickle installed in your environment." }, { "code": null, "e": 1480, "s": 1413, "text": "Next, let’s import the module and dump the model into a .bin file:" }, { "code": null, "e": 1664, "s": 1480, "text": "import pickle##dump the model into a filewith open(\"model.bin\", 'wb') as f_out: pickle.dump(final_model, f_out) # write final_model in .bin file f_out.close() # close the file " }, { "code": null, "e": 1760, "s": 1664, "text": "This will save your model in your present working directory unless you specify some other path." }, { "code": null, "e": 1920, "s": 1760, "text": "It’s time to test if we are able to use this file to load our model and make predictions, we are going to use the same(as defined in prev blog) vehicle config:" }, { "code": null, "e": 2195, "s": 1920, "text": "##vehicle configvehicle_config = { 'Cylinders': [4, 6, 8], 'Displacement': [155.0, 160.0, 165.5], 'Horsepower': [93.0, 130.0, 98.0], 'Weight': [2500.0, 3150.0, 2600.0], 'Acceleration': [15.0, 14.0, 16.0], 'Model Year': [81, 80, 78], 'Origin': [3, 2, 1]}" }, { "code": null, "e": 2230, "s": 2195, "text": "Let’ load the model from the file:" }, { "code": null, "e": 2336, "s": 2230, "text": "##loading the model from the saved filewith open('model.bin', 'rb') as f_in: model = pickle.load(f_in)" }, { "code": null, "e": 2375, "s": 2336, "text": "Make predictions on the vehicle_config" }, { "code": null, "e": 2488, "s": 2375, "text": "##defined in prev_blogpredict_mpg(vehicle_config, model)##output: array([34.83333333, 18.50666667, 20.56333333])" }, { "code": null, "e": 2554, "s": 2488, "text": "The output is the same as we predicted earlier using final_model." }, { "code": null, "e": 2721, "s": 2554, "text": "The next step is to package this model into a web service that when given the data through a POST request returns the MPG(Miles per Gallon) predictions as a response." }, { "code": null, "e": 2908, "s": 2721, "text": "I am using the Flask web framework, a commonly used lightweight framework for developing web services in Python. In my opinion, it is probably the easiest way to implement a web service." }, { "code": null, "e": 3057, "s": 2908, "text": "Flask requires gets you started with very little code and you don’t need to worry about the complexity of handling with HTTP requests and responses." }, { "code": null, "e": 3077, "s": 3057, "text": "Here are the steps:" }, { "code": null, "e": 3128, "s": 3077, "text": "Create a new directory for your flask application." }, { "code": null, "e": 3198, "s": 3128, "text": "Set up a dedicated environment with dependencies installed using pip." }, { "code": null, "e": 3230, "s": 3198, "text": "Install the following packages:" }, { "code": null, "e": 3269, "s": 3230, "text": "pandasnumpysklearnflaskgunicornseaborn" }, { "code": null, "e": 3379, "s": 3269, "text": "The next step is to activate this environment and start developing a simple endpoint to test the application:" }, { "code": null, "e": 3435, "s": 3379, "text": "Create a new file, main.py and import the flask module:" }, { "code": null, "e": 3459, "s": 3435, "text": "from flask import Flask" }, { "code": null, "e": 3512, "s": 3459, "text": "Create a Flask app by instantiating the Flask class:" }, { "code": null, "e": 3573, "s": 3512, "text": "##creating a flask app and naming it \"app\"app = Flask('app')" }, { "code": null, "e": 3657, "s": 3573, "text": "Create a route and a function corresponding to it that will return a simple string:" }, { "code": null, "e": 3745, "s": 3657, "text": "@app.route('/test', methods=['GET'])def test(): return 'Pinging Model Application!!'" }, { "code": null, "e": 4026, "s": 3745, "text": "The above code makes use of decorators — an advanced python feature. You can read more about decorators here. We don’t need a deep understanding of decorators, just that adding a decorator @app.route on top of the test() function assigns that web service address to that function." }, { "code": null, "e": 4087, "s": 4026, "text": "Now, to run the application we need this last piece of code:" }, { "code": null, "e": 4164, "s": 4087, "text": "if __name__ == ‘__main__’: app.run(debug=True, host=’0.0.0.0', port=9696)" }, { "code": null, "e": 4243, "s": 4164, "text": "The run method starts our flask application service. The 3 parameters specify:" }, { "code": null, "e": 4337, "s": 4243, "text": "debug=True — restarts the application automatically when it encounters any change in the code" }, { "code": null, "e": 4383, "s": 4337, "text": "host=’0.0.0.0' — makes the web service public" }, { "code": null, "e": 4442, "s": 4383, "text": "port=9696 — the port that we use to access the application" }, { "code": null, "e": 4480, "s": 4442, "text": "Now, in your terminal run the main.py" }, { "code": null, "e": 4495, "s": 4480, "text": "python main.py" }, { "code": null, "e": 4599, "s": 4495, "text": "Opening the URL http://0.0.0.0:9696/test in your browser will print the response string on the webpage:" }, { "code": null, "e": 4655, "s": 4599, "text": "With the application now, running, let’s run the model:" }, { "code": null, "e": 4727, "s": 4655, "text": "Create a new directory model_files to store all the model-related code." }, { "code": null, "e": 4857, "s": 4727, "text": "In this directory, create a ml_model.py file which will contain the data preparation code and the predict function we wrote here." }, { "code": null, "e": 4997, "s": 4857, "text": "Copy and paste the libraries you imported in the first part and the preprocessing/transformation functions. The file should look like this:" }, { "code": null, "e": 5061, "s": 4997, "text": "In the same directory, place your saved model.bin file as well." }, { "code": null, "e": 5264, "s": 5061, "text": "Now, in the main.py we are going to import the predict_mpg function to make predictions but to do that we are required to create an empty __init__.py file to tell Python that the directory is a package." }, { "code": null, "e": 5302, "s": 5264, "text": "Your directory should have this tree:" }, { "code": null, "e": 5468, "s": 5302, "text": "Next up, define the predict/ route that will accept the vehicle_config from an HTTP POST request and return the predictions using the model and predict_mpg() method." }, { "code": null, "e": 5499, "s": 5468, "text": "In your main.py, first import:" }, { "code": null, "e": 5598, "s": 5499, "text": "import picklefrom flask import Flask, request, jsonifyfrom model_files.ml_model import predict_mpg" }, { "code": null, "e": 5657, "s": 5598, "text": "Then add the predict route and the corresponding function:" }, { "code": null, "e": 5769, "s": 5657, "text": "Here, we’ll only be accepting POST request for our function and thus we have methods=[‘POST’] in the decorator." }, { "code": null, "e": 5892, "s": 5769, "text": "First, we capture the data(vehicle_config) from our request using get_json() method and stored it in the variable vehicle." }, { "code": null, "e": 5992, "s": 5892, "text": "Then we load the trained model into the model variable from the file we have in model_files folder." }, { "code": null, "e": 6092, "s": 5992, "text": "Now, we make the predictions by calling the predict_mpg function and passing the vehicle and model." }, { "code": null, "e": 6214, "s": 6092, "text": "We create a JSON response of this array returned in the predictions variable and return this JSON as the method response." }, { "code": null, "e": 6402, "s": 6214, "text": "We can test this route using Postman or the requests package, start the server running the main.py and then in your notebook, add this code to send a POST request with the vehicle_config:" }, { "code": null, "e": 6602, "s": 6402, "text": "import requestsurl = “http://localhost:9696/predict\"r = requests.post(url, json = vehicle_config)r.text.strip()##output: '{\"mpg_predictions\":[34.60333333333333,19.32333333333333,14.893333333333333]}'" }, { "code": null, "e": 6705, "s": 6602, "text": "Great! Now, comes the last part, this same functionality should work when deployed on a remote server." }, { "code": null, "e": 6793, "s": 6705, "text": "To deploy this flask application on Heroku, you need to follow these very simple steps:" }, { "code": null, "e": 6942, "s": 6793, "text": "Create a Procfile in the main directory — this contains the command to get the run the application on the server.Add the following in your Procfile:" }, { "code": null, "e": 7056, "s": 6942, "text": "Create a Procfile in the main directory — this contains the command to get the run the application on the server." }, { "code": null, "e": 7092, "s": 7056, "text": "Add the following in your Procfile:" }, { "code": null, "e": 7115, "s": 7092, "text": "web: gunicorn wsgi:app" }, { "code": null, "e": 7183, "s": 7115, "text": "We are using gunicorn(installed earlier) to deploy the application:" }, { "code": null, "e": 7449, "s": 7183, "text": "Gunicorn is a pure-Python HTTP server for WSGI applications. It allows you to run any Python application concurrently by running multiple Python processes within a single dyno. It provides a perfect balance of performance, flexibility, and configuration simplicity." }, { "code": null, "e": 7483, "s": 7449, "text": "3. Create a wsgi.py file and add:" }, { "code": null, "e": 7578, "s": 7483, "text": "##importing the app from main filefrom main import appif __name__ == “__main__”: app.run()" }, { "code": null, "e": 7631, "s": 7578, "text": "Make sure you delete the run code from the main.py ." }, { "code": null, "e": 7691, "s": 7631, "text": "4. Write all the python dependencies into requirements.txt:" }, { "code": null, "e": 7836, "s": 7691, "text": "you can use pip freeze > requirements.txt or simply put the above-mentioned list of packages + any other package that your application is using." }, { "code": null, "e": 7859, "s": 7836, "text": "5. Using the terminal," }, { "code": null, "e": 7895, "s": 7859, "text": "initialize an empty git repository," }, { "code": null, "e": 7929, "s": 7895, "text": "add the files to the staging area" }, { "code": null, "e": 7967, "s": 7929, "text": "commit files to the local repository:" }, { "code": null, "e": 8022, "s": 7967, "text": "$ git init $ git add .$ git commit -m \"Initial Commit\"" }, { "code": null, "e": 8094, "s": 8022, "text": "6. Create a Heroku account if you haven’t already, login to Heroku CLI:" }, { "code": null, "e": 8107, "s": 8094, "text": "heroku login" }, { "code": null, "e": 8163, "s": 8107, "text": "Approve the login from the browser as the page pops up:" }, { "code": null, "e": 8186, "s": 8163, "text": "7. Create a flask app:" }, { "code": null, "e": 8219, "s": 8186, "text": "heroku create <name of your app>" }, { "code": null, "e": 8330, "s": 8219, "text": "I named it mpg-flask-app. It will create a flask app and will give us a URL on which the app will be deployed." }, { "code": null, "e": 8379, "s": 8330, "text": "8. Finally, push all your code to Heroku remote:" }, { "code": null, "e": 8404, "s": 8379, "text": "$ git push heroku master" }, { "code": null, "e": 8496, "s": 8404, "text": "And Voila! your web service is now deployed on https://mpg-flask-app.herokuapp.com/predict." }, { "code": null, "e": 8579, "s": 8496, "text": "Again, test the endpoint using request package by sending the same vehicle config:" }, { "code": null, "e": 8681, "s": 8579, "text": "With that, you have all the major skills you need to get on to building more complex ML applications." }, { "code": null, "e": 8737, "s": 8681, "text": "You can refer to my GitHub repository for this project:" }, { "code": null, "e": 8748, "s": 8737, "text": "github.com" }, { "code": null, "e": 8803, "s": 8748, "text": "And you can develop this entire project along with me:" }, { "code": null, "e": 8985, "s": 8803, "text": "This was still a simple project, for the next steps, I’d recommend you take up a more complex dataset, maybe pick up a classification problem and repeat these tasks till deployment." }, { "code": null, "e": 9140, "s": 8985, "text": "But if you don’t want to wait, here is the complete tutorial series(playlist) on my YouTube channel where you can follow me while working on this project." }, { "code": null, "e": 9291, "s": 9140, "text": "With this channel, I plan to roll out a couple of series covering the entire data science space. Here is why you should be subscribing to the channel:" }, { "code": null, "e": 9439, "s": 9291, "text": "These series would cover all the required/demanded quality tutorials on each of the topics and subtopics like Python fundamentals for Data Science." }, { "code": null, "e": 9526, "s": 9439, "text": "Explained Mathematics and derivations of why we do what we do in ML and Deep Learning." }, { "code": null, "e": 9644, "s": 9526, "text": "Podcasts with Data Scientists and Engineers at Google, Microsoft, Amazon, etc, and CEOs of big data-driven companies." } ]