title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Animate CSS z-index property
To implement animation on z-index property with CSS, you can try to run the following code − Live Demo <!DOCTYPE html> <html> <head> <style> div { position: absolute; } #box div { background-color: orange; border: 2px solid yellow; width: 100px; height: 100px; opacity: 0.3; } div#demo { opacity: 1; background-color: coral; z-index: 1; animation: myanim 3s; } @keyframes myanim { 30% { z-index: 3; } } </style> </head> <body> <h1>CSS z-index property</h1> <div id = "box"> <div id = "demo"></div> <div style = "top:20px;left:20px;z-index:1;">One</div> <div style = "top:40px;left:40px;z-index:2;">Two</div> <div style = "top:60px;left:60px;z-index:3;">Three</div> <div style = "top:80px;left:80px;z-index:4;">Four</div> <div style = "top:100px;left:40px;z-index:5;">Five</div> <div style = "top:120px;left:60px;z-index:6;">Six</div> <div style = "top:140px;left:80px;z-index:7;">Seven</div> </div> </body> </html>
[ { "code": null, "e": 1155, "s": 1062, "text": "To implement animation on z-index property with CSS, you can try to run the following code −" }, { "code": null, "e": 1165, "s": 1155, "text": "Live Demo" }, { "code": null, "e": 2322, "s": 1165, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n div {\n position: absolute;\n }\n #box div {\n background-color: orange;\n border: 2px solid yellow;\n width: 100px;\n height: 100px;\n opacity: 0.3;\n }\n div#demo {\n opacity: 1;\n background-color: coral;\n z-index: 1;\n animation: myanim 3s;\n }\n @keyframes myanim {\n 30% {\n z-index: 3;\n }\n }\n </style>\n </head>\n <body>\n <h1>CSS z-index property</h1>\n <div id = \"box\">\n <div id = \"demo\"></div>\n <div style = \"top:20px;left:20px;z-index:1;\">One</div>\n <div style = \"top:40px;left:40px;z-index:2;\">Two</div>\n <div style = \"top:60px;left:60px;z-index:3;\">Three</div>\n <div style = \"top:80px;left:80px;z-index:4;\">Four</div>\n <div style = \"top:100px;left:40px;z-index:5;\">Five</div>\n <div style = \"top:120px;left:60px;z-index:6;\">Six</div>\n <div style = \"top:140px;left:80px;z-index:7;\">Seven</div>\n </div>\n </body>\n</html>" } ]
How to get the running processes with the WMI object using PowerShell?
To get the running processes with a WMI object, you need to use class Win32_Process. With this method, you will get more properties than the Get-Process command. Get-WmiObject –Class Win32_Process GENUS : 2 __CLASS : Win32_Process __SUPERCLASS : CIM_Process __DYNASTY : CIM_ManagedSystemElement __RELPATH : Win32_Process.Handle="0" __PROPERTY_COUNT : 45 __DERIVATION : {CIM_Process, CIM_LogicalElement, CIM_ManagedSystemElement} __SERVER : DESKTOP-9435KM9 __NAMESPACE : root\cimv2 __PATH : \\DESKTOP-9435KM9\root\cimv2:Win32_Process.Handle="0" Caption : System Idle Process CommandLine : CreationClassName : Win32_Process CreationDate : 20191225011715.424076+330 CSCreationClassName : Win32_ComputerSystem CSName : DESKTOP-9435KM9 Description : System Idle Process ExecutablePath : ExecutionState : Handle : 0 HandleCount : 0 InstallDate : KernelModeTime : 5294149218750 MaximumWorkingSetSize : MinimumWorkingSetSize : Name : System Idle Process OSCreationClassName : Win32_OperatingSystem OSName : Microsoft Windows 10 Pro|C:\WINDOWS|\Device\Harddisk0\Partition4 OtherOperationCount : 0 OtherTransferCount : 0 PageFaults : 9 PageFileUsage : 60 ParentProcessId : 0 PeakPageFileUsage : 60 PeakVirtualSize : 8192 PeakWorkingSetSize : 12 Priority : 0 PrivatePageCount : 61440 ProcessId : 0 QuotaNonPagedPoolUsage : 1 QuotaPagedPoolUsage : 0 QuotaPeakNonPagedPoolUsage : 1 QuotaPeakPagedPoolUsage : 0 ReadOperationCount : 0 ReadTransferCount : 0 SessionId : 0 Status : TerminationDate : ThreadCount : 4 UserModeTime : 0 VirtualSize : 8192 WindowsVersion : 10.0.18362 WorkingSetSize : 8192 WriteOperationCount : 0 WriteTransferCount : 0 PSComputerName : DESKTOP-9435KM9 ProcessName : System Idle Process Handles : 0 VM : 8192 WS : 8192 Path :
[ { "code": null, "e": 1224, "s": 1062, "text": "To get the running processes with a WMI object, you need to use class Win32_Process. With this method, you will get more properties than the Get-Process command." }, { "code": null, "e": 1259, "s": 1224, "text": "Get-WmiObject –Class Win32_Process" }, { "code": null, "e": 3613, "s": 1259, "text": "GENUS : 2\n__CLASS : Win32_Process\n__SUPERCLASS : CIM_Process\n__DYNASTY : CIM_ManagedSystemElement\n__RELPATH : Win32_Process.Handle=\"0\"\n__PROPERTY_COUNT : 45\n__DERIVATION : {CIM_Process, CIM_LogicalElement, CIM_ManagedSystemElement}\n__SERVER : DESKTOP-9435KM9\n__NAMESPACE : root\\cimv2\n__PATH : \\\\DESKTOP-9435KM9\\root\\cimv2:Win32_Process.Handle=\"0\"\nCaption : System Idle Process\nCommandLine :\nCreationClassName : Win32_Process\nCreationDate : 20191225011715.424076+330\nCSCreationClassName : Win32_ComputerSystem\nCSName : DESKTOP-9435KM9\nDescription : System Idle Process\nExecutablePath :\nExecutionState :\nHandle : 0\nHandleCount : 0\nInstallDate :\nKernelModeTime : 5294149218750\nMaximumWorkingSetSize :\nMinimumWorkingSetSize :\nName : System Idle Process\nOSCreationClassName : Win32_OperatingSystem\nOSName : Microsoft Windows 10 Pro|C:\\WINDOWS|\\Device\\Harddisk0\\Partition4\nOtherOperationCount : 0\nOtherTransferCount : 0\nPageFaults : 9\nPageFileUsage : 60\nParentProcessId : 0\nPeakPageFileUsage : 60\nPeakVirtualSize : 8192\nPeakWorkingSetSize : 12\nPriority : 0\nPrivatePageCount : 61440\nProcessId : 0\nQuotaNonPagedPoolUsage : 1\nQuotaPagedPoolUsage : 0\nQuotaPeakNonPagedPoolUsage : 1\nQuotaPeakPagedPoolUsage : 0\nReadOperationCount : 0\nReadTransferCount : 0\nSessionId : 0\nStatus :\nTerminationDate :\nThreadCount : 4\nUserModeTime : 0\nVirtualSize : 8192\nWindowsVersion : 10.0.18362\nWorkingSetSize : 8192\nWriteOperationCount : 0\nWriteTransferCount : 0\nPSComputerName : DESKTOP-9435KM9\nProcessName : System Idle Process\nHandles : 0\nVM : 8192\nWS : 8192\nPath :" } ]
How to complete address from latitude and longitude on Android?
This example demonstrates how do I complete address from latitude and logitude 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. <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="16sp" tools:context=".MainActivity"> <TextView android:text="" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:text="Show Address" android:id="@+id/btnShowAddress" android:layout_centerHorizontal="true" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/tvAddress" android:layout_alignParentBottom="true" android:layout_marginBottom="134dp" android:layout_alignParentEnd="true" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.Settings; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { Button btnShowAddress; TextView tvAddress; Location location; AppLocationService appLocationService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvAddress = findViewById(R.id.tvAddress); appLocationService = new AppLocationService(MainActivity.this); btnShowAddress = findViewById(R.id.btnShowAddress); btnShowAddress.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { location = appLocationService.getLocation(LocationManager.GPS_PROVIDER); double latitude = 13.1000727; double longitude = 80.2126274; LocationAddress locationAddress = new LocationAddress(); locationAddress.getAddressFromLocation(latitude, longitude, getApplicationContext(), new GeoCodeHandler()); showSettingsAlert(); } public void showSettingsAlert() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); alertDialog.setTitle("SETTINGS"); alertDialog.setMessage("Enable Location Provider! Go to settings menu?"); alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); MainActivity.this.startActivity(intent); } }); alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } class GeoCodeHandler extends Handler { @Override public void handleMessage(Message message) { String locationAddress; switch (message.what) { case 1: Bundle bundle = message.getData(); locationAddress = bundle.getString("address"); break; default: locationAddress = null; } tvAddress.setText(locationAddress); } } }); } } Step 4 − Create a java class (ApplicationService.java) and add the following code import android.annotation.SuppressLint; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; @SuppressLint("Registered") public class AppLocationService extends Service implements LocationListener { protected LocationManager locationManager; Location location; private static final long MIN_DISTANCE_FOR_UPDATE = 10; private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2; public AppLocationService(Context context) { locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE); } @SuppressLint("MissingPermission") public Location getLocation(String provider) { if (locationManager.isProviderEnabled(provider)) { locationManager.requestLocationUpdates(provider, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this); if (locationManager != null) { location = locationManager.getLastKnownLocation(provider); return location; } } return null; } @Override public void onLocationChanged(Location location) { } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public IBinder onBind(Intent arg0) { return null; } } Step 5 − Create a java class (LocationAddress.java) and add the following code − import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.IOException; import java.util.List; import java.util.Locale; class LocationAddress { private static final String TAG = "LocationAddress"; static void getAddressFromLocation(final double latitude, final double longitude, final Context context, final Handler handler) { Thread thread = new Thread() { @Override public void run() { Geocoder geocoder = new Geocoder(context, Locale.getDefault()); String result = null; try { List<Address> addressList = geocoder.getFromLocation( latitude, longitude, 1); if (addressList != null && addressList.size() > 0) { Address address = addressList.get(0); StringBuilder sb = new StringBuilder(); for (int i = 0; i < address.getMaxAddressLineIndex(); i++) { sb.append(address.getAddressLine(i)).append("\n"); } sb.append(address.getLocality()).append("\n"); sb.append(address.getPostalCode()).append("\n"); sb.append(address.getCountryName()); result = sb.toString(); } } catch (IOException e) { Log.e(TAG, "Unable connect to Geocoder", e); } finally { Message message = Message.obtain(); message.setTarget(handler); if (result != null) { message.what = 1; Bundle bundle = new Bundle(); result = "Latitude: " + latitude + " Longitude: " + longitude + "\n\nAddress:\n" + result; bundle.putString("address", result); message.setData(bundle); } else { message.what = 1; Bundle bundle = new Bundle(); result = "Latitude: " + latitude + " Longitude: " + longitude + "\n Unable to get address for this lat-long."; bundle.putString("address" , result); message.setData(bundle); } message.sendToTarget(); } } }; thread.start(); } } Step 6 − 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"> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
[ { "code": null, "e": 1153, "s": 1062, "text": "This example demonstrates how do I complete address from latitude and logitude in android." }, { "code": null, "e": 1282, "s": 1153, "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": 1347, "s": 1282, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2308, "s": 1347, "text": "<RelativeLayout\n 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 android:padding=\"16sp\"\n tools:context=\".MainActivity\">\n <TextView\n android:text=\"\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textView\" />\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"40dp\"\n android:text=\"Show Address\"\n android:id=\"@+id/btnShowAddress\"\n android:layout_centerHorizontal=\"true\" />\n <TextView\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/tvAddress\"\n android:layout_alignParentBottom=\"true\"\n android:layout_marginBottom=\"134dp\"\n android:layout_alignParentEnd=\"true\" />\n</RelativeLayout>" }, { "code": null, "e": 2365, "s": 2308, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5311, "s": 2365, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.app.AlertDialog;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.location.Location;\nimport android.location.LocationManager;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.provider.Settings;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n Button btnShowAddress;\n TextView tvAddress;\n Location location;\n AppLocationService appLocationService;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n tvAddress = findViewById(R.id.tvAddress);\n appLocationService = new\n AppLocationService(MainActivity.this);\n btnShowAddress = findViewById(R.id.btnShowAddress);\n btnShowAddress.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View arg0) {\n location = appLocationService.getLocation(LocationManager.GPS_PROVIDER);\n double latitude = 13.1000727;\n double longitude = 80.2126274;\n LocationAddress locationAddress = new LocationAddress();\n locationAddress.getAddressFromLocation(latitude, longitude,\n getApplicationContext(), new GeoCodeHandler());\n showSettingsAlert();\n }\n public void showSettingsAlert() {\n AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);\n alertDialog.setTitle(\"SETTINGS\");\n alertDialog.setMessage(\"Enable Location\n Provider! Go to settings menu?\");\n alertDialog.setPositiveButton(\"Settings\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);\n MainActivity.this.startActivity(intent);\n }\n });\n alertDialog.setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n dialog.cancel();\n }\n });\n alertDialog.show();\n }\n class GeoCodeHandler extends Handler {\n @Override\n public void handleMessage(Message message) {\n String locationAddress;\n switch (message.what) {\n case 1:\n Bundle bundle = message.getData();\n locationAddress = bundle.getString(\"address\");\n break;\n default:\n locationAddress = null;\n }\n tvAddress.setText(locationAddress);\n }\n }\n });\n }\n}" }, { "code": null, "e": 5393, "s": 5311, "text": "Step 4 − Create a java class (ApplicationService.java) and add the following code" }, { "code": null, "e": 6982, "s": 5393, "text": "import android.annotation.SuppressLint;\nimport android.app.Service;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.location.Location;\nimport android.location.LocationListener;\nimport android.location.LocationManager;\nimport android.os.Bundle;\nimport android.os.IBinder;\n@SuppressLint(\"Registered\")\npublic class AppLocationService extends Service implements LocationListener {\n protected LocationManager locationManager;\n Location location;\n private static final long MIN_DISTANCE_FOR_UPDATE = 10;\n private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;\n public AppLocationService(Context context) {\n locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);\n }\n @SuppressLint(\"MissingPermission\")\n public Location getLocation(String provider) {\n if (locationManager.isProviderEnabled(provider)) {\n locationManager.requestLocationUpdates(provider,\n MIN_TIME_FOR_UPDATE,\n MIN_DISTANCE_FOR_UPDATE, this);\n if (locationManager != null) {\n location = locationManager.getLastKnownLocation(provider);\n return location;\n }\n }\n return null;\n }\n @Override\n public void onLocationChanged(Location location) {\n }\n @Override\n public void onProviderDisabled(String provider) {\n }\n @Override\n public void onProviderEnabled(String provider) {\n }\n @Override\n public void onStatusChanged(String provider, int status, Bundle extras) {\n }\n @Override\n public IBinder onBind(Intent arg0) {\n return null;\n }\n}" }, { "code": null, "e": 7063, "s": 6982, "text": "Step 5 − Create a java class (LocationAddress.java) and add the following code −" }, { "code": null, "e": 9626, "s": 7063, "text": "import android.content.Context;\nimport android.location.Address;\nimport android.location.Geocoder;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.util.Log;\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Locale;\nclass LocationAddress {\n private static final String TAG = \"LocationAddress\";\n static void getAddressFromLocation(final double latitude,\n final double longitude, final Context context, final Handler\n handler) {\n Thread thread = new Thread() {\n @Override\n public void run() {\n Geocoder geocoder = new Geocoder(context,\n Locale.getDefault());\n String result = null;\n try {\n List<Address> addressList =\n geocoder.getFromLocation(\n latitude, longitude, 1);\n if (addressList != null &&\n addressList.size() > 0) {\n Address address = addressList.get(0);\n StringBuilder sb = new\n StringBuilder();\n for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {\n sb.append(address.getAddressLine(i)).append(\"\\n\");\n }\n sb.append(address.getLocality()).append(\"\\n\");\n sb.append(address.getPostalCode()).append(\"\\n\");\n sb.append(address.getCountryName());\n result = sb.toString();\n }\n } catch (IOException e) {\n Log.e(TAG, \"Unable connect to Geocoder\", e);\n } finally {\n Message message = Message.obtain();\n message.setTarget(handler);\n if (result != null) {\n message.what = 1;\n Bundle bundle = new Bundle();\n result = \"Latitude: \" + latitude + \" Longitude: \" + longitude +\n \"\\n\\nAddress:\\n\" + result;\n bundle.putString(\"address\", result);\n message.setData(bundle);\n } else {\n message.what = 1;\n Bundle bundle = new Bundle();\n result = \"Latitude: \" + latitude + \" Longitude: \" + longitude +\n \"\\n Unable to get address for\n this lat-long.\";\n bundle.putString(\"address\" , result);\n message.setData(bundle);\n }\n message.sendToTarget();\n }\n }\n };\n thread.start();\n }\n}" }, { "code": null, "e": 9681, "s": 9626, "text": "Step 6 − Add the following code to androidManifest.xml" }, { "code": null, "e": 10556, "s": 9681, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <uses-permission\n android:name=\"android.permission.ACCESS_COARSE_LOCATION\" />\n <uses-permission\n android:name=\"android.permission.ACCESS_FINE_LOCATION\"/>\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\n android:name=\"android.intent.action.MAIN\" />\n <category\n android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 10903, "s": 10556, "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 −" } ]
LocalDate isAfter() method in Java
It can be checked if a particular LocalDate is after the other LocalDate in a timeline using the isAfter() method in the LocalDate class in Java. This method requires a single parameter i.e. the LocalDate object that is to be compared. It returns true if the LocalDate object is after the other LocalDate object and false otherwise. A program that demonstrates this is given as follows − Live Demo import java.time.*; public class Main { public static void main(String[] args) { LocalDate ld1 = LocalDate.parse("2019-02-20"); LocalDate ld2 = LocalDate.parse("2019-02-14"); System.out.println("The LocalDate ld1 is: " + ld1); System.out.println("The LocalDate ld2 is: " + ld2); boolean flag = ld1.isAfter(ld2); if(flag) System.out.println("\nLocalDate object ld1 is after LocalDate object ld2"); else System.out.println("\nLocalDate object ld1 is before LocalDate object ld2"); } } The LocalDate ld1 is: 2019-02-20 The LocalDate ld2 is: 2019-02-14 LocalDate object ld1 is after LocalDate object ld2 Now let us understand the above program. The two LocalDate objects ld1 and ld2 are displayed. It is checked if the LocalDate object ld1 is after the LocalDate object ld2 in the timeline using the isAfter() method. The returned value is displayed using an if statement. A code snippet that demonstrates this is as follows − LocalDate ld1 = LocalDate.parse("2019-02-20"); LocalDate ld2 = LocalDate.parse("2019-02-14"); System.out.println("The LocalDate ld1 is: " + ld1); System.out.println("The LocalDate ld2 is: " + ld2); boolean flag = ld1.isAfter(ld2); if(flag) System.out.println("\nLocalDate object ld1 is after LocalDate object ld2"); else System.out.println("\nLocalDate object ld1 is before LocalDate object ld2");
[ { "code": null, "e": 1395, "s": 1062, "text": "It can be checked if a particular LocalDate is after the other LocalDate in a timeline using the isAfter() method in the LocalDate class in Java. This method requires a single parameter i.e. the LocalDate object that is to be compared. It returns true if the LocalDate object is after the other LocalDate object and false otherwise." }, { "code": null, "e": 1450, "s": 1395, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1461, "s": 1450, "text": " Live Demo" }, { "code": null, "e": 2010, "s": 1461, "text": "import java.time.*;\npublic class Main {\n public static void main(String[] args) {\n LocalDate ld1 = LocalDate.parse(\"2019-02-20\");\n LocalDate ld2 = LocalDate.parse(\"2019-02-14\");\n System.out.println(\"The LocalDate ld1 is: \" + ld1);\n System.out.println(\"The LocalDate ld2 is: \" + ld2);\n boolean flag = ld1.isAfter(ld2);\n if(flag)\n System.out.println(\"\\nLocalDate object ld1 is after LocalDate object ld2\");\n else\n System.out.println(\"\\nLocalDate object ld1 is before LocalDate object ld2\");\n }\n}" }, { "code": null, "e": 2127, "s": 2010, "text": "The LocalDate ld1 is: 2019-02-20\nThe LocalDate ld2 is: 2019-02-14\nLocalDate object ld1 is after LocalDate object ld2" }, { "code": null, "e": 2168, "s": 2127, "text": "Now let us understand the above program." }, { "code": null, "e": 2450, "s": 2168, "text": "The two LocalDate objects ld1 and ld2 are displayed. It is checked if the LocalDate object ld1 is after the LocalDate object ld2 in the timeline using the isAfter() method. The returned value is displayed using an if statement. A code snippet that demonstrates this is as follows −" }, { "code": null, "e": 2854, "s": 2450, "text": "LocalDate ld1 = LocalDate.parse(\"2019-02-20\");\nLocalDate ld2 = LocalDate.parse(\"2019-02-14\");\nSystem.out.println(\"The LocalDate ld1 is: \" + ld1);\nSystem.out.println(\"The LocalDate ld2 is: \" + ld2);\nboolean flag = ld1.isAfter(ld2);\nif(flag)\n System.out.println(\"\\nLocalDate object ld1 is after LocalDate object ld2\");\nelse\n System.out.println(\"\\nLocalDate object ld1 is before LocalDate object ld2\");" } ]
C++ Program to Represent Graph Using Adjacency List
The adjacency list representation of a graph is linked list representation. In this representation we have an array of lists The array size is V. Here V is the number of vertices. In other words, we can say that we have an array to store V number of different lists. If a list header is vertex u, then it signifies that it will hold all of the adjacent vertices of u. This representation takes O(V+2E) for undirected graph, and O(V+E) for directed graph. If the number of edges are increased, then the required space will also be increased. This representation takes O(V+2E) for undirected graph, and O(V+E) for directed graph. If the number of edges are increased, then the required space will also be increased. Input: Output: Input − The u and v of an edge {u,v}, and the adjacency list Output − Adjacency List of the graph G Begin Append v into the list at index u Append u into the list at index v End Live Demo #include<iostream> #include<list> #include<iterator> using namespace std; void displayAdjList(list<int> adj_list[], int v) { for(int i = 0; i<v; i++) { cout << i << "--->"; list<int> :: iterator it; for(it = adj_list[i].begin(); it != adj_list[i].end(); ++it) { cout << *it << " "; } cout << endl; } } void add_edge(list<int> adj_list[], int u, int v) { //add v into the list u, and u into list v adj_list[u].push_back(v); adj_list[v].push_back(u); } main(int argc, char* argv[]) { int v = 6; //there are 6 vertices in the graph //create an array of lists whose size is 6 list<int> adj_list[v]; add_edge(adj_list, 0, 4); add_edge(adj_list, 0, 3); add_edge(adj_list, 1, 2); add_edge(adj_list, 1, 4); add_edge(adj_list, 1, 5); add_edge(adj_list, 2, 3); add_edge(adj_list, 2, 5); add_edge(adj_list, 5, 3); add_edge(adj_list, 5, 4); displayAdjList(adj_list, v); } 0--->4 3 1--->2 4 5 2--->1 3 5 3--->0 2 5 4--->0 1 5 5--->1 2 3 4
[ { "code": null, "e": 1430, "s": 1062, "text": "The adjacency list representation of a graph is linked list representation. In this representation we have an array of lists The array size is V. Here V is the number of vertices. In other words, we can say that we have an array to store V number of different lists. If a list header is vertex u, then it signifies that it will hold all of the adjacent vertices of u." }, { "code": null, "e": 1603, "s": 1430, "text": "This representation takes O(V+2E) for undirected graph, and O(V+E) for directed graph. If the number of edges are increased, then the required space will also be increased." }, { "code": null, "e": 1776, "s": 1603, "text": "This representation takes O(V+2E) for undirected graph, and O(V+E) for directed graph. If the number of edges are increased, then the required space will also be increased." }, { "code": null, "e": 1783, "s": 1776, "text": "Input:" }, { "code": null, "e": 1791, "s": 1783, "text": "Output:" }, { "code": null, "e": 1852, "s": 1791, "text": "Input − The u and v of an edge {u,v}, and the adjacency list" }, { "code": null, "e": 1891, "s": 1852, "text": "Output − Adjacency List of the graph G" }, { "code": null, "e": 1975, "s": 1891, "text": "Begin\n Append v into the list at index u\n Append u into the list at index v\nEnd" }, { "code": null, "e": 1986, "s": 1975, "text": " Live Demo" }, { "code": null, "e": 2936, "s": 1986, "text": "#include<iostream>\n#include<list>\n#include<iterator>\nusing namespace std;\nvoid displayAdjList(list<int> adj_list[], int v) {\n for(int i = 0; i<v; i++) {\n cout << i << \"--->\";\n list<int> :: iterator it;\n for(it = adj_list[i].begin(); it != adj_list[i].end(); ++it) {\n cout << *it << \" \";\n }\n cout << endl;\n }\n}\nvoid add_edge(list<int> adj_list[], int u, int v) { //add v into the list u, and u into list v\n adj_list[u].push_back(v);\n adj_list[v].push_back(u);\n}\nmain(int argc, char* argv[]) {\n int v = 6; //there are 6 vertices in the graph\n //create an array of lists whose size is 6\n list<int> adj_list[v];\n add_edge(adj_list, 0, 4);\n add_edge(adj_list, 0, 3);\n add_edge(adj_list, 1, 2);\n add_edge(adj_list, 1, 4);\n add_edge(adj_list, 1, 5);\n add_edge(adj_list, 2, 3);\n add_edge(adj_list, 2, 5);\n add_edge(adj_list, 5, 3);\n add_edge(adj_list, 5, 4);\n displayAdjList(adj_list, v);\n}" }, { "code": null, "e": 3002, "s": 2936, "text": "0--->4 3\n1--->2 4 5\n2--->1 3 5\n3--->0 2 5\n4--->0 1 5\n5--->1 2 3 4" } ]
Count Vowels Permutation in C++
Suppose we have one number n, we have to count how many strings of length n can be formed using these rules − Each character is a lower case vowel Each vowel 'a' may only be followed by an 'e'. Each vowel 'e' may only be followed by an 'a' or 'i'. Each vowel 'i' may not be followed by another 'i'. Each vowel 'o' may only be followed by an 'i' or 'u'. Each vowel 'u' may only be followed by an 'a'. The answer may be too large, so we will find the answer modulo 10^9 + 7. So, if the input is like 2, then the output will be 10, this is because all possible strings are "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou", "ua". To solve this, we will follow these steps − m = 1^9 + 7 m = 1^9 + 7 Define a function add(), this will take a, b, Define a function add(), this will take a, b, return ((a mod m) + (b mod m)) mod m return ((a mod m) + (b mod m)) mod m Define a function mul(), this will take a, b, Define a function mul(), this will take a, b, return ((a mod m) * (b mod m)) mod m return ((a mod m) * (b mod m)) mod m Define a function solve(), this will take n, Define a function solve(), this will take n, Define an array A of size: 5 x 5 := {{0,1,0,0,0},{1,0,1,0,0},{1,1,0,1,1},{0,0,1,0,1},{1,0,0,0,0}} Define an array A of size: 5 x 5 := {{0,1,0,0,0},{1,0,1,0,0},{1,1,0,1,1},{0,0,1,0,1},{1,0,0,0,0}} Define an array result of size: 5 x 5. Define an array result of size: 5 x 5. for initialize i := 0, when i < 5, update (increase i by 1), do −for initialize j := 0, when j < 5, update (increase j by 1), do −if i is same as j, then, result[i, j] := 1Otherwise,result[i, j] := 0 for initialize i := 0, when i < 5, update (increase i by 1), do − for initialize j := 0, when j < 5, update (increase j by 1), do −if i is same as j, then, result[i, j] := 1Otherwise,result[i, j] := 0 for initialize j := 0, when j < 5, update (increase j by 1), do − if i is same as j, then, result[i, j] := 1 if i is same as j, then, result[i, j] := 1 Otherwise,result[i, j] := 0 Otherwise,result[i, j] := 0 (decrease n by 1) (decrease n by 1) for initialize i := 1, when i <= n, update (increase i by 1), do −results = result * A for initialize i := 1, when i <= n, update (increase i by 1), do − results = result * A results = result * A sum := 0 sum := 0 for initialize i := 0, when i < 5, update (increase i by 1), do −for initialize j := 0, when j < 5, update (increase j by 1), do −sum := add(result[i, j], sum) for initialize i := 0, when i < 5, update (increase i by 1), do − for initialize j := 0, when j < 5, update (increase j by 1), do −sum := add(result[i, j], sum) for initialize j := 0, when j < 5, update (increase j by 1), do − sum := add(result[i, j], sum) sum := add(result[i, j], sum) return sum return sum Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; typedef long long int lli; const lli m = 1e9+7; lli add(lli a, lli b){ return ((a%m) + (b%m))%m; } lli mul(lli a, lli b){ return ((a%m) * (b%m))%m; } class Solution { public: void multiply(lli A[5][5], lli B[5][5]){ lli C[5][5]; for(lli i =0;i<5;i++){ for(lli j=0;j<5;j++){ lli temp =0; for(lli k =0;k<5;k++){ temp = add(temp,mul(A[i][k],B[k][j])); } C[i][j] = temp; } } for(lli i =0;i<5;i++){ for(lli j =0;j<5;j++){ A[i][j] = C[i][j]; } } } lli solve(lli n){ lli A[5][5] = { { 0, 1, 0, 0, 0 }, { 1, 0, 1, 0, 0 }, { 1, 1, 0, 1, 1 }, { 0, 0, 1, 0, 1 }, { 1, 0, 0, 0, 0 } }; lli result[5][5]; for (lli i = 0; i < 5; i++) { for (lli j = 0; j < 5; j++) { if (i == j) result[i][j] = 1; else result[i][j] = 0; } } n--; for (int i = 1; i <= n; i++) multiply(result, A); lli sum = 0; for (lli i = 0; i < 5; i++) { for (lli j = 0; j < 5; j++) { sum = add(result[i][j], sum); } } return sum; } int countVowelPermutation(int n) { return solve(n); } }; main(){ Solution ob; cout << (ob.countVowelPermutation(2)); } 2 10
[ { "code": null, "e": 1535, "s": 1062, "text": "Suppose we have one number n, we have to count how many strings of length n can be formed using these rules − Each character is a lower case vowel Each vowel 'a' may only be followed by an 'e'. Each vowel 'e' may only be followed by an 'a' or 'i'. Each vowel 'i' may not be followed by another 'i'. Each vowel 'o' may only be followed by an 'i' or 'u'. Each vowel 'u' may only be followed by an 'a'. The answer may be too large, so we will find the answer modulo 10^9 + 7." }, { "code": null, "e": 1692, "s": 1535, "text": "So, if the input is like 2, then the output will be 10, this is because all possible strings are \"ae\", \"ea\", \"ei\", \"ia\", \"ie\", \"io\", \"iu\", \"oi\", \"ou\", \"ua\"." }, { "code": null, "e": 1736, "s": 1692, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1748, "s": 1736, "text": "m = 1^9 + 7" }, { "code": null, "e": 1760, "s": 1748, "text": "m = 1^9 + 7" }, { "code": null, "e": 1806, "s": 1760, "text": "Define a function add(), this will take a, b," }, { "code": null, "e": 1852, "s": 1806, "text": "Define a function add(), this will take a, b," }, { "code": null, "e": 1889, "s": 1852, "text": "return ((a mod m) + (b mod m)) mod m" }, { "code": null, "e": 1926, "s": 1889, "text": "return ((a mod m) + (b mod m)) mod m" }, { "code": null, "e": 1972, "s": 1926, "text": "Define a function mul(), this will take a, b," }, { "code": null, "e": 2018, "s": 1972, "text": "Define a function mul(), this will take a, b," }, { "code": null, "e": 2055, "s": 2018, "text": "return ((a mod m) * (b mod m)) mod m" }, { "code": null, "e": 2092, "s": 2055, "text": "return ((a mod m) * (b mod m)) mod m" }, { "code": null, "e": 2137, "s": 2092, "text": "Define a function solve(), this will take n," }, { "code": null, "e": 2182, "s": 2137, "text": "Define a function solve(), this will take n," }, { "code": null, "e": 2280, "s": 2182, "text": "Define an array A of size: 5 x 5 := {{0,1,0,0,0},{1,0,1,0,0},{1,1,0,1,1},{0,0,1,0,1},{1,0,0,0,0}}" }, { "code": null, "e": 2378, "s": 2280, "text": "Define an array A of size: 5 x 5 := {{0,1,0,0,0},{1,0,1,0,0},{1,1,0,1,1},{0,0,1,0,1},{1,0,0,0,0}}" }, { "code": null, "e": 2417, "s": 2378, "text": "Define an array result of size: 5 x 5." }, { "code": null, "e": 2456, "s": 2417, "text": "Define an array result of size: 5 x 5." }, { "code": null, "e": 2656, "s": 2456, "text": "for initialize i := 0, when i < 5, update (increase i by 1), do −for initialize j := 0, when j < 5, update (increase j by 1), do −if i is same as j, then, result[i, j] := 1Otherwise,result[i, j] := 0" }, { "code": null, "e": 2722, "s": 2656, "text": "for initialize i := 0, when i < 5, update (increase i by 1), do −" }, { "code": null, "e": 2857, "s": 2722, "text": "for initialize j := 0, when j < 5, update (increase j by 1), do −if i is same as j, then, result[i, j] := 1Otherwise,result[i, j] := 0" }, { "code": null, "e": 2923, "s": 2857, "text": "for initialize j := 0, when j < 5, update (increase j by 1), do −" }, { "code": null, "e": 2966, "s": 2923, "text": "if i is same as j, then, result[i, j] := 1" }, { "code": null, "e": 3009, "s": 2966, "text": "if i is same as j, then, result[i, j] := 1" }, { "code": null, "e": 3037, "s": 3009, "text": "Otherwise,result[i, j] := 0" }, { "code": null, "e": 3065, "s": 3037, "text": "Otherwise,result[i, j] := 0" }, { "code": null, "e": 3083, "s": 3065, "text": "(decrease n by 1)" }, { "code": null, "e": 3101, "s": 3083, "text": "(decrease n by 1)" }, { "code": null, "e": 3188, "s": 3101, "text": "for initialize i := 1, when i <= n, update (increase i by 1), do −results = result * A" }, { "code": null, "e": 3255, "s": 3188, "text": "for initialize i := 1, when i <= n, update (increase i by 1), do −" }, { "code": null, "e": 3276, "s": 3255, "text": "results = result * A" }, { "code": null, "e": 3297, "s": 3276, "text": "results = result * A" }, { "code": null, "e": 3306, "s": 3297, "text": "sum := 0" }, { "code": null, "e": 3315, "s": 3306, "text": "sum := 0" }, { "code": null, "e": 3475, "s": 3315, "text": "for initialize i := 0, when i < 5, update (increase i by 1), do −for initialize j := 0, when j < 5, update (increase j by 1), do −sum := add(result[i, j], sum)" }, { "code": null, "e": 3541, "s": 3475, "text": "for initialize i := 0, when i < 5, update (increase i by 1), do −" }, { "code": null, "e": 3636, "s": 3541, "text": "for initialize j := 0, when j < 5, update (increase j by 1), do −sum := add(result[i, j], sum)" }, { "code": null, "e": 3702, "s": 3636, "text": "for initialize j := 0, when j < 5, update (increase j by 1), do −" }, { "code": null, "e": 3732, "s": 3702, "text": "sum := add(result[i, j], sum)" }, { "code": null, "e": 3762, "s": 3732, "text": "sum := add(result[i, j], sum)" }, { "code": null, "e": 3773, "s": 3762, "text": "return sum" }, { "code": null, "e": 3784, "s": 3773, "text": "return sum" }, { "code": null, "e": 3854, "s": 3784, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3865, "s": 3854, "text": " Live Demo" }, { "code": null, "e": 5268, "s": 3865, "text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int lli;\nconst lli m = 1e9+7;\nlli add(lli a, lli b){\n return ((a%m) + (b%m))%m;\n}\nlli mul(lli a, lli b){\n return ((a%m) * (b%m))%m;\n}\nclass Solution {\n public:\n void multiply(lli A[5][5], lli B[5][5]){\n lli C[5][5];\n for(lli i =0;i<5;i++){\n for(lli j=0;j<5;j++){\n lli temp =0;\n for(lli k =0;k<5;k++){\n temp = add(temp,mul(A[i][k],B[k][j]));\n }\n C[i][j] = temp;\n }\n }\n for(lli i =0;i<5;i++){\n for(lli j =0;j<5;j++){\n A[i][j] = C[i][j];\n }\n }\n }\n lli solve(lli n){\n lli A[5][5] = { { 0, 1, 0, 0, 0 }, { 1, 0, 1, 0, 0 }, { 1, 1,\n 0, 1, 1 }, { 0, 0, 1, 0, 1 }, { 1, 0, 0, 0, 0 } };\n lli result[5][5];\n for (lli i = 0; i < 5; i++) {\n for (lli j = 0; j < 5; j++) {\n if (i == j)\n result[i][j] = 1;\n else\n result[i][j] = 0;\n }\n }\n n--;\n for (int i = 1; i <= n; i++)\n multiply(result, A);\n lli sum = 0;\n for (lli i = 0; i < 5; i++) {\n for (lli j = 0; j < 5; j++) {\n sum = add(result[i][j], sum);\n }\n }\n return sum;\n }\n int countVowelPermutation(int n) {\n return solve(n);\n }\n};\nmain(){\n Solution ob;\n cout << (ob.countVowelPermutation(2));\n}" }, { "code": null, "e": 5270, "s": 5268, "text": "2" }, { "code": null, "e": 5273, "s": 5270, "text": "10" } ]
What is conditional compilation in C language?
In C programming language, several directives control the selective compilation of portions of the program code. They are as follows − #if #else #elif #endif The general form of #if is as follows − #if constant_expression statement sequence #endif #else works much like the C keyword else. #elif means "else if" and establishes an if else-if compilation chain. Amongst other things, #if provides an alternative method of "commenting out" code. For example, #if 0 printf("#d", total); #endif Here, the compiler will ignore printf("#d", total); #ifdef and #ifndef #ifdef means "if defined", and is terminated by an #endif. #indef means "if not defined". #undef #undef removes a previously defined definition. #line #line changes the contents of __LINE__ which contains the line number of the currently compiled code and __FILE__ which is a string that contains the name of the source file being compiled. Both of which are predefined identifiers in the compiler. #pragma The #pragma directive is an implementation-defined directive which allows the various instructions to be given to the compiler. Following is the C program to demonstrate #ifdef, #ifndef , #else and #endif − Live Demo # include <stdio.h> # define a 10 void main(){ #ifdef a printf("\n Hello I am here.."); #endif #ifndef a printf("\n Not defined "); #else printf("\n R u There "); #endif } When the above program is executed, it produces the following result − Hello I am here.. R u There
[ { "code": null, "e": 1197, "s": 1062, "text": "In C programming language, several directives control the selective compilation of portions of the program code. They are as follows −" }, { "code": null, "e": 1201, "s": 1197, "text": "#if" }, { "code": null, "e": 1207, "s": 1201, "text": "#else" }, { "code": null, "e": 1213, "s": 1207, "text": "#elif" }, { "code": null, "e": 1220, "s": 1213, "text": "#endif" }, { "code": null, "e": 1260, "s": 1220, "text": "The general form of #if is as follows −" }, { "code": null, "e": 1313, "s": 1260, "text": "#if constant_expression\n statement sequence\n#endif" }, { "code": null, "e": 1355, "s": 1313, "text": "#else works much like the C keyword else." }, { "code": null, "e": 1426, "s": 1355, "text": "#elif means \"else if\" and establishes an if else-if compilation chain." }, { "code": null, "e": 1509, "s": 1426, "text": "Amongst other things, #if provides an alternative method of \"commenting out\" code." }, { "code": null, "e": 1522, "s": 1509, "text": "For example," }, { "code": null, "e": 1559, "s": 1522, "text": "#if 0\n printf(\"#d\", total);\n#endif" }, { "code": null, "e": 1611, "s": 1559, "text": "Here, the compiler will ignore printf(\"#d\", total);" }, { "code": null, "e": 1630, "s": 1611, "text": "#ifdef and #ifndef" }, { "code": null, "e": 1689, "s": 1630, "text": "#ifdef means \"if defined\", and is terminated by an #endif." }, { "code": null, "e": 1720, "s": 1689, "text": "#indef means \"if not defined\"." }, { "code": null, "e": 1727, "s": 1720, "text": "#undef" }, { "code": null, "e": 1775, "s": 1727, "text": "#undef removes a previously defined definition." }, { "code": null, "e": 1781, "s": 1775, "text": "#line" }, { "code": null, "e": 2029, "s": 1781, "text": "#line changes the contents of __LINE__ which contains the line number of the currently compiled code and __FILE__ which is a string that contains the name of the source file being compiled. Both of which are predefined identifiers in the compiler." }, { "code": null, "e": 2037, "s": 2029, "text": "#pragma" }, { "code": null, "e": 2165, "s": 2037, "text": "The #pragma directive is an implementation-defined directive which allows the various instructions to be given to the compiler." }, { "code": null, "e": 2244, "s": 2165, "text": "Following is the C program to demonstrate #ifdef, #ifndef , #else and #endif −" }, { "code": null, "e": 2255, "s": 2244, "text": " Live Demo" }, { "code": null, "e": 2451, "s": 2255, "text": "# include <stdio.h>\n# define a 10\nvoid main(){\n #ifdef a\n printf(\"\\n Hello I am here..\");\n #endif\n #ifndef a\n printf(\"\\n Not defined \");\n #else\n printf(\"\\n R u There \");\n #endif\n}" }, { "code": null, "e": 2522, "s": 2451, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2550, "s": 2522, "text": "Hello I am here..\nR u There" } ]
Creating a multiple Selection using Tkinter - GeeksforGeeks
21 Apr, 2020 Prerequisites: Python Tkinter – ListBox Widget, Scrollable ListBox in Python-tkinter Tkinter is a GUI library in python which is easy to read and understand. In Tkinter, multiple selections can be done using the List box widget. Generally, a Listbox displays different items in the form of a list. A list box widget provides one or more selections of items from a list. There are many options available in a Listbox widget that makes the user select multiple options. By assigning the select mode option as multiple, the user can able to select multiple options. If the select mode option is single then only one option can be selected by the user.The selectmode option of a listbox widget can be single, browse, multiple or extended. single – Selects one line of text. browse – It is a default option where the user can select one line of text. multiple – Selects multiple lines of text without dragging from first line of option to last line. extended – User can select and drag adjacent multiple lines of text. Syntax : list_box = Listbox(root, options, ....) Example 1: Python program displaying limited items in the listbox. # Python program demonstrating# Multiple selection in Listbox widget from tkinter import * window = Tk()window.geometry('100x150') # Choosing selectmode as multiple # for selecting multiple optionslist = Listbox(window, selectmode = "multiple") # Widget expands horizontally and# vertically by assigning both to # fill optionlist.pack(expand = YES, fill = "both") # Taking a list 'x' with the items # as languagesx = ["C", "C++", "Java", "Python", "R", "Go", "Ruby", "JavaScript", "Swift"] for each_item in range(len(x)): list.insert(END, x[each_item]) # coloring alternative lines of listbox list.itemconfig(each_item, bg = "yellow" if each_item % 2 == 0 else "cyan") window.mainloop() Output : From the above multiple selection Listbox, the user can select multiple options. As there are limited items in the Listbox that fit into the prescribed size, the user can able to see all the items. But if there are more items to be displayed to the user then all the items are not visible at once in a Listbox. Hence, attaching a scrollbar to a Listbox is necessary if there are more items to be displayed in a list. This can be done by the yscrollcommand option(to scroll vertically) in Listbox. Example 2: Python program displaying List box with attached scroll bar. # Python program demonstrating Multiple selection# in Listbox widget with a scrollbar from tkinter import * window = Tk()window.title('Multiple selection') # for scrolling verticallyyscrollbar = Scrollbar(window)yscrollbar.pack(side = RIGHT, fill = Y) label = Label(window, text = "Select the languages below : ", font = ("Times New Roman", 10), padx = 10, pady = 10)label.pack()list = Listbox(window, selectmode = "multiple", yscrollcommand = yscrollbar.set) # Widget expands horizontally and # vertically by assigning both to# fill optionlist.pack(padx = 10, pady = 10, expand = YES, fill = "both") x =["C", "C++", "C#", "Java", "Python", "R", "Go", "Ruby", "JavaScript", "Swift", "SQL", "Perl", "XML"] for each_item in range(len(x)): list.insert(END, x[each_item]) list.itemconfig(each_item, bg = "lime") # Attach listbox to vertical scrollbaryscrollbar.config(command = list.yview)window.mainloop() Output : Python-tkinter Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Convert string to integer in Python Python infinity How to set input type date in dd-mm-yyyy format using HTML ? Matplotlib.pyplot.title() in Python Factory method design pattern in Java
[ { "code": null, "e": 24318, "s": 24290, "text": "\n21 Apr, 2020" }, { "code": null, "e": 24403, "s": 24318, "text": "Prerequisites: Python Tkinter – ListBox Widget, Scrollable ListBox in Python-tkinter" }, { "code": null, "e": 25053, "s": 24403, "text": "Tkinter is a GUI library in python which is easy to read and understand. In Tkinter, multiple selections can be done using the List box widget. Generally, a Listbox displays different items in the form of a list. A list box widget provides one or more selections of items from a list. There are many options available in a Listbox widget that makes the user select multiple options. By assigning the select mode option as multiple, the user can able to select multiple options. If the select mode option is single then only one option can be selected by the user.The selectmode option of a listbox widget can be single, browse, multiple or extended." }, { "code": null, "e": 25088, "s": 25053, "text": "single – Selects one line of text." }, { "code": null, "e": 25164, "s": 25088, "text": "browse – It is a default option where the user can select one line of text." }, { "code": null, "e": 25263, "s": 25164, "text": "multiple – Selects multiple lines of text without dragging from first line of option to last line." }, { "code": null, "e": 25332, "s": 25263, "text": "extended – User can select and drag adjacent multiple lines of text." }, { "code": null, "e": 25341, "s": 25332, "text": "Syntax :" }, { "code": null, "e": 25382, "s": 25341, "text": "list_box = Listbox(root, options, ....)\n" }, { "code": null, "e": 25449, "s": 25382, "text": "Example 1: Python program displaying limited items in the listbox." }, { "code": "# Python program demonstrating# Multiple selection in Listbox widget from tkinter import * window = Tk()window.geometry('100x150') # Choosing selectmode as multiple # for selecting multiple optionslist = Listbox(window, selectmode = \"multiple\") # Widget expands horizontally and# vertically by assigning both to # fill optionlist.pack(expand = YES, fill = \"both\") # Taking a list 'x' with the items # as languagesx = [\"C\", \"C++\", \"Java\", \"Python\", \"R\", \"Go\", \"Ruby\", \"JavaScript\", \"Swift\"] for each_item in range(len(x)): list.insert(END, x[each_item]) # coloring alternative lines of listbox list.itemconfig(each_item, bg = \"yellow\" if each_item % 2 == 0 else \"cyan\") window.mainloop()", "e": 26187, "s": 25449, "text": null }, { "code": null, "e": 26196, "s": 26187, "text": "Output :" }, { "code": null, "e": 26693, "s": 26196, "text": "From the above multiple selection Listbox, the user can select multiple options. As there are limited items in the Listbox that fit into the prescribed size, the user can able to see all the items. But if there are more items to be displayed to the user then all the items are not visible at once in a Listbox. Hence, attaching a scrollbar to a Listbox is necessary if there are more items to be displayed in a list. This can be done by the yscrollcommand option(to scroll vertically) in Listbox." }, { "code": null, "e": 26765, "s": 26693, "text": "Example 2: Python program displaying List box with attached scroll bar." }, { "code": "# Python program demonstrating Multiple selection# in Listbox widget with a scrollbar from tkinter import * window = Tk()window.title('Multiple selection') # for scrolling verticallyyscrollbar = Scrollbar(window)yscrollbar.pack(side = RIGHT, fill = Y) label = Label(window, text = \"Select the languages below : \", font = (\"Times New Roman\", 10), padx = 10, pady = 10)label.pack()list = Listbox(window, selectmode = \"multiple\", yscrollcommand = yscrollbar.set) # Widget expands horizontally and # vertically by assigning both to# fill optionlist.pack(padx = 10, pady = 10, expand = YES, fill = \"both\") x =[\"C\", \"C++\", \"C#\", \"Java\", \"Python\", \"R\", \"Go\", \"Ruby\", \"JavaScript\", \"Swift\", \"SQL\", \"Perl\", \"XML\"] for each_item in range(len(x)): list.insert(END, x[each_item]) list.itemconfig(each_item, bg = \"lime\") # Attach listbox to vertical scrollbaryscrollbar.config(command = list.yview)window.mainloop()", "e": 27761, "s": 26765, "text": null }, { "code": null, "e": 27770, "s": 27761, "text": "Output :" }, { "code": null, "e": 27785, "s": 27770, "text": "Python-tkinter" }, { "code": null, "e": 27792, "s": 27785, "text": "Python" }, { "code": null, "e": 27808, "s": 27792, "text": "Write From Home" }, { "code": null, "e": 27906, "s": 27808, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27938, "s": 27906, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27980, "s": 27938, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28036, "s": 27980, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28078, "s": 28036, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28133, "s": 28078, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28169, "s": 28133, "text": "Convert string to integer in Python" }, { "code": null, "e": 28185, "s": 28169, "text": "Python infinity" }, { "code": null, "e": 28246, "s": 28185, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28282, "s": 28246, "text": "Matplotlib.pyplot.title() in Python" } ]
Stream of Characters in C++
Suppose we want to implement the StreamChecker class as follows − StreamChecker(words) − This is the constructor, this initializes the data structure with the given words. StreamChecker(words) − This is the constructor, this initializes the data structure with the given words. query(letter) − This returns true when for some k >= 1, the last k characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the given list. query(letter) − This returns true when for some k >= 1, the last k characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the given list. So, if the input is like word list = ["ce", "g", "lm"], then call query many times for [a,b,c,e,f,g,h,i,j,k,l,m], then the output will be true for e, g, m, and false for others. To solve this, we will follow these steps − Define a node structure, there is an array of 26 nodes, and isEnd flag Define a node structure, there is an array of 26 nodes, and isEnd flag initially isEnd is false, and the child array is filled with null. initially isEnd is false, and the child array is filled with null. Define a node head Define a node head Make an array of nodes waitList Make an array of nodes waitList Define a function insertNode(), this will take head, s,curr := headfor initialize i := 0, when i < size of s, update (increase i by 1), do−x := s[i]if child[x - 'a'] of curr is not-null, then −curr.child[x - 'a'] = create a new node Nodecurr := curr.child[x - 'a']isEnd of curr := true Define a function insertNode(), this will take head, s, curr := head curr := head for initialize i := 0, when i < size of s, update (increase i by 1), do−x := s[i]if child[x - 'a'] of curr is not-null, then −curr.child[x - 'a'] = create a new node Nodecurr := curr.child[x - 'a'] for initialize i := 0, when i < size of s, update (increase i by 1), do− x := s[i] x := s[i] if child[x - 'a'] of curr is not-null, then −curr.child[x - 'a'] = create a new node Node if child[x - 'a'] of curr is not-null, then − curr.child[x - 'a'] = create a new node Node curr.child[x - 'a'] = create a new node Node curr := curr.child[x - 'a'] curr := curr.child[x - 'a'] isEnd of curr := true isEnd of curr := true From the initializer do thishead := create a new nodefor initialize i := 0, when i < size of words, update (increase i by 1), do −insertNode(head, words[i])curr := head From the initializer do this head := create a new node head := create a new node for initialize i := 0, when i < size of words, update (increase i by 1), do −insertNode(head, words[i]) for initialize i := 0, when i < size of words, update (increase i by 1), do − insertNode(head, words[i]) insertNode(head, words[i]) curr := head curr := head Define a function query(), this will take x,make one array of nodes tempif head.child[x - 'a'], then −insert head at the end of waitListret := falsefor initialize i := 0, when i < size of waitList, update (increase i by 1), do −curr := waitList[i]if curr.child[x - 'a'], thencurr := child[x - 'a'] of currinsert curr at the end of tempret := ret OR isEnd of currswap(temp, waitList)return ret Define a function query(), this will take x, make one array of nodes temp make one array of nodes temp if head.child[x - 'a'], then −insert head at the end of waitList if head.child[x - 'a'], then − insert head at the end of waitList insert head at the end of waitList ret := false ret := false for initialize i := 0, when i < size of waitList, update (increase i by 1), do −curr := waitList[i]if curr.child[x - 'a'], thencurr := child[x - 'a'] of currinsert curr at the end of tempret := ret OR isEnd of curr for initialize i := 0, when i < size of waitList, update (increase i by 1), do − curr := waitList[i] curr := waitList[i] if curr.child[x - 'a'], thencurr := child[x - 'a'] of currinsert curr at the end of tempret := ret OR isEnd of curr if curr.child[x - 'a'], then curr := child[x - 'a'] of curr curr := child[x - 'a'] of curr insert curr at the end of temp insert curr at the end of temp ret := ret OR isEnd of curr ret := ret OR isEnd of curr swap(temp, waitList) swap(temp, waitList) return ret return ret Let us see the following implementation to get better understanding − #include <bits/stdc++.h> using namespace std; struct Node { Node* child[26]; bool isEnd; Node(){ isEnd = false; for (int i = 0; i < 26; i++) child[i] = NULL; } }; class StreamChecker { public: Node* head; vector<Node*> waitList; void insertNode(Node* head, string& s){ Node* curr = head; for (int i = 0; i < s.size(); i++) { char x = s[i]; if (!curr->child[x - 'a']) { curr->child[x - 'a'] = new Node(); } curr = curr->child[x - 'a']; } curr->isEnd = true; } StreamChecker(vector<string>& words){ head = new Node(); for (int i = 0; i < words.size(); i++) { insertNode(head, words[i]); } Node* curr = head; } bool query(char x){ vector<Node*> temp; if (head->child[x - 'a']) { waitList.push_back(head); } bool ret = false; for (int i = 0; i < waitList.size(); i++) { Node* curr = waitList[i]; if (curr->child[x - 'a']) { curr = curr->child[x - 'a']; temp.push_back(curr); ret |= curr->isEnd; } } swap(temp, waitList); return ret; } }; main(){ vector<string> v = {"ce","g","lm"}; StreamChecker ob(v); cout << (ob.query('a')) << endl; cout << (ob.query('b')) << endl; cout << (ob.query('c')) << endl; cout << (ob.query('e')) << endl; cout << (ob.query('f')) << endl; cout << (ob.query('g')) << endl; cout << (ob.query('h')) << endl; cout << (ob.query('i')) << endl; cout << (ob.query('j')) << endl; cout << (ob.query('k')) << endl; cout << (ob.query('l')) << endl; cout << (ob.query('m')); } "ce","g","lm", query(), 0 0 0 1 0 1 0 0 0 0 0 1
[ { "code": null, "e": 1128, "s": 1062, "text": "Suppose we want to implement the StreamChecker class as follows −" }, { "code": null, "e": 1234, "s": 1128, "text": "StreamChecker(words) − This is the constructor, this initializes the data structure with the given words." }, { "code": null, "e": 1340, "s": 1234, "text": "StreamChecker(words) − This is the constructor, this initializes the data structure with the given words." }, { "code": null, "e": 1537, "s": 1340, "text": "query(letter) − This returns true when for some k >= 1, the last k characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the given list." }, { "code": null, "e": 1734, "s": 1537, "text": "query(letter) − This returns true when for some k >= 1, the last k characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the given list." }, { "code": null, "e": 1912, "s": 1734, "text": "So, if the input is like word list = [\"ce\", \"g\", \"lm\"], then call query many times for [a,b,c,e,f,g,h,i,j,k,l,m], then the output will be true for e, g, m, and false for others." }, { "code": null, "e": 1956, "s": 1912, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 2027, "s": 1956, "text": "Define a node structure, there is an array of 26 nodes, and isEnd flag" }, { "code": null, "e": 2098, "s": 2027, "text": "Define a node structure, there is an array of 26 nodes, and isEnd flag" }, { "code": null, "e": 2165, "s": 2098, "text": "initially isEnd is false, and the child array is filled with null." }, { "code": null, "e": 2232, "s": 2165, "text": "initially isEnd is false, and the child array is filled with null." }, { "code": null, "e": 2251, "s": 2232, "text": "Define a node head" }, { "code": null, "e": 2270, "s": 2251, "text": "Define a node head" }, { "code": null, "e": 2302, "s": 2270, "text": "Make an array of nodes waitList" }, { "code": null, "e": 2334, "s": 2302, "text": "Make an array of nodes waitList" }, { "code": null, "e": 2620, "s": 2334, "text": "Define a function insertNode(), this will take head, s,curr := headfor initialize i := 0, when i < size of s, update (increase i by 1), do−x := s[i]if child[x - 'a'] of curr is not-null, then −curr.child[x - 'a'] = create a new node Nodecurr := curr.child[x - 'a']isEnd of curr := true" }, { "code": null, "e": 2676, "s": 2620, "text": "Define a function insertNode(), this will take head, s," }, { "code": null, "e": 2689, "s": 2676, "text": "curr := head" }, { "code": null, "e": 2702, "s": 2689, "text": "curr := head" }, { "code": null, "e": 2900, "s": 2702, "text": "for initialize i := 0, when i < size of s, update (increase i by 1), do−x := s[i]if child[x - 'a'] of curr is not-null, then −curr.child[x - 'a'] = create a new node Nodecurr := curr.child[x - 'a']" }, { "code": null, "e": 2973, "s": 2900, "text": "for initialize i := 0, when i < size of s, update (increase i by 1), do−" }, { "code": null, "e": 2983, "s": 2973, "text": "x := s[i]" }, { "code": null, "e": 2993, "s": 2983, "text": "x := s[i]" }, { "code": null, "e": 3083, "s": 2993, "text": "if child[x - 'a'] of curr is not-null, then −curr.child[x - 'a'] = create a new node Node" }, { "code": null, "e": 3129, "s": 3083, "text": "if child[x - 'a'] of curr is not-null, then −" }, { "code": null, "e": 3174, "s": 3129, "text": "curr.child[x - 'a'] = create a new node Node" }, { "code": null, "e": 3219, "s": 3174, "text": "curr.child[x - 'a'] = create a new node Node" }, { "code": null, "e": 3247, "s": 3219, "text": "curr := curr.child[x - 'a']" }, { "code": null, "e": 3275, "s": 3247, "text": "curr := curr.child[x - 'a']" }, { "code": null, "e": 3297, "s": 3275, "text": "isEnd of curr := true" }, { "code": null, "e": 3319, "s": 3297, "text": "isEnd of curr := true" }, { "code": null, "e": 3488, "s": 3319, "text": "From the initializer do thishead := create a new nodefor initialize i := 0, when i < size of words, update (increase i by 1), do −insertNode(head, words[i])curr := head" }, { "code": null, "e": 3517, "s": 3488, "text": "From the initializer do this" }, { "code": null, "e": 3543, "s": 3517, "text": "head := create a new node" }, { "code": null, "e": 3569, "s": 3543, "text": "head := create a new node" }, { "code": null, "e": 3673, "s": 3569, "text": "for initialize i := 0, when i < size of words, update (increase i by 1), do −insertNode(head, words[i])" }, { "code": null, "e": 3751, "s": 3673, "text": "for initialize i := 0, when i < size of words, update (increase i by 1), do −" }, { "code": null, "e": 3778, "s": 3751, "text": "insertNode(head, words[i])" }, { "code": null, "e": 3805, "s": 3778, "text": "insertNode(head, words[i])" }, { "code": null, "e": 3818, "s": 3805, "text": "curr := head" }, { "code": null, "e": 3831, "s": 3818, "text": "curr := head" }, { "code": null, "e": 4224, "s": 3831, "text": "Define a function query(), this will take x,make one array of nodes tempif head.child[x - 'a'], then −insert head at the end of waitListret := falsefor initialize i := 0, when i < size of waitList, update (increase i by 1), do −curr := waitList[i]if curr.child[x - 'a'], thencurr := child[x - 'a'] of currinsert curr at the end of tempret := ret OR isEnd of currswap(temp, waitList)return ret" }, { "code": null, "e": 4269, "s": 4224, "text": "Define a function query(), this will take x," }, { "code": null, "e": 4298, "s": 4269, "text": "make one array of nodes temp" }, { "code": null, "e": 4327, "s": 4298, "text": "make one array of nodes temp" }, { "code": null, "e": 4392, "s": 4327, "text": "if head.child[x - 'a'], then −insert head at the end of waitList" }, { "code": null, "e": 4423, "s": 4392, "text": "if head.child[x - 'a'], then −" }, { "code": null, "e": 4458, "s": 4423, "text": "insert head at the end of waitList" }, { "code": null, "e": 4493, "s": 4458, "text": "insert head at the end of waitList" }, { "code": null, "e": 4506, "s": 4493, "text": "ret := false" }, { "code": null, "e": 4519, "s": 4506, "text": "ret := false" }, { "code": null, "e": 4734, "s": 4519, "text": "for initialize i := 0, when i < size of waitList, update (increase i by 1), do −curr := waitList[i]if curr.child[x - 'a'], thencurr := child[x - 'a'] of currinsert curr at the end of tempret := ret OR isEnd of curr" }, { "code": null, "e": 4815, "s": 4734, "text": "for initialize i := 0, when i < size of waitList, update (increase i by 1), do −" }, { "code": null, "e": 4835, "s": 4815, "text": "curr := waitList[i]" }, { "code": null, "e": 4855, "s": 4835, "text": "curr := waitList[i]" }, { "code": null, "e": 4971, "s": 4855, "text": "if curr.child[x - 'a'], thencurr := child[x - 'a'] of currinsert curr at the end of tempret := ret OR isEnd of curr" }, { "code": null, "e": 5000, "s": 4971, "text": "if curr.child[x - 'a'], then" }, { "code": null, "e": 5031, "s": 5000, "text": "curr := child[x - 'a'] of curr" }, { "code": null, "e": 5062, "s": 5031, "text": "curr := child[x - 'a'] of curr" }, { "code": null, "e": 5093, "s": 5062, "text": "insert curr at the end of temp" }, { "code": null, "e": 5124, "s": 5093, "text": "insert curr at the end of temp" }, { "code": null, "e": 5152, "s": 5124, "text": "ret := ret OR isEnd of curr" }, { "code": null, "e": 5180, "s": 5152, "text": "ret := ret OR isEnd of curr" }, { "code": null, "e": 5201, "s": 5180, "text": "swap(temp, waitList)" }, { "code": null, "e": 5222, "s": 5201, "text": "swap(temp, waitList)" }, { "code": null, "e": 5233, "s": 5222, "text": "return ret" }, { "code": null, "e": 5244, "s": 5233, "text": "return ret" }, { "code": null, "e": 5314, "s": 5244, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 7027, "s": 5314, "text": "#include <bits/stdc++.h>\nusing namespace std;\nstruct Node {\n Node* child[26];\n bool isEnd;\n Node(){\n isEnd = false;\n for (int i = 0; i < 26; i++)\n child[i] = NULL;\n }\n};\nclass StreamChecker {\n public:\n Node* head;\n vector<Node*> waitList;\n void insertNode(Node* head, string& s){\n Node* curr = head;\n for (int i = 0; i < s.size(); i++) {\n char x = s[i];\n if (!curr->child[x - 'a']) {\n curr->child[x - 'a'] = new Node();\n }\n curr = curr->child[x - 'a'];\n }\n curr->isEnd = true;\n }\n StreamChecker(vector<string>& words){\n head = new Node();\n for (int i = 0; i < words.size(); i++) {\n insertNode(head, words[i]);\n }\n Node* curr = head;\n }\n bool query(char x){\n vector<Node*> temp;\n if (head->child[x - 'a']) {\n waitList.push_back(head);\n }\n bool ret = false;\n for (int i = 0; i < waitList.size(); i++) {\n Node* curr = waitList[i];\n if (curr->child[x - 'a']) {\n curr = curr->child[x - 'a'];\n temp.push_back(curr);\n ret |= curr->isEnd;\n }\n }\n swap(temp, waitList);\n return ret;\n }\n};\nmain(){\n vector<string> v = {\"ce\",\"g\",\"lm\"};\n StreamChecker ob(v);\n cout << (ob.query('a')) << endl;\n cout << (ob.query('b')) << endl;\n cout << (ob.query('c')) << endl;\n cout << (ob.query('e')) << endl;\n cout << (ob.query('f')) << endl;\n cout << (ob.query('g')) << endl;\n cout << (ob.query('h')) << endl;\n cout << (ob.query('i')) << endl;\n cout << (ob.query('j')) << endl;\n cout << (ob.query('k')) << endl;\n cout << (ob.query('l')) << endl;\n cout << (ob.query('m'));\n}" }, { "code": null, "e": 7051, "s": 7027, "text": "\"ce\",\"g\",\"lm\", query()," }, { "code": null, "e": 7075, "s": 7051, "text": "0 0 0 1 0 1 0 0 0 0 0 1" } ]
Java Regular expression to check if a string contains alphabet
Following is the regular expression to match alphabet in the given input − "^[a-zA-Z]*$" Where, ^ matches the starting of the sentence. [a-zA-z] matches the lower case and upper case letters. * indicates the occurrence for zero or more times. & indicates the end of the line. import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ContainsAlphabetExample { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String names[] = new String[5]; for(int i=0; i<names.length;i++){ System.out.println("Enter your name: "); names[i] = sc.nextLine(); } //Regular expression to accept English alphabet String regex = "^[a-zA-Z]*$"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); for (String name : names) { //Creating a Matcher object Matcher matcher = pattern.matcher(name); if(matcher.matches()) { System.out.println(name+" is a valid name"); } else { System.out.println(name+" is not a valid name"); } } } } Enter your name: krishna Enter your name: kasyap Enter your name: maruthi# Enter your name: Sai_Ram Enter your name: Vani.Viswanath krishna is a valid name kasyap is a valid name maruthi# is not a valid name Sai_Ram is not a valid name Vani.Viswanath is not a valid name import java.util.Scanner; public class Just { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter your name: "); String name = sc.nextLine(); String regex = "^[a-zA-Z]*$"; boolean result = name.matches(regex); if(result) { System.out.println("Given name is valid"); } else { System.out.println("Given name is not valid"); } } } Enter your name: vasu#dev Given name is not valid
[ { "code": null, "e": 1137, "s": 1062, "text": "Following is the regular expression to match alphabet in the given input −" }, { "code": null, "e": 1151, "s": 1137, "text": "\"^[a-zA-Z]*$\"" }, { "code": null, "e": 1158, "s": 1151, "text": "Where," }, { "code": null, "e": 1198, "s": 1158, "text": "^ matches the starting of the sentence." }, { "code": null, "e": 1254, "s": 1198, "text": "[a-zA-z] matches the lower case and upper case letters." }, { "code": null, "e": 1305, "s": 1254, "text": "* indicates the occurrence for zero or more times." }, { "code": null, "e": 1338, "s": 1305, "text": "& indicates the end of the line." }, { "code": null, "e": 2213, "s": 1338, "text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class ContainsAlphabetExample {\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n String names[] = new String[5];\n for(int i=0; i<names.length;i++){\n System.out.println(\"Enter your name: \");\n names[i] = sc.nextLine();\n }\n //Regular expression to accept English alphabet\n String regex = \"^[a-zA-Z]*$\";\n //Creating a pattern object\n Pattern pattern = Pattern.compile(regex);\n for (String name : names) {\n //Creating a Matcher object\n Matcher matcher = pattern.matcher(name);\n if(matcher.matches()) {\n System.out.println(name+\" is a valid name\");\n } else {\n System.out.println(name+\" is not a valid name\");\n }\n }\n }\n}" }, { "code": null, "e": 2484, "s": 2213, "text": "Enter your name:\nkrishna\nEnter your name:\nkasyap\nEnter your name:\nmaruthi#\nEnter your name:\nSai_Ram\nEnter your name:\nVani.Viswanath\nkrishna is a valid name\nkasyap is a valid name\nmaruthi# is not a valid name\nSai_Ram is not a valid name\nVani.Viswanath is not a valid name" }, { "code": null, "e": 2936, "s": 2484, "text": "import java.util.Scanner;\npublic class Just {\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter your name: \");\n String name = sc.nextLine();\n String regex = \"^[a-zA-Z]*$\";\n boolean result = name.matches(regex);\n if(result) {\n System.out.println(\"Given name is valid\");\n } else {\n System.out.println(\"Given name is not valid\");\n }\n }\n}" }, { "code": null, "e": 2986, "s": 2936, "text": "Enter your name:\nvasu#dev\nGiven name is not valid" } ]
MongoDB query to add multiple documents
To perform multiple write operations, use bulkWrite(). Let us create an array list values. Following is the query − > const arrayList = [ ... {"Value1":100, "Value2":200, "Name": "John"}, ... {"Value1":100, "Value2":200, "Name": "Bob"} ... ]; > let op1 = []; > arrayList.forEach(({ Value1, Value2, Name }) => { ... op1.push({ ... "updateOne": { ... "filter": { Name}, ... "update": { "$set": { Value1, Value2, Name } }, ... "upsert": true ... } ... }) ... }); > db.demo397.bulkWrite(op1); { "acknowledged" : true, "deletedCount" : 0, "insertedCount" : 0, "matchedCount" : 0, "upsertedCount" : 2, "insertedIds" : { }, "upsertedIds" : { "0" : ObjectId("5e5e8c07f995e1718151981c"), "1" : ObjectId("5e5e8c07f995e1718151981d") } } Display all documents from a collection with the help of find() method − > db.demo397.find(); This will produce the following output − { "_id" : ObjectId("5e5e8c07f995e1718151981c"), "Name" : "John", "Value1" : 100, "Value2" : 200 } { "_id" : ObjectId("5e5e8c07f995e1718151981d"), "Name" : "Bob", "Value1" : 100, "Value2" : 200 }
[ { "code": null, "e": 1178, "s": 1062, "text": "To perform multiple write operations, use bulkWrite(). Let us create an array list values. Following is the query −" }, { "code": null, "e": 1878, "s": 1178, "text": "> const arrayList = [\n... {\"Value1\":100, \"Value2\":200, \"Name\": \"John\"},\n... {\"Value1\":100, \"Value2\":200, \"Name\": \"Bob\"}\n... ];\n> let op1 = [];\n> arrayList.forEach(({ Value1, Value2, Name }) => {\n... op1.push({\n... \"updateOne\": {\n... \"filter\": { Name},\n... \"update\": { \"$set\": { Value1, Value2, Name } },\n... \"upsert\": true\n... }\n... })\n... });\n> db.demo397.bulkWrite(op1);\n{\n \"acknowledged\" : true,\n \"deletedCount\" : 0,\n \"insertedCount\" : 0,\n \"matchedCount\" : 0,\n \"upsertedCount\" : 2,\n \"insertedIds\" : {\n },\n \"upsertedIds\" : {\n \"0\" : ObjectId(\"5e5e8c07f995e1718151981c\"),\n \"1\" : ObjectId(\"5e5e8c07f995e1718151981d\")\n }\n}" }, { "code": null, "e": 1951, "s": 1878, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1972, "s": 1951, "text": "> db.demo397.find();" }, { "code": null, "e": 2013, "s": 1972, "text": "This will produce the following output −" }, { "code": null, "e": 2208, "s": 2013, "text": "{ \"_id\" : ObjectId(\"5e5e8c07f995e1718151981c\"), \"Name\" : \"John\", \"Value1\" : 100, \"Value2\" : 200 }\n{ \"_id\" : ObjectId(\"5e5e8c07f995e1718151981d\"), \"Name\" : \"Bob\", \"Value1\" : 100, \"Value2\" : 200 }" } ]
5 Ultimate Python Libraries for Image Processing | by Pranjal Saxena | Towards Data Science
Image processing is the phenomenon of manipulating an image to extract features from it. In today’s world of computer vision and deep learning, different algorithms for image processing are heavily used to carry out edge detection, recognition, classification from a dataset of images. Sometimes these algorithms are also applied to videos frame by frame to extract features from them. In today’s article, we will take a look at the 5 best Python libraries that might help you to carry out manipulation of images like cropping, grayscaling etc. OpenCV is one of the most popular and widely used libraries for image processing and computer vision. This oral library can be used with many programming languages like C, C++, Python, Java but the library of Python bindings is the most popular one. Not only image manipulation but complex deep learning algorithms related to computer vision can also be implemented using this library easily. The best thing about open CV is that it is cross-platform and it can work with mobile devices also. Installation pip install opencv-python To do a Gaussian blur on an image. We will be using Colab as there we don’t need to set thing environment — everything is pre-setup here. First of all, let’s import the necessary packages. Colab doesn’t support cv2.imshow() — but, we have an alternative for that. import cv2import numpy as npimport urllibimport urllib.request as urfrom google.colab.patches import cv2_imshow Now, let’s load an image from the internet and apply some filters. SimpleCV is a python framework that uses computer vision libraries like OpenCV. This library is quite simple and easy to use and can be really helpful for quick prototyping. This library can particularly be useful for those who don’t have a knowledge of different image manipulation concepts like eigenvalues, colour spaces, and bit depth. Installation pip install SimpleCV This library can be a better choice to play with object detection tasks. You can find some amazing tasks like — detecting if a car is parked or not, using this library. You can learn more about this library here. Pillow is an image processing library for Python derived from the PIL or the Python Imaging Library. Although it is not as powerful and fast as openCV it can be used for simple image manipulation works like cropping, resizing, rotating and greyscaling the image. Another benefit is that it can be used without NumPy and Matplotlib. Installation pip install pillow To read an image in PIL we can use: from PIL import Imageim = Image.open(r"C:\Users\System-Pc\Desktop\image1.jpg")im.show() You can learn more about this library here. Mahotas is a Python library for image processing and computer vision that was originally designed for bioimage Informatics. But other computer vision tasks can be performed using it as well. It is originally written in C++ which makes it pretty fast and it has no dependencies other than NumPy. Installation pip install mahotas Grayscaling an image using mahotas: Finally, after running the code — we can get the following result. Pgmagick is a Python wrapper for GraphicsMagick which is the collection of tools and libraries for the manipulation of images. It supports more than 88 formats of image. Other than image processing work it can also be used in web applications for creating new images. Installation pip install pgmagick For extracting the edge from a picture: from pgmagick.api import Imageimg = Image(‘lena.jpg’) #Your image path will come hereimg.edge(2)img.write(‘lena_edge.jpg’) Although OpenCV is the major image processing library that we are going to use in the future, having a little bit of knowledge about the other image processing libraries will definitely be a good idea. All these libraries can make your workflow easier with their simpler implementation for specific functions. To know more about these libraries you can always follow the official documentation and also consult with the open-source community that these libraries have. Before you go... If you liked this article and want to stay tuned with more exciting articles on Python & Data Science — do consider becoming a medium member by clicking here https://pranjalai.medium.com/membership. Please do consider signing up using my referral link. In this way, the portion of the membership fee goes to me, which motivates me to write more exciting stuff on Python and Data Science. Also, feel free to subscribe to my free newsletter: Pranjal’s Newsletter.
[ { "code": null, "e": 261, "s": 172, "text": "Image processing is the phenomenon of manipulating an image to extract features from it." }, { "code": null, "e": 458, "s": 261, "text": "In today’s world of computer vision and deep learning, different algorithms for image processing are heavily used to carry out edge detection, recognition, classification from a dataset of images." }, { "code": null, "e": 558, "s": 458, "text": "Sometimes these algorithms are also applied to videos frame by frame to extract features from them." }, { "code": null, "e": 717, "s": 558, "text": "In today’s article, we will take a look at the 5 best Python libraries that might help you to carry out manipulation of images like cropping, grayscaling etc." }, { "code": null, "e": 967, "s": 717, "text": "OpenCV is one of the most popular and widely used libraries for image processing and computer vision. This oral library can be used with many programming languages like C, C++, Python, Java but the library of Python bindings is the most popular one." }, { "code": null, "e": 1210, "s": 967, "text": "Not only image manipulation but complex deep learning algorithms related to computer vision can also be implemented using this library easily. The best thing about open CV is that it is cross-platform and it can work with mobile devices also." }, { "code": null, "e": 1223, "s": 1210, "text": "Installation" }, { "code": null, "e": 1249, "s": 1223, "text": "pip install opencv-python" }, { "code": null, "e": 1387, "s": 1249, "text": "To do a Gaussian blur on an image. We will be using Colab as there we don’t need to set thing environment — everything is pre-setup here." }, { "code": null, "e": 1513, "s": 1387, "text": "First of all, let’s import the necessary packages. Colab doesn’t support cv2.imshow() — but, we have an alternative for that." }, { "code": null, "e": 1625, "s": 1513, "text": "import cv2import numpy as npimport urllibimport urllib.request as urfrom google.colab.patches import cv2_imshow" }, { "code": null, "e": 1692, "s": 1625, "text": "Now, let’s load an image from the internet and apply some filters." }, { "code": null, "e": 1866, "s": 1692, "text": "SimpleCV is a python framework that uses computer vision libraries like OpenCV. This library is quite simple and easy to use and can be really helpful for quick prototyping." }, { "code": null, "e": 2032, "s": 1866, "text": "This library can particularly be useful for those who don’t have a knowledge of different image manipulation concepts like eigenvalues, colour spaces, and bit depth." }, { "code": null, "e": 2045, "s": 2032, "text": "Installation" }, { "code": null, "e": 2066, "s": 2045, "text": "pip install SimpleCV" }, { "code": null, "e": 2235, "s": 2066, "text": "This library can be a better choice to play with object detection tasks. You can find some amazing tasks like — detecting if a car is parked or not, using this library." }, { "code": null, "e": 2279, "s": 2235, "text": "You can learn more about this library here." }, { "code": null, "e": 2611, "s": 2279, "text": "Pillow is an image processing library for Python derived from the PIL or the Python Imaging Library. Although it is not as powerful and fast as openCV it can be used for simple image manipulation works like cropping, resizing, rotating and greyscaling the image. Another benefit is that it can be used without NumPy and Matplotlib." }, { "code": null, "e": 2624, "s": 2611, "text": "Installation" }, { "code": null, "e": 2643, "s": 2624, "text": "pip install pillow" }, { "code": null, "e": 2679, "s": 2643, "text": "To read an image in PIL we can use:" }, { "code": null, "e": 2767, "s": 2679, "text": "from PIL import Imageim = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\image1.jpg\")im.show()" }, { "code": null, "e": 2811, "s": 2767, "text": "You can learn more about this library here." }, { "code": null, "e": 3106, "s": 2811, "text": "Mahotas is a Python library for image processing and computer vision that was originally designed for bioimage Informatics. But other computer vision tasks can be performed using it as well. It is originally written in C++ which makes it pretty fast and it has no dependencies other than NumPy." }, { "code": null, "e": 3119, "s": 3106, "text": "Installation" }, { "code": null, "e": 3139, "s": 3119, "text": "pip install mahotas" }, { "code": null, "e": 3175, "s": 3139, "text": "Grayscaling an image using mahotas:" }, { "code": null, "e": 3242, "s": 3175, "text": "Finally, after running the code — we can get the following result." }, { "code": null, "e": 3510, "s": 3242, "text": "Pgmagick is a Python wrapper for GraphicsMagick which is the collection of tools and libraries for the manipulation of images. It supports more than 88 formats of image. Other than image processing work it can also be used in web applications for creating new images." }, { "code": null, "e": 3523, "s": 3510, "text": "Installation" }, { "code": null, "e": 3544, "s": 3523, "text": "pip install pgmagick" }, { "code": null, "e": 3584, "s": 3544, "text": "For extracting the edge from a picture:" }, { "code": null, "e": 3707, "s": 3584, "text": "from pgmagick.api import Imageimg = Image(‘lena.jpg’) #Your image path will come hereimg.edge(2)img.write(‘lena_edge.jpg’)" }, { "code": null, "e": 3909, "s": 3707, "text": "Although OpenCV is the major image processing library that we are going to use in the future, having a little bit of knowledge about the other image processing libraries will definitely be a good idea." }, { "code": null, "e": 4017, "s": 3909, "text": "All these libraries can make your workflow easier with their simpler implementation for specific functions." }, { "code": null, "e": 4176, "s": 4017, "text": "To know more about these libraries you can always follow the official documentation and also consult with the open-source community that these libraries have." }, { "code": null, "e": 4193, "s": 4176, "text": "Before you go..." }, { "code": null, "e": 4392, "s": 4193, "text": "If you liked this article and want to stay tuned with more exciting articles on Python & Data Science — do consider becoming a medium member by clicking here https://pranjalai.medium.com/membership." }, { "code": null, "e": 4581, "s": 4392, "text": "Please do consider signing up using my referral link. In this way, the portion of the membership fee goes to me, which motivates me to write more exciting stuff on Python and Data Science." } ]
Linear Regression Model with Python | by Idil Ismiguzel | Towards Data Science
Regression models are widely used machine learning tools allowing us to make predictions from data by learning the relationship between features and continuous-valued outcomes. Checking model assumptions and understanding whether they are satisfied or not is as important as checking the accuracy and goodness of the model. In this article you will learn: How to build a linear regression modelHow to assess the model by prediction accuracy and R-squaredHow to check model diagnostics by testing linearity, normality, homoscedasticity, autocorrelation, and multicollinearityHow to detect outliers with Cook’s distanceHow to find the influence of each observation by studentized residuals and H leverage. How to build a linear regression model How to assess the model by prediction accuracy and R-squared How to check model diagnostics by testing linearity, normality, homoscedasticity, autocorrelation, and multicollinearity How to detect outliers with Cook’s distance How to find the influence of each observation by studentized residuals and H leverage. While following the article, I encourage you to check out the Jupyter Notebook on my GitHub for the full analysis and code. github.com Regression analysis is used to model the relationship between a single dependent variable Y (aka response, target, or outcome) and one or more independent variables X (aka predictor or feature). When we have one predictor it is “simple” linear regression and when we have more than one predictors it is “multiple” linear regression. In general, data does not fall exactly on a linear line, so the regression equation should include an error term(ε). The fitted (predicted) values typically denoted by Y-hat, and β-hat coefficients are chosen by the model as they minimize the squared distance (aka residuals) between the actual Y value and the best fit (Y-hat) minimizing the following expression: The method of minimizing the sum of the squared residuals is called Ordinary Least Squares (OLS) regression. We will be building the multiple linear regression model on the Boston housing dataset from the late 1970s. Data consists of a total of 506 cases with 14 attributes. Let’s have a look at it! names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']data = pd.read_csv("./housing.csv", delim_whitespace=True, names=names)data.head() We will be predicting house prices (“MEDV”) by using all the other variables. predictors = ["CRIM", "ZN", "INDUS", "CHAS", "NOX", "RM", "AGE", "DIS", "RAD", "TAX", "PTRATIO", "B", "LSTAT"]outcome = "MEDV"-> Create X and y datasetsX = data[predictors]y = data["MEDV"] We will use the Statsmodels library for linear regression. (Scikit-learn can also be used as an alternative but here I preferred statsmodels to reach a more detailed analysis of the regression model). Having said that, we will still be using Scikit-learn for train-test split. Details below! -> Because we are using statsmodels, we need to add the constant term to the X value.import statsmodels.api as smX = sm.add_constant(X) We will split our dataset into train and test sets (80% for training, and 20% for testing). The regression model will learn from training data where the output is known, and later we will generalize the model on the test set. We will predict the test set’s y values output and comparing these predictions with the actual values. This is done to detect overfitting or underfitting problems. -> Train-test splitfrom sklearn.model_selection import train_test_splittrain_X, test_X, train_y, test_y = train_test_split(X, y, train_size = 0.8, random_state = 42)-> Linear regression model model = sm.OLS(train_y, train_X)model = model.fit()print(model.summary2()) No. Observations is 404 (80% of the overall dataset) R-squared (goodness of the model from 0 to 1) is 0.75 p-value >0.05 for some predictors: “ZN”, “INDUS”, “AGE”, “TAX” meaning that we would consider removing these variables from the predictors list! It is because p-values determine whether the relationships that we observe in this sample also exist in the larger population. We will use model.predict on the test_X and compare the predictions with the actual test_y values. predictions = model.predict(test_X)df_results = pd.DataFrame({‘Actual’: test_y, ‘Predicted’: predictions}) One of the most important metrics is root mean squared error; the square root of the average squared error in the predicted y values (y-hat). It measures the overall accuracy of the model. Another important metric is R-squared ranging from 0 to 1; measures the proportion of variation in the data that is accounted in the regression model. It tells how well the model fits the data and R-squared=1 indicates that the regression predictions perfectly fit the data. Let’s find RMSE and R-squared for the predictions. from sklearn.metrics import r2_score, mean_squared_errorRMSE = np.sqrt(mean_squared_error(test_y, predictions))r2 = r2_score(test_y, predictions)print(RMSE, r2) RMSE=4.92 R-squared = 0.66 As we see our model performance dropped from 0.75 (on training data) to 0.66 (on test data), and we are expecting to be 4.92 far off on our next predictions using this model. Before we built a linear regression model, we make the following assumptions: Linearity: The relationship between X and the mean of Y is linear.Normality: The residuals follow a normal distribution and the expected mean of the residuals is zero.Homoscedasticity: The variance of residual is constant for all values of X.No autocorrelation: Residuals are independent of each other.No multicollinearity: There is no high correlation between predictor variables. Linearity: The relationship between X and the mean of Y is linear. Normality: The residuals follow a normal distribution and the expected mean of the residuals is zero. Homoscedasticity: The variance of residual is constant for all values of X. No autocorrelation: Residuals are independent of each other. No multicollinearity: There is no high correlation between predictor variables. Before being confused about the model performance, it is crucial to check whether the assumptions are strongly satisfied or not. It could be difficult to fulfill all the assumptions perfectly with the real-world data, however, it is crucial to understand how far our model being interpreted correctly. We assumed that there is a linear relationship between the predictors and the outcome, but this may not be correct. When we do modeling, we are trying to fit our data to a function that explains our data, but linear regression might not be the fitting estimator in this case. We will test linearity with a scatter plot to see predicted values versus the actual values. Ideally, the data points should lie around the diagonal line on the plot. -> Plot the actual vs predicted resultssns.lmplot(x='Actual', y='Predicted', data=df_results, fit_reg=False)-> Plot the diagonal lined_line= np.arange(df_results.min().min(), df_results.max().max())plt.plot(d_line, d_line, color='red', linestyle='--')plt.show() In the Boston dataset, we can see that there is not a perfect relationship. On the lower and higher-end values, our predictions are biased. We assumed that the error terms (residuals) of the model are normally distributed. This assumption might be violated due to the linearity assumption not been hold or due to outliers in the dataset. We will test normality by checking with the quantile-quantile plot, Q-Q plot. from statsmodels.graphics.gofplots import qqplotfig=qqplot(model.resid_pearson,line=’45',fit=’True’)plt.xlabel(“Theoretical quantiles”)plt.ylabel(“Sample quantiles”)plt.show() The ideal match on the left shows data distribution follows the red line from the bottom left to the top right. In Boston dataset, we can see that our model biasing towards under-estimating. You can go further and plot a histogram of residuals or perform normality tests such as Anderson-Darling or Shapiro-Wilk Test. We assumed that the variance of error terms (residuals) is constant for all values of X. However, heteroscedasticity, the violation of homoscedasticity happens when we do not have the same variance across the error terms. This violation can happen when the model gives different weights to the subsets of the data. We will test homoscedasticity by plotting the residuals and checking if the variance is uniform. fig, ax = plt.subplots(figsize=(5, 5))sns.regplot(model.fittedvalues,model.resid, scatter_kws={'alpha': 0.25}, line_kws={'color': 'C2', 'lw': 2}, ax=ax)ax.set_xlabel('predicted')ax.set_ylabel('residuals')plt.tight_layout()plt.show() The ideal plot on the left shows a uniform distribution of the residuals however, we can’t say the same for Boston Dataset. We need to be careful about heteroscedasticity, which indicates that the prediction errors are different for a different range of predicted values meaning that our model could be incomplete. Autocorrelation occurs when the residuals are not independent of each other, in other words, when the value of y_t is not independent of y_t-1. This is generally the case for time series data such as stock prices. To learn more on this you can check my article about time series forecasting. towardsdatascience.com We will perform the Durbin-Watson test to determine if the no autocorrelation assumption holds. from statsmodels.stats.stattools import durbin_watsondurbinWatson = durbin_watson(model.resid)print(durbinWatson) >>>Durbin-Watson =2.11 The Durbin-Watson statistic ranges between 0 and 4. A value of 2.0 means that there is no autocorrelation. Values between 0 and 2 indicate positive and values between 2 and 4 indicate negative autocorrelation. In our case, Durbin-Watson statistic is very close to 2.0 therefore we can say that no autocorrelation assumption is not violated. We assumed that the predictor variables in the regression are not correlated with each other. Having this assumption violated does not make our model unusable but it is still important to understand and get rid of some unnecessary predictors if they are highly correlated with others. We will plot a heatmap to see the correlation between predictors visually and we will also calculate the variance inflation factor (VIF), which measures the multicollinearity among the independent variables. mask = np.zeros_like(train_X.drop("const", axis=1).corr())mask[np.triu_indices_from(mask)] = Truesns.heatmap(train_X.drop("const", axis=1).corr().round(2), annot=True, mask=mask, cmap="cividis") As we can see between some variables we have a high (negative/positive) correlation in Boston Dataset. And we calculate VIF: from statsmodels.stats.outliers_influence import variance_inflation_factor as viffor i in range(len(X.columns)): v=vif(np.matrix(X),i) print("Variance inflation factor for {}: {}".format(X.columns[i],round(v,2))) Variance inflation factor for CRIM: 1.79Variance inflation factor for ZN: 2.3Variance inflation factor for INDUS: 3.99Variance inflation factor for CHAS: 1.07Variance inflation factor for NOX: 4.39Variance inflation factor for RM: 1.93Variance inflation factor for AGE: 3.1Variance inflation factor for DIS: 3.96Variance inflation factor for RAD: 7.48Variance inflation factor for TAX: 9.01Variance inflation factor for PTRATIO: 1.8Variance inflation factor for B: 1.35Variance inflation factor for LSTAT: 2.94 A VIF of 1 indicates two variables are not correlated, a VIF between 1 and 5 indicates a moderate correlation, and a VIF above 5 indicates a high correlation. As result shows we have 2 high correlated and 5 moderately correlated variables. It is better if we get rid of some of them. Outlier detection using Cook’s distance plot Cook’s distance determines the effect of deletion of a given observation from the dataset. We can leverage Cook’s distance while examining if an observation is a potential outlier or an influential variable. Here is how to plot Cook’s distance. from statsmodels.stats.outliers_influence import OLSInfluence as influenceinf=influence(model)(i, d) = inf.cooks_distanceplt.title("Cook's distance plot")plt.stem(np.arange(len(i)), i, markerfmt=",")plt.show() From Cook’s plot, we can understand which are the observations we need to pay more attention to and decide whether to drop them or not. (As a rule, the observation has a high influence if the Cook’s distance is greater than 4/N-k-1 ( N=number of observations, k= number of predictors, yellow horizontal line in the plot) Influence plots show the studentized residuals versus the leverage of each observation as measured by the hat matrix. from statsmodels.stats.outliers_influence import OLSInfluence influence = OLSInfluence(model)fig, ax = plt.subplots()ax.axhline(-2.5, linestyle='-', color='C1')ax.axhline(2.5, linestyle='-', color='C1')ax.scatter(influence.hat_matrix_diag, influence.resid_studentized_internal, s=1000 * np.sqrt(influence.cooks_distance[0]), alpha=0.5)ax.set_xlabel(‘H Leverage’)ax.set_ylabel(‘Studentized Residuals’)ax.set_title(“BOSTON DATASET \nInfluence Plot”)plt.tight_layout()plt.show() In contrast to the ideal plot, in Boston Dataset we can see that some data points have low leverage but large residuals. These highly influential data points need a delicate evaluation before including in the model. In this analysis, we found out that some of the assumptions we made before building a linear regression model have been violated and caused significant problems in the model performance and outcome predictions. Even though meeting with the assumptions with real-world data sounds a bit superficial, we still need to check and know the flaws of our model and if a possible fix or improve them, before making important decisions based on the outputs. If you have outcomes like here we have with the Boston dataset, I would suggest you to try modeling with Random Forest Regressor or XGBoost to understand if you can improve model performance. You can enrich with principal component analysis-PCA for feature extraction to drop the least important predictors while still keeping the most valuable parts of all the variables. Moreover, you can also perform K-fold Cross Validation(CV) by dividing entire dataset into k folds and being sure that each fold is used as a testing set. I hope you enjoyed reading the article and find it useful for your analyses! If you liked this article, you can read my other articles here and follow me on Medium. Let me know if you have any questions or suggestions.✨ Enjoy this article? Become a member for more!
[ { "code": null, "e": 496, "s": 172, "text": "Regression models are widely used machine learning tools allowing us to make predictions from data by learning the relationship between features and continuous-valued outcomes. Checking model assumptions and understanding whether they are satisfied or not is as important as checking the accuracy and goodness of the model." }, { "code": null, "e": 528, "s": 496, "text": "In this article you will learn:" }, { "code": null, "e": 876, "s": 528, "text": "How to build a linear regression modelHow to assess the model by prediction accuracy and R-squaredHow to check model diagnostics by testing linearity, normality, homoscedasticity, autocorrelation, and multicollinearityHow to detect outliers with Cook’s distanceHow to find the influence of each observation by studentized residuals and H leverage." }, { "code": null, "e": 915, "s": 876, "text": "How to build a linear regression model" }, { "code": null, "e": 976, "s": 915, "text": "How to assess the model by prediction accuracy and R-squared" }, { "code": null, "e": 1097, "s": 976, "text": "How to check model diagnostics by testing linearity, normality, homoscedasticity, autocorrelation, and multicollinearity" }, { "code": null, "e": 1141, "s": 1097, "text": "How to detect outliers with Cook’s distance" }, { "code": null, "e": 1228, "s": 1141, "text": "How to find the influence of each observation by studentized residuals and H leverage." }, { "code": null, "e": 1352, "s": 1228, "text": "While following the article, I encourage you to check out the Jupyter Notebook on my GitHub for the full analysis and code." }, { "code": null, "e": 1363, "s": 1352, "text": "github.com" }, { "code": null, "e": 1558, "s": 1363, "text": "Regression analysis is used to model the relationship between a single dependent variable Y (aka response, target, or outcome) and one or more independent variables X (aka predictor or feature)." }, { "code": null, "e": 1696, "s": 1558, "text": "When we have one predictor it is “simple” linear regression and when we have more than one predictors it is “multiple” linear regression." }, { "code": null, "e": 1813, "s": 1696, "text": "In general, data does not fall exactly on a linear line, so the regression equation should include an error term(ε)." }, { "code": null, "e": 2061, "s": 1813, "text": "The fitted (predicted) values typically denoted by Y-hat, and β-hat coefficients are chosen by the model as they minimize the squared distance (aka residuals) between the actual Y value and the best fit (Y-hat) minimizing the following expression:" }, { "code": null, "e": 2170, "s": 2061, "text": "The method of minimizing the sum of the squared residuals is called Ordinary Least Squares (OLS) regression." }, { "code": null, "e": 2361, "s": 2170, "text": "We will be building the multiple linear regression model on the Boston housing dataset from the late 1970s. Data consists of a total of 506 cases with 14 attributes. Let’s have a look at it!" }, { "code": null, "e": 2557, "s": 2361, "text": "names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']data = pd.read_csv(\"./housing.csv\", delim_whitespace=True, names=names)data.head()" }, { "code": null, "e": 2635, "s": 2557, "text": "We will be predicting house prices (“MEDV”) by using all the other variables." }, { "code": null, "e": 2824, "s": 2635, "text": "predictors = [\"CRIM\", \"ZN\", \"INDUS\", \"CHAS\", \"NOX\", \"RM\", \"AGE\", \"DIS\", \"RAD\", \"TAX\", \"PTRATIO\", \"B\", \"LSTAT\"]outcome = \"MEDV\"-> Create X and y datasetsX = data[predictors]y = data[\"MEDV\"]" }, { "code": null, "e": 3116, "s": 2824, "text": "We will use the Statsmodels library for linear regression. (Scikit-learn can also be used as an alternative but here I preferred statsmodels to reach a more detailed analysis of the regression model). Having said that, we will still be using Scikit-learn for train-test split. Details below!" }, { "code": null, "e": 3252, "s": 3116, "text": "-> Because we are using statsmodels, we need to add the constant term to the X value.import statsmodels.api as smX = sm.add_constant(X)" }, { "code": null, "e": 3642, "s": 3252, "text": "We will split our dataset into train and test sets (80% for training, and 20% for testing). The regression model will learn from training data where the output is known, and later we will generalize the model on the test set. We will predict the test set’s y values output and comparing these predictions with the actual values. This is done to detect overfitting or underfitting problems." }, { "code": null, "e": 3909, "s": 3642, "text": "-> Train-test splitfrom sklearn.model_selection import train_test_splittrain_X, test_X, train_y, test_y = train_test_split(X, y, train_size = 0.8, random_state = 42)-> Linear regression model model = sm.OLS(train_y, train_X)model = model.fit()print(model.summary2())" }, { "code": null, "e": 3962, "s": 3909, "text": "No. Observations is 404 (80% of the overall dataset)" }, { "code": null, "e": 4016, "s": 3962, "text": "R-squared (goodness of the model from 0 to 1) is 0.75" }, { "code": null, "e": 4288, "s": 4016, "text": "p-value >0.05 for some predictors: “ZN”, “INDUS”, “AGE”, “TAX” meaning that we would consider removing these variables from the predictors list! It is because p-values determine whether the relationships that we observe in this sample also exist in the larger population." }, { "code": null, "e": 4387, "s": 4288, "text": "We will use model.predict on the test_X and compare the predictions with the actual test_y values." }, { "code": null, "e": 4494, "s": 4387, "text": "predictions = model.predict(test_X)df_results = pd.DataFrame({‘Actual’: test_y, ‘Predicted’: predictions})" }, { "code": null, "e": 4683, "s": 4494, "text": "One of the most important metrics is root mean squared error; the square root of the average squared error in the predicted y values (y-hat). It measures the overall accuracy of the model." }, { "code": null, "e": 4958, "s": 4683, "text": "Another important metric is R-squared ranging from 0 to 1; measures the proportion of variation in the data that is accounted in the regression model. It tells how well the model fits the data and R-squared=1 indicates that the regression predictions perfectly fit the data." }, { "code": null, "e": 5009, "s": 4958, "text": "Let’s find RMSE and R-squared for the predictions." }, { "code": null, "e": 5170, "s": 5009, "text": "from sklearn.metrics import r2_score, mean_squared_errorRMSE = np.sqrt(mean_squared_error(test_y, predictions))r2 = r2_score(test_y, predictions)print(RMSE, r2)" }, { "code": null, "e": 5180, "s": 5170, "text": "RMSE=4.92" }, { "code": null, "e": 5197, "s": 5180, "text": "R-squared = 0.66" }, { "code": null, "e": 5372, "s": 5197, "text": "As we see our model performance dropped from 0.75 (on training data) to 0.66 (on test data), and we are expecting to be 4.92 far off on our next predictions using this model." }, { "code": null, "e": 5450, "s": 5372, "text": "Before we built a linear regression model, we make the following assumptions:" }, { "code": null, "e": 5832, "s": 5450, "text": "Linearity: The relationship between X and the mean of Y is linear.Normality: The residuals follow a normal distribution and the expected mean of the residuals is zero.Homoscedasticity: The variance of residual is constant for all values of X.No autocorrelation: Residuals are independent of each other.No multicollinearity: There is no high correlation between predictor variables." }, { "code": null, "e": 5899, "s": 5832, "text": "Linearity: The relationship between X and the mean of Y is linear." }, { "code": null, "e": 6001, "s": 5899, "text": "Normality: The residuals follow a normal distribution and the expected mean of the residuals is zero." }, { "code": null, "e": 6077, "s": 6001, "text": "Homoscedasticity: The variance of residual is constant for all values of X." }, { "code": null, "e": 6138, "s": 6077, "text": "No autocorrelation: Residuals are independent of each other." }, { "code": null, "e": 6218, "s": 6138, "text": "No multicollinearity: There is no high correlation between predictor variables." }, { "code": null, "e": 6520, "s": 6218, "text": "Before being confused about the model performance, it is crucial to check whether the assumptions are strongly satisfied or not. It could be difficult to fulfill all the assumptions perfectly with the real-world data, however, it is crucial to understand how far our model being interpreted correctly." }, { "code": null, "e": 6796, "s": 6520, "text": "We assumed that there is a linear relationship between the predictors and the outcome, but this may not be correct. When we do modeling, we are trying to fit our data to a function that explains our data, but linear regression might not be the fitting estimator in this case." }, { "code": null, "e": 6963, "s": 6796, "text": "We will test linearity with a scatter plot to see predicted values versus the actual values. Ideally, the data points should lie around the diagonal line on the plot." }, { "code": null, "e": 7225, "s": 6963, "text": "-> Plot the actual vs predicted resultssns.lmplot(x='Actual', y='Predicted', data=df_results, fit_reg=False)-> Plot the diagonal lined_line= np.arange(df_results.min().min(), df_results.max().max())plt.plot(d_line, d_line, color='red', linestyle='--')plt.show()" }, { "code": null, "e": 7365, "s": 7225, "text": "In the Boston dataset, we can see that there is not a perfect relationship. On the lower and higher-end values, our predictions are biased." }, { "code": null, "e": 7563, "s": 7365, "text": "We assumed that the error terms (residuals) of the model are normally distributed. This assumption might be violated due to the linearity assumption not been hold or due to outliers in the dataset." }, { "code": null, "e": 7641, "s": 7563, "text": "We will test normality by checking with the quantile-quantile plot, Q-Q plot." }, { "code": null, "e": 7817, "s": 7641, "text": "from statsmodels.graphics.gofplots import qqplotfig=qqplot(model.resid_pearson,line=’45',fit=’True’)plt.xlabel(“Theoretical quantiles”)plt.ylabel(“Sample quantiles”)plt.show()" }, { "code": null, "e": 8008, "s": 7817, "text": "The ideal match on the left shows data distribution follows the red line from the bottom left to the top right. In Boston dataset, we can see that our model biasing towards under-estimating." }, { "code": null, "e": 8135, "s": 8008, "text": "You can go further and plot a histogram of residuals or perform normality tests such as Anderson-Darling or Shapiro-Wilk Test." }, { "code": null, "e": 8357, "s": 8135, "text": "We assumed that the variance of error terms (residuals) is constant for all values of X. However, heteroscedasticity, the violation of homoscedasticity happens when we do not have the same variance across the error terms." }, { "code": null, "e": 8450, "s": 8357, "text": "This violation can happen when the model gives different weights to the subsets of the data." }, { "code": null, "e": 8547, "s": 8450, "text": "We will test homoscedasticity by plotting the residuals and checking if the variance is uniform." }, { "code": null, "e": 8780, "s": 8547, "text": "fig, ax = plt.subplots(figsize=(5, 5))sns.regplot(model.fittedvalues,model.resid, scatter_kws={'alpha': 0.25}, line_kws={'color': 'C2', 'lw': 2}, ax=ax)ax.set_xlabel('predicted')ax.set_ylabel('residuals')plt.tight_layout()plt.show()" }, { "code": null, "e": 9095, "s": 8780, "text": "The ideal plot on the left shows a uniform distribution of the residuals however, we can’t say the same for Boston Dataset. We need to be careful about heteroscedasticity, which indicates that the prediction errors are different for a different range of predicted values meaning that our model could be incomplete." }, { "code": null, "e": 9387, "s": 9095, "text": "Autocorrelation occurs when the residuals are not independent of each other, in other words, when the value of y_t is not independent of y_t-1. This is generally the case for time series data such as stock prices. To learn more on this you can check my article about time series forecasting." }, { "code": null, "e": 9410, "s": 9387, "text": "towardsdatascience.com" }, { "code": null, "e": 9506, "s": 9410, "text": "We will perform the Durbin-Watson test to determine if the no autocorrelation assumption holds." }, { "code": null, "e": 9620, "s": 9506, "text": "from statsmodels.stats.stattools import durbin_watsondurbinWatson = durbin_watson(model.resid)print(durbinWatson)" }, { "code": null, "e": 9643, "s": 9620, "text": ">>>Durbin-Watson =2.11" }, { "code": null, "e": 9984, "s": 9643, "text": "The Durbin-Watson statistic ranges between 0 and 4. A value of 2.0 means that there is no autocorrelation. Values between 0 and 2 indicate positive and values between 2 and 4 indicate negative autocorrelation. In our case, Durbin-Watson statistic is very close to 2.0 therefore we can say that no autocorrelation assumption is not violated." }, { "code": null, "e": 10269, "s": 9984, "text": "We assumed that the predictor variables in the regression are not correlated with each other. Having this assumption violated does not make our model unusable but it is still important to understand and get rid of some unnecessary predictors if they are highly correlated with others." }, { "code": null, "e": 10477, "s": 10269, "text": "We will plot a heatmap to see the correlation between predictors visually and we will also calculate the variance inflation factor (VIF), which measures the multicollinearity among the independent variables." }, { "code": null, "e": 10672, "s": 10477, "text": "mask = np.zeros_like(train_X.drop(\"const\", axis=1).corr())mask[np.triu_indices_from(mask)] = Truesns.heatmap(train_X.drop(\"const\", axis=1).corr().round(2), annot=True, mask=mask, cmap=\"cividis\")" }, { "code": null, "e": 10775, "s": 10672, "text": "As we can see between some variables we have a high (negative/positive) correlation in Boston Dataset." }, { "code": null, "e": 10797, "s": 10775, "text": "And we calculate VIF:" }, { "code": null, "e": 11016, "s": 10797, "text": "from statsmodels.stats.outliers_influence import variance_inflation_factor as viffor i in range(len(X.columns)): v=vif(np.matrix(X),i) print(\"Variance inflation factor for {}: {}\".format(X.columns[i],round(v,2)))" }, { "code": null, "e": 11527, "s": 11016, "text": "Variance inflation factor for CRIM: 1.79Variance inflation factor for ZN: 2.3Variance inflation factor for INDUS: 3.99Variance inflation factor for CHAS: 1.07Variance inflation factor for NOX: 4.39Variance inflation factor for RM: 1.93Variance inflation factor for AGE: 3.1Variance inflation factor for DIS: 3.96Variance inflation factor for RAD: 7.48Variance inflation factor for TAX: 9.01Variance inflation factor for PTRATIO: 1.8Variance inflation factor for B: 1.35Variance inflation factor for LSTAT: 2.94" }, { "code": null, "e": 11686, "s": 11527, "text": "A VIF of 1 indicates two variables are not correlated, a VIF between 1 and 5 indicates a moderate correlation, and a VIF above 5 indicates a high correlation." }, { "code": null, "e": 11811, "s": 11686, "text": "As result shows we have 2 high correlated and 5 moderately correlated variables. It is better if we get rid of some of them." }, { "code": null, "e": 11856, "s": 11811, "text": "Outlier detection using Cook’s distance plot" }, { "code": null, "e": 12101, "s": 11856, "text": "Cook’s distance determines the effect of deletion of a given observation from the dataset. We can leverage Cook’s distance while examining if an observation is a potential outlier or an influential variable. Here is how to plot Cook’s distance." }, { "code": null, "e": 12311, "s": 12101, "text": "from statsmodels.stats.outliers_influence import OLSInfluence as influenceinf=influence(model)(i, d) = inf.cooks_distanceplt.title(\"Cook's distance plot\")plt.stem(np.arange(len(i)), i, markerfmt=\",\")plt.show()" }, { "code": null, "e": 12632, "s": 12311, "text": "From Cook’s plot, we can understand which are the observations we need to pay more attention to and decide whether to drop them or not. (As a rule, the observation has a high influence if the Cook’s distance is greater than 4/N-k-1 ( N=number of observations, k= number of predictors, yellow horizontal line in the plot)" }, { "code": null, "e": 12750, "s": 12632, "text": "Influence plots show the studentized residuals versus the leverage of each observation as measured by the hat matrix." }, { "code": null, "e": 13227, "s": 12750, "text": "from statsmodels.stats.outliers_influence import OLSInfluence influence = OLSInfluence(model)fig, ax = plt.subplots()ax.axhline(-2.5, linestyle='-', color='C1')ax.axhline(2.5, linestyle='-', color='C1')ax.scatter(influence.hat_matrix_diag, influence.resid_studentized_internal, s=1000 * np.sqrt(influence.cooks_distance[0]), alpha=0.5)ax.set_xlabel(‘H Leverage’)ax.set_ylabel(‘Studentized Residuals’)ax.set_title(“BOSTON DATASET \\nInfluence Plot”)plt.tight_layout()plt.show()" }, { "code": null, "e": 13443, "s": 13227, "text": "In contrast to the ideal plot, in Boston Dataset we can see that some data points have low leverage but large residuals. These highly influential data points need a delicate evaluation before including in the model." }, { "code": null, "e": 13892, "s": 13443, "text": "In this analysis, we found out that some of the assumptions we made before building a linear regression model have been violated and caused significant problems in the model performance and outcome predictions. Even though meeting with the assumptions with real-world data sounds a bit superficial, we still need to check and know the flaws of our model and if a possible fix or improve them, before making important decisions based on the outputs." }, { "code": null, "e": 14420, "s": 13892, "text": "If you have outcomes like here we have with the Boston dataset, I would suggest you to try modeling with Random Forest Regressor or XGBoost to understand if you can improve model performance. You can enrich with principal component analysis-PCA for feature extraction to drop the least important predictors while still keeping the most valuable parts of all the variables. Moreover, you can also perform K-fold Cross Validation(CV) by dividing entire dataset into k folds and being sure that each fold is used as a testing set." }, { "code": null, "e": 14497, "s": 14420, "text": "I hope you enjoyed reading the article and find it useful for your analyses!" }, { "code": null, "e": 14640, "s": 14497, "text": "If you liked this article, you can read my other articles here and follow me on Medium. Let me know if you have any questions or suggestions.✨" } ]
Short Text Topic Modeling. Intuition and (some) maths to... | by Matyas Amrouche | Towards Data Science
Topic Modeling aims to find the topics (or clusters) inside a corpus of texts (like mails or news articles), without knowing those topics at first. Here lies the real power of Topic Modeling, you don’t need any labeled or annotated data, only raw texts, and from this chaos Topic Modeling algorithms will find the topics your texts are about! In this post we will describe the intuition and logic behind the most popular approach for Topic Modeling, the LDA, and see its limitation on short texts. Given this post is about Short Text Topic Modeling (STTM) we will not dive into the details of LDA. The reader willing to deepen his knowledge of LDA can find great articles and useful resources about LDA here and here. Then, in a second part, we will present a new approach for STTM and finally see in a third part how to easily apply it (fit/predict ✌️) on a toy dataset and evaluate its performance. The reader already familiar with LDA and Topic Modeling may want to skip the first part and directly go to the second and third ones which present a new approach for Short Text Topic Modeling and its Python coding 🐍. The most popular Topic Modeling algorithm is LDA, Latent Dirichlet Allocation. Let’s first unravel this imposing name to have an intuition of what it does. Latent because the topics are “hidden”. We have a bunch of texts and we want the algorithm to put them into clusters that will make sense to us. For example, if our text data come from news content, typically the clusters found might be about Mideast Politics, Computer, Space... but we don’t know it yet. Dirichlet stands for the Dirichlet distribution the model uses as a prior to generate document-topic and word-topic distributions. Allocation because we want to allocate topics to our texts. Figure 1 below describes how the LDA steps articulate to find the topics within a corpus of documents. “A document is generated by sampling a mixture of these topics and then sampling words from that mixture” (Andrew Ng, David Blei and Michael Jordan from the LDA original paper). NB: In the Figure 1 above, we have set K=3 topics and N=8 words in our vocabulary for illustration ease. We also named these topics Computer, Space and Mideast Politics for illustration ease (rather than calling them topic 1, topic 2 and topic 3). Indeed, it will be our task to understand that the 3 found topics are about Computer, Space and Mideast Politics regarding their content (we will see this part more in depth during the topic attribution of our STTM pipeline in part III). In short, LDA by using Dirichlet distributions as prior knowledge generates documents made of topics and then update them until they match the ground truth. Despite its great results on medium or large sized texts (>50 words), typically mails and news articles are about this size range, LDA poorly performs on short texts like Tweets, Reddit posts or StackOverflow titles’ questions. Looking at the short texts examples above on Figure 2, it is evident that the assumption that a text is a mixture of topics (remember first step in Figure 1) is not true anymore. We will now assume that a short text is made from only one topic. The Gibbs Sampling Dirichlet Mixture Model (GSDMM) is an “altered” LDA algorithm, showing great results on STTM tasks, that makes the initial assumption: 1 topic ↔️1 document. The words within a document are generated using the same unique topic, and not from a mixture of topics as it was in the original LDA. Before diving into code and practical aspects, let’s understand GSDMM with an equivalent procedure called the Movie Group Process that will help us understand the different steps and process under the hood of STTM, and how to tune efficiently its hyper-parameters (we remember alpha and beta from the LDA part). Imagine a bunch of students in a restaurant, seating randomly at K tables. They are all asked to write their favorite movies on a paper (but it must remain a short list). The objective is to cluster them in such a way that so students within the same group share the same movie interest. To do so, one after another, students must make a new table choice regarding the two following rules: Rule 1: Choose a table with more students. This rule improves completeness, all students sharing the same movie’s interest are assigned to the same table. Rule 2: Choose a table where students share similar movie’s interest. This rule aims to increase homogeneity, we want only members sharing the same movie’s interest at a table. After repeating this process, we expect some tables to disappear and others to grow larger and eventually have clusters of students matching their movie’s interest. This is simply what the GSDMM algorithm does! In this part we will build full STTM pipeline from a concrete example using the 20 News Groups dataset from Scikit-learn used for Topic Modeling on texts. First thing first, we need to download the STTM script from Github into our project folder. cd sttm_projectgit clone https://github.com/rwalk/gsdmm.git Now, we can start implementing the STTM pipeline (here is a static version of the notebook I used). # Useful libsfrom sklearn.datasets import fetch_20newsgroupsimport pickleimport pandas as pdimport numpy as np# STTM lib from Githubfrom gsdmm import MovieGroupProcess# Custom python scripts for preprocessing, prediction and# visualization that I will define more in depth laterfrom preprocessing import tokenizefrom topic_allocation import top_words, topic_attributionfrom visualisation import plot_topic_notebook# Load the 20NewsGroups dataset from sklearncats = ['talk.politics.mideast', 'comp.windows.x', 'sci.space']newsgroups_train = fetch_20newsgroups(subset=’train’, categories=cats) However, in this exercise, we will not use the whole content of the news to extrapolate a topic from it, but only consider the Subject and the first sentence of the news (see Figure 3 below). Indeed, we need short texts for short texts topic modeling... obviously 🙏 Besides, we will only look at only 3 topics (evenly distributed among the dataset), for illustration ease. These topics are the following: Mideast Politics 🌍 Space 👾 Windows X 🖥 # Preprocessing and tokenizationtokenized_data = tokenize(df, form_reduction='stemming', predict=False) Here are the preprocessing recipe I have followed for this task: Tokenization using spaCy tokenizer. Removing stop words and 1 character words. Stemming (given my empirical experience I have observed that stemming gives better clusters on short text compared to lemmatization) using the nltk library’s stemmer. Removing empty documents and documents with more than 30 tokens. Removing unique token (with a term frequency = 1). However, one must keep in mind that preprocessing is data dependent and should consider to adapt an other preprocessing approach if a different dataset is used. Now that our data are cleaned and processed to the proper input format, we are ready to train the model 🚀 # Train STTM model# Init of the Gibbs Sampling Dirichlet Mixture Model algorithm# K = number of potential topic (which we don't know a priori)# alpha = # beta = # n_iters = number of iterations to mgp = MovieGroupProcess(K=10, alpha=0.1, beta=0.1, n_iters=30)vocab = set(x for doc in docs for x in doc)n_terms = len(vocab)y = mgp.fit(docs, n_terms)# Save modelwith open(‘dumps/trained_models/v1.model’, “wb”) as f: pickle.dump(mgp, f) f.close() Let’s dive under the hood and understand the hyper-parameters machinery of the GSDMM model 🛠: K = 10. In a real case we are not aware of the exact number of topic so we want to choose a higher value. Theoretically, GSDMM should empty useless clusters and eventually find the exact number of cluster. It will not be the case here, but nothing to worry, we will explain the situation more in depth later. alpha = 0.1 and beta = 0.1. Here we kept the default parameters (which work well for several datasets). However, one might want to tune them to improve its topic allocation regarding the completeness and homogeneity of the clusters. Don’t hesitate to refer to the original paper 📖 to understand the balance between these two parameters. n_iters = 30. According to the original paper, GSDMM converges quite fast (about 5 iterations) on several datasets and remain very stable. Hence, 30 iterations is a good default value for any kind of dataset. Once the model is trained, we want to explore the topics found and check if they are coherent regarding their content 🔎 Given that our model has gathered the documents into 10 topics, we must give them a name that will make sense regarding their content. So let’s dive into the topics found by our model. doc_count = np.array(mgp.cluster_doc_count)print('Number of documents per topic :', doc_count)print('*'*20)# Topics sorted by the number of document they are allocated totop_index = doc_count.argsort()[-10:][::-1]print('Most important clusters (by number of docs inside):', top_index)print('*'*20)# Show the top 5 words in term frequency for each cluster top_words(mgp.cluster_word_distribution, top_index, 5) The code above display the following statistics that give us insight about what our clusters are made of. Ideally, the GSDMM algorithm should find the correct number of topics, here 3, not 10. Three explanations come to my mind: Find other hyper-parameters to empty smaller cluster (refer to original paper for a deeper understanding of alpha and beta parameters). We have both small dataset and vocabulary (about 1700 documents and 2100 words), which may be difficult for the model to extrapolate and distinguish significant difference between topics. As usual, the more data, the better. The algorithm might found topics inside the topics. Let me explain. As we well know, one of the topic is about Mideast news. However, the algorithm split this topic into 3 sub-topics: tension between Israel and Hezbollah (cluster 7), tension between Turkish government and Armenia (cluster 5) or Zionism in Israel (cluster 0). However, even if there are more than 3 found clusters, it’s pretty obvious how we can assign them to their respective general topic. # Must be hand made so the topic names match the above clusters # (Figure 5) regarding their contenttopic_dict = {}topic_names = ['x', 'mideast', 'x', 'space', 'space', 'mideast', 'space', 'space', 'mideast', 'space']for i, topic_num in enumerate(top_index): topic_dict[topic_num]=topic_names[i] df_pred = topic_attribution(tokenized_data, mgp, topic_dict, threshold=0.4) One might ask what is the threshold input parameter of the topic_attribution function. Actually, the topics are allocated to a text given a probability and topic_attribution is a custom function that allows to choose which threshold (confidence degree) to consider in order to belong to a topic. For example, looking at the highest probability allocation of a topic to a text, if this probability is below 0.4 the text will be allocated in a “Others” topic. NB: This custom topic_attribution function is built upon the original function available in the GSDMM package: choose_best_label, which outputs the topic with the highest probability to belong to a document. Now it’s time to allocate the topic found to the documents and compare them with the ground truth (✅ vs ❌) df_pred[['content', 'topic_name', 'topic_true_name']].head(20) Naively comparing the predicted topics to the true topics we would have had a 82% accuracy! 🎯Only with a 9 words average by document, a small corpus of 1705 documents and very few hyper-parameters tuning! It’s great to have an efficient model but it is even better if we are able to simply show and interact with its results. To do so, pyLDAvis is a very powerful tool for topic modeling visualization, allowing to dynamically display the clusters and their content in a 2-D space dimension. Now it’s your turn to try it on your own data (social media comments, online chats’ answers...) 💪 Et voilà ! 👌 I would like to thank Rajaa El Hamdani for reviewing and giving me her feedback. References and other useful resources- The original paper of GSDMM - A nice python package that implements STTM.- The pyLDAvis library to beautifully visualize topics in a bunch of texts (or any bag-of- words alike data).- A recent comparative survey of STTM to see other strategies. PS: For those willing to dive deeper in STTM, there is an interesting further approach (which I have not personally explore for now) called GPU-DMM that has shown SOTA results on Short Text Topic Modeling tasks. In short, GPU-DMM is using pre-trained word embeddings as an external source of knowledge to influence the sampling of words to generate topics and documents.
[ { "code": null, "e": 515, "s": 172, "text": "Topic Modeling aims to find the topics (or clusters) inside a corpus of texts (like mails or news articles), without knowing those topics at first. Here lies the real power of Topic Modeling, you don’t need any labeled or annotated data, only raw texts, and from this chaos Topic Modeling algorithms will find the topics your texts are about!" }, { "code": null, "e": 1073, "s": 515, "text": "In this post we will describe the intuition and logic behind the most popular approach for Topic Modeling, the LDA, and see its limitation on short texts. Given this post is about Short Text Topic Modeling (STTM) we will not dive into the details of LDA. The reader willing to deepen his knowledge of LDA can find great articles and useful resources about LDA here and here. Then, in a second part, we will present a new approach for STTM and finally see in a third part how to easily apply it (fit/predict ✌️) on a toy dataset and evaluate its performance." }, { "code": null, "e": 1290, "s": 1073, "text": "The reader already familiar with LDA and Topic Modeling may want to skip the first part and directly go to the second and third ones which present a new approach for Short Text Topic Modeling and its Python coding 🐍." }, { "code": null, "e": 1446, "s": 1290, "text": "The most popular Topic Modeling algorithm is LDA, Latent Dirichlet Allocation. Let’s first unravel this imposing name to have an intuition of what it does." }, { "code": null, "e": 1752, "s": 1446, "text": "Latent because the topics are “hidden”. We have a bunch of texts and we want the algorithm to put them into clusters that will make sense to us. For example, if our text data come from news content, typically the clusters found might be about Mideast Politics, Computer, Space... but we don’t know it yet." }, { "code": null, "e": 1883, "s": 1752, "text": "Dirichlet stands for the Dirichlet distribution the model uses as a prior to generate document-topic and word-topic distributions." }, { "code": null, "e": 1943, "s": 1883, "text": "Allocation because we want to allocate topics to our texts." }, { "code": null, "e": 2046, "s": 1943, "text": "Figure 1 below describes how the LDA steps articulate to find the topics within a corpus of documents." }, { "code": null, "e": 2224, "s": 2046, "text": "“A document is generated by sampling a mixture of these topics and then sampling words from that mixture” (Andrew Ng, David Blei and Michael Jordan from the LDA original paper)." }, { "code": null, "e": 2710, "s": 2224, "text": "NB: In the Figure 1 above, we have set K=3 topics and N=8 words in our vocabulary for illustration ease. We also named these topics Computer, Space and Mideast Politics for illustration ease (rather than calling them topic 1, topic 2 and topic 3). Indeed, it will be our task to understand that the 3 found topics are about Computer, Space and Mideast Politics regarding their content (we will see this part more in depth during the topic attribution of our STTM pipeline in part III)." }, { "code": null, "e": 2867, "s": 2710, "text": "In short, LDA by using Dirichlet distributions as prior knowledge generates documents made of topics and then update them until they match the ground truth." }, { "code": null, "e": 3095, "s": 2867, "text": "Despite its great results on medium or large sized texts (>50 words), typically mails and news articles are about this size range, LDA poorly performs on short texts like Tweets, Reddit posts or StackOverflow titles’ questions." }, { "code": null, "e": 3340, "s": 3095, "text": "Looking at the short texts examples above on Figure 2, it is evident that the assumption that a text is a mixture of topics (remember first step in Figure 1) is not true anymore. We will now assume that a short text is made from only one topic." }, { "code": null, "e": 3651, "s": 3340, "text": "The Gibbs Sampling Dirichlet Mixture Model (GSDMM) is an “altered” LDA algorithm, showing great results on STTM tasks, that makes the initial assumption: 1 topic ↔️1 document. The words within a document are generated using the same unique topic, and not from a mixture of topics as it was in the original LDA." }, { "code": null, "e": 3963, "s": 3651, "text": "Before diving into code and practical aspects, let’s understand GSDMM with an equivalent procedure called the Movie Group Process that will help us understand the different steps and process under the hood of STTM, and how to tune efficiently its hyper-parameters (we remember alpha and beta from the LDA part)." }, { "code": null, "e": 4353, "s": 3963, "text": "Imagine a bunch of students in a restaurant, seating randomly at K tables. They are all asked to write their favorite movies on a paper (but it must remain a short list). The objective is to cluster them in such a way that so students within the same group share the same movie interest. To do so, one after another, students must make a new table choice regarding the two following rules:" }, { "code": null, "e": 4508, "s": 4353, "text": "Rule 1: Choose a table with more students. This rule improves completeness, all students sharing the same movie’s interest are assigned to the same table." }, { "code": null, "e": 4685, "s": 4508, "text": "Rule 2: Choose a table where students share similar movie’s interest. This rule aims to increase homogeneity, we want only members sharing the same movie’s interest at a table." }, { "code": null, "e": 4896, "s": 4685, "text": "After repeating this process, we expect some tables to disappear and others to grow larger and eventually have clusters of students matching their movie’s interest. This is simply what the GSDMM algorithm does!" }, { "code": null, "e": 5051, "s": 4896, "text": "In this part we will build full STTM pipeline from a concrete example using the 20 News Groups dataset from Scikit-learn used for Topic Modeling on texts." }, { "code": null, "e": 5143, "s": 5051, "text": "First thing first, we need to download the STTM script from Github into our project folder." }, { "code": null, "e": 5203, "s": 5143, "text": "cd sttm_projectgit clone https://github.com/rwalk/gsdmm.git" }, { "code": null, "e": 5303, "s": 5203, "text": "Now, we can start implementing the STTM pipeline (here is a static version of the notebook I used)." }, { "code": null, "e": 5895, "s": 5303, "text": "# Useful libsfrom sklearn.datasets import fetch_20newsgroupsimport pickleimport pandas as pdimport numpy as np# STTM lib from Githubfrom gsdmm import MovieGroupProcess# Custom python scripts for preprocessing, prediction and# visualization that I will define more in depth laterfrom preprocessing import tokenizefrom topic_allocation import top_words, topic_attributionfrom visualisation import plot_topic_notebook# Load the 20NewsGroups dataset from sklearncats = ['talk.politics.mideast', 'comp.windows.x', 'sci.space']newsgroups_train = fetch_20newsgroups(subset=’train’, categories=cats)" }, { "code": null, "e": 6161, "s": 5895, "text": "However, in this exercise, we will not use the whole content of the news to extrapolate a topic from it, but only consider the Subject and the first sentence of the news (see Figure 3 below). Indeed, we need short texts for short texts topic modeling... obviously 🙏" }, { "code": null, "e": 6300, "s": 6161, "text": "Besides, we will only look at only 3 topics (evenly distributed among the dataset), for illustration ease. These topics are the following:" }, { "code": null, "e": 6319, "s": 6300, "text": "Mideast Politics 🌍" }, { "code": null, "e": 6327, "s": 6319, "text": "Space 👾" }, { "code": null, "e": 6339, "s": 6327, "text": "Windows X 🖥" }, { "code": null, "e": 6443, "s": 6339, "text": "# Preprocessing and tokenizationtokenized_data = tokenize(df, form_reduction='stemming', predict=False)" }, { "code": null, "e": 6508, "s": 6443, "text": "Here are the preprocessing recipe I have followed for this task:" }, { "code": null, "e": 6544, "s": 6508, "text": "Tokenization using spaCy tokenizer." }, { "code": null, "e": 6587, "s": 6544, "text": "Removing stop words and 1 character words." }, { "code": null, "e": 6754, "s": 6587, "text": "Stemming (given my empirical experience I have observed that stemming gives better clusters on short text compared to lemmatization) using the nltk library’s stemmer." }, { "code": null, "e": 6819, "s": 6754, "text": "Removing empty documents and documents with more than 30 tokens." }, { "code": null, "e": 6870, "s": 6819, "text": "Removing unique token (with a term frequency = 1)." }, { "code": null, "e": 7031, "s": 6870, "text": "However, one must keep in mind that preprocessing is data dependent and should consider to adapt an other preprocessing approach if a different dataset is used." }, { "code": null, "e": 7137, "s": 7031, "text": "Now that our data are cleaned and processed to the proper input format, we are ready to train the model 🚀" }, { "code": null, "e": 7582, "s": 7137, "text": "# Train STTM model# Init of the Gibbs Sampling Dirichlet Mixture Model algorithm# K = number of potential topic (which we don't know a priori)# alpha = # beta = # n_iters = number of iterations to mgp = MovieGroupProcess(K=10, alpha=0.1, beta=0.1, n_iters=30)vocab = set(x for doc in docs for x in doc)n_terms = len(vocab)y = mgp.fit(docs, n_terms)# Save modelwith open(‘dumps/trained_models/v1.model’, “wb”) as f: pickle.dump(mgp, f) f.close()" }, { "code": null, "e": 7676, "s": 7582, "text": "Let’s dive under the hood and understand the hyper-parameters machinery of the GSDMM model 🛠:" }, { "code": null, "e": 7985, "s": 7676, "text": "K = 10. In a real case we are not aware of the exact number of topic so we want to choose a higher value. Theoretically, GSDMM should empty useless clusters and eventually find the exact number of cluster. It will not be the case here, but nothing to worry, we will explain the situation more in depth later." }, { "code": null, "e": 8322, "s": 7985, "text": "alpha = 0.1 and beta = 0.1. Here we kept the default parameters (which work well for several datasets). However, one might want to tune them to improve its topic allocation regarding the completeness and homogeneity of the clusters. Don’t hesitate to refer to the original paper 📖 to understand the balance between these two parameters." }, { "code": null, "e": 8531, "s": 8322, "text": "n_iters = 30. According to the original paper, GSDMM converges quite fast (about 5 iterations) on several datasets and remain very stable. Hence, 30 iterations is a good default value for any kind of dataset." }, { "code": null, "e": 8651, "s": 8531, "text": "Once the model is trained, we want to explore the topics found and check if they are coherent regarding their content 🔎" }, { "code": null, "e": 8836, "s": 8651, "text": "Given that our model has gathered the documents into 10 topics, we must give them a name that will make sense regarding their content. So let’s dive into the topics found by our model." }, { "code": null, "e": 9246, "s": 8836, "text": "doc_count = np.array(mgp.cluster_doc_count)print('Number of documents per topic :', doc_count)print('*'*20)# Topics sorted by the number of document they are allocated totop_index = doc_count.argsort()[-10:][::-1]print('Most important clusters (by number of docs inside):', top_index)print('*'*20)# Show the top 5 words in term frequency for each cluster top_words(mgp.cluster_word_distribution, top_index, 5)" }, { "code": null, "e": 9352, "s": 9246, "text": "The code above display the following statistics that give us insight about what our clusters are made of." }, { "code": null, "e": 9475, "s": 9352, "text": "Ideally, the GSDMM algorithm should find the correct number of topics, here 3, not 10. Three explanations come to my mind:" }, { "code": null, "e": 9611, "s": 9475, "text": "Find other hyper-parameters to empty smaller cluster (refer to original paper for a deeper understanding of alpha and beta parameters)." }, { "code": null, "e": 9836, "s": 9611, "text": "We have both small dataset and vocabulary (about 1700 documents and 2100 words), which may be difficult for the model to extrapolate and distinguish significant difference between topics. As usual, the more data, the better." }, { "code": null, "e": 10163, "s": 9836, "text": "The algorithm might found topics inside the topics. Let me explain. As we well know, one of the topic is about Mideast news. However, the algorithm split this topic into 3 sub-topics: tension between Israel and Hezbollah (cluster 7), tension between Turkish government and Armenia (cluster 5) or Zionism in Israel (cluster 0)." }, { "code": null, "e": 10296, "s": 10163, "text": "However, even if there are more than 3 found clusters, it’s pretty obvious how we can assign them to their respective general topic." }, { "code": null, "e": 10798, "s": 10296, "text": "# Must be hand made so the topic names match the above clusters # (Figure 5) regarding their contenttopic_dict = {}topic_names = ['x', 'mideast', 'x', 'space', 'space', 'mideast', 'space', 'space', 'mideast', 'space']for i, topic_num in enumerate(top_index): topic_dict[topic_num]=topic_names[i] df_pred = topic_attribution(tokenized_data, mgp, topic_dict, threshold=0.4) " }, { "code": null, "e": 11256, "s": 10798, "text": "One might ask what is the threshold input parameter of the topic_attribution function. Actually, the topics are allocated to a text given a probability and topic_attribution is a custom function that allows to choose which threshold (confidence degree) to consider in order to belong to a topic. For example, looking at the highest probability allocation of a topic to a text, if this probability is below 0.4 the text will be allocated in a “Others” topic." }, { "code": null, "e": 11464, "s": 11256, "text": "NB: This custom topic_attribution function is built upon the original function available in the GSDMM package: choose_best_label, which outputs the topic with the highest probability to belong to a document." }, { "code": null, "e": 11571, "s": 11464, "text": "Now it’s time to allocate the topic found to the documents and compare them with the ground truth (✅ vs ❌)" }, { "code": null, "e": 11634, "s": 11571, "text": "df_pred[['content', 'topic_name', 'topic_true_name']].head(20)" }, { "code": null, "e": 11839, "s": 11634, "text": "Naively comparing the predicted topics to the true topics we would have had a 82% accuracy! 🎯Only with a 9 words average by document, a small corpus of 1705 documents and very few hyper-parameters tuning!" }, { "code": null, "e": 12126, "s": 11839, "text": "It’s great to have an efficient model but it is even better if we are able to simply show and interact with its results. To do so, pyLDAvis is a very powerful tool for topic modeling visualization, allowing to dynamically display the clusters and their content in a 2-D space dimension." }, { "code": null, "e": 12224, "s": 12126, "text": "Now it’s your turn to try it on your own data (social media comments, online chats’ answers...) 💪" }, { "code": null, "e": 12238, "s": 12224, "text": "Et voilà ! 👌" }, { "code": null, "e": 12319, "s": 12238, "text": "I would like to thank Rajaa El Hamdani for reviewing and giving me her feedback." }, { "code": null, "e": 12603, "s": 12319, "text": "References and other useful resources- The original paper of GSDMM - A nice python package that implements STTM.- The pyLDAvis library to beautifully visualize topics in a bunch of texts (or any bag-of- words alike data).- A recent comparative survey of STTM to see other strategies." } ]
MySQL Tryit Editor v1.0
SELECT CustomerName, City, Country FROM Customers ORDER BY (CASE WHEN City IS NULL THEN Country ELSE City END); ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, and Opera. If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 50, "s": 0, "text": "SELECT CustomerName, City, Country FROM Customers" }, { "code": null, "e": 65, "s": 50, "text": "ORDER BY (CASE" }, { "code": null, "e": 96, "s": 65, "text": "WHEN City IS NULL THEN Country" }, { "code": null, "e": 106, "s": 96, "text": "ELSE City" }, { "code": null, "e": 112, "s": 106, "text": "END);" }, { "code": null, "e": 114, "s": 112, "text": "​" }, { "code": null, "e": 186, "s": 123, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 246, "s": 186, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 314, "s": 246, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 352, "s": 314, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 437, "s": 352, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 611, "s": 437, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 662, "s": 611, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 730, "s": 662, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 901, "s": 730, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 1001, "s": 901, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 1051, "s": 1001, "text": "WebSQL is supported in Chrome, Safari, and Opera." } ]
Add two numbers represented by linked lists | Practice | GeeksforGeeks
Given two numbers represented by two linked lists of size N and M. The task is to return a sum list. The sum list is a linked list representation of the addition of two input numbers from the last. Example 1: Input: N = 2 valueN[] = {4,5} M = 3 valueM[] = {3,4,5} Output: 3 9 0 Explanation: For the given two linked list (4 5) and (3 4 5), after adding the two linked list resultant linked list will be (3 9 0). Example 2: Input: N = 2 valueN[] = {6,3} M = 1 valueM[] = {7} Output: 7 0 Explanation: For the given two linked list (6 3) and (7), after adding the two linked list resultant linked list will be (7 0). Your Task: The task is to complete the function addTwoLists() which has node reference of both the linked lists and returns the head of the sum list. Expected Time Complexity: O(N+M) Expected Auxiliary Space: O(Max(N,M)) for the resultant list. Constraints: 1 <= N, M <= 5000 +1 shahabuddinbravo40in 11 hours class Solution{ public: //Function to add two numbers represented by linked list. struct Node* addTwoLists(struct Node* first, struct Node* second) { Node *first_reverse=reverse(first); Node *second_reverse=reverse(second); Node *list=new Node(-1),*sum=list; int carry=0,r,temp; while(first_reverse && second_reverse) { temp=(first_reverse->data+second_reverse->data)+carry; r=temp%10; list->next=new Node(r); list=list->next; first_reverse=first_reverse->next; second_reverse=second_reverse->next; carry=temp/10; } if(first_reverse==NULL){ while(second_reverse) { temp=(second_reverse->data)+carry; r=temp%10; list->next=new Node(r); list=list->next; second_reverse=second_reverse->next; carry=temp/10; } } if(second_reverse==NULL){ while(first_reverse) { temp=(first_reverse->data)+carry; r=temp%10; list->next=new Node(r); list=list->next; first_reverse=first_reverse->next; carry=temp/10; } } if(first_reverse==NULL && second_reverse==NULL && carry!=0){ list->next=new Node(carry); list=list->next; } sum=sum->next; return reverse(sum); } Node* reverse(Node *head){ Node *prev=NULL,*ptr=head,*ptr1=head; while(ptr1) { ptr1=ptr1->next; ptr->next=prev; prev=ptr; ptr=ptr1; } return prev; } }; 0 avikumarking9 hours ago Use pen and paper to understand this better. yeah, kind of a lengthy but easy solution. class Solution { public: Node*rev(Node*head,int &len) { if(!head) return head; Node*trail=NULL; while(head) { len++; Node*temp=head; head=head->next; temp->next=trail; trail=temp; } return trail; } struct Node* addTwoLists(struct Node* first, struct Node* second) { if(!first) return second; if(!second) return first; int lenF=0; int lenS=0; first=rev(first,lenF); second=rev(second,lenS); if(lenF>=lenS) { int c=0; Node*head=first; while(second) { int ele=first->data+second->data+c; c=ele/10; ele=ele%10; first->data=ele; first=first->next; second=second->next; } if(c==0) return rev(head,lenF); while(first && c!=0) { int ele=first->data+c; c=ele/10; ele=ele%10; first->data=ele; first=first->next; } if(c!=0) { first=head; Node*trail=NULL; while(first) { trail=first; first=first->next; } trail->next=new Node(c); } return rev(head,lenF); } else { int c=0; Node*head=second; while(first) { int ele=first->data+second->data+c; c=ele/10; ele=ele%10; second->data=ele; first=first->next; second=second->next; } if(c==0) return rev(head,lenS); while(second && c!=0) { int ele=second->data+c; c=ele/10; ele=ele%10; second->data=ele; second=second->next; } if(c!=0) { second=head; Node*trail=NULL; while(second) { trail=second; second=second->next; } trail->next=new Node(c); } return rev(head,lenF); } return NULL; } }; 0 mannukhurana1039721 hours ago java 180/200 test cases pass static Node addTwoLists(Node first, Node second){ if(first==null || second==null){ return first == null?second:first; } String FNum=""; String SNum=""; while(first!=null){ FNum+=first.data; first = first.next; } while(second!=null){ SNum+=second.data; second = second.next; } java.math.BigInteger n1 = new java.math.BigInteger(FNum); java.math.BigInteger n2 = new java.math.BigInteger(SNum); String finalStr = n1.add(n2).toString(); first = new Node(0); Node temp = first; for(int i=0; i<finalStr.length(); i++){ temp.next = new Node(Integer.parseInt(String.valueOf(finalStr.charAt(i)))); temp = temp.next; } return first.next; } +1 bipulharsh1231 day ago struct Node* addTwoLists(struct Node* first, struct Node* second) { // code here int sum=0; first = reverse(first); second = reverse(second); Node *result=nullptr, *new_n=nullptr; while(first || second || sum){ sum += (first?first->data:0)+(second?second->data:0); if(first) first = first->next; if(second) second = second->next; new_n = new Node(sum%10); new_n->next = result; result = new_n; sum /= 10; // Leaving carry value } return result; } 0 hk63017359395 days ago JAVA SOLUTION....................... class Solution{ //Function to add two numbers represented by linked list. static Node addTwoLists(Node first, Node second){ String s="",s1=""; Node dummy = new Node(0); Node l=dummy; Node temp=first; while(temp!=null){ s+=temp.data; temp=temp.next; } temp=second; while(temp!=null){ s1+=temp.data; temp=temp.next; } java.math.BigInteger n1= new java.math.BigInteger(s); java.math.BigInteger n2= new java.math.BigInteger(s1); java.math.BigInteger n=n1.add(n2); String h=n.toString(); //System.out.println(h); for(int i=0;i<h.length();i++){ l.next=new Node(Integer.parseInt(String.valueOf(h.charAt(i)))); l=l.next; } return dummy.next; }} 0 dev1711 week ago simple C++ reverse and take carry forward Node *reverse(struct Node* k){ Node *prev=NULL; while(k){ Node* next=k->next; k->next=prev; prev=k; k=next; } return prev; } struct Node* addTwoLists(struct Node* first, struct Node* second) { // code here Node * k=reverse(first); Node *j=reverse(second); int carry=0; Node *dummy=new Node(-1),*last=dummy; while(k && j){ int val=k->data+j->data+carry; Node *temp=new Node(val%10); last->next=temp; last=temp; carry=val/10; k=k->next; j=j->next; } while(k){ int val=k->data+carry; Node *temp=new Node(val%10); last->next=temp; last=temp; carry=val/10; k=k->next; } while(j){ int val=j->data+carry; Node *temp=new Node(val%10); last->next=temp; last=temp; carry=val/10; j=j->next; } if(carry>0){ last->next=new Node(carry); } return reverse(dummy->next); } 0 someshthakur901 week ago why my code does not work for large test cases!! static Node addTwoLists(Node first, Node second){ if(first==null&&second==null) { return null; } if(first==null&&second!=null){ return second; } if(first!=null&&second==null){ return first; } long num1=0,num=0,sum=0; while(first!=null){ num1 = num1*10 + first.data; first = first.next; } while(second!=null){ num = num*10 + second.data; second = second.next; } //System.out.println(num); // System.out.println(num1); sum = num1 + num; //System.out.println(sum); long d = sum%10; Node sumList = new Node((int)d); sum=sum/10; Node temp = sumList; temp.next=null; while(temp!=null&&sum!=0){ long D = sum%10; temp.next = new Node((int)D); temp = temp.next; sum = sum/10; } Node current=sumList,prev=null,next=null; while(current!=null){ next = current.next; current.next=prev; prev = current; current = next; } sumList = prev; return sumList; 0 satyamagarwal2491 week ago import sys sys.setrecursionlimit(10**7) class Solution: def addTwoLists(self, first, second): self.result = None l1 = l2 = 0 node = first while node: node = node.next l1 += 1 node = second while node: node = node.next l2 += 1 if l2 > l1: first, second = second, first l1, l2 = l2, l1 k = l1 - l2 f = first s = second while k > 0: f = f.next k -= 1 self.carry = self.addUtil(f,s) # print('self.carry', self.carry) carry = self.addRest(first, l1 - l2) if carry: self.insertBegin(carry) return self.result def addRest(self, f, k): if k == 0: return self.carry carry = self.addRest(f.next, k-1) sum_ = f.data + carry # print('sum_', sum_) self.insertBegin(sum_%10) return sum_ // 10 def addUtil(self, a, b): if a is None: return 0 carry = self.addUtil(a.next, b.next) sum_ = a.data + b.data + carry self.insertBegin(sum_%10) return sum_ // 10 def insertBegin(self, data): temp = Node(data) temp.next = self.result self.result = temp +1 chinmayanaokar2 weeks ago public Node addTwoLists(Node first, Node second) { if(first ==null || second==null) { return first==null ? second : first; } int carry=0; Node third=new Node(0); while(first !=null || second !=null || carry !=0) { int val_1= ( first ==null ? 0 : first.data); int val_2= ( second ==null ? 0 : second.data); int sum= val_1 + val_2 + carry; int newVal= sum%10; Node p= new Node(newVal); third.next=p; third=p; carry= sum/10; first= ( first==null ? null : first.next ); second= ( second ==null ? null : second.next ); } return third.next; +3 souravdas62 weeks ago class Solution{ public: Node*reverse(Node*head){ Node*prev=NULL,*nex=NULL,*curr=head; while(curr!=NULL){ nex=curr->next; curr->next=prev; prev=curr; curr=nex; } return prev; } //Function to add two numbers represented by linked list. struct Node* addTwoLists(struct Node* first, struct Node* second) { first=reverse(first); second=reverse(second); Node*curr=NULL,*res=NULL,*t; int s=0; int c=0; while(first!=NULL or second!=NULL){ s=c+(first?first->data:0)+(second?second->data:0); c=(s>=10)?1:0; s=s%10; t=new Node(s); if(res==NULL)res=t; else curr->next=t; curr=t; if(first)first=first->next; if(second)second=second->next; } if(c>0){ t=new Node(c); curr->next=t; } res=reverse(res); return res; }}; 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": 340, "s": 238, "text": "Given two numbers represented by two linked lists of size N and M. The task is to return a sum list. " }, { "code": null, "e": 437, "s": 340, "text": "The sum list is a linked list representation of the addition of two input numbers from the last." }, { "code": null, "e": 448, "s": 437, "text": "Example 1:" }, { "code": null, "e": 653, "s": 448, "text": "Input:\nN = 2\nvalueN[] = {4,5}\nM = 3\nvalueM[] = {3,4,5}\nOutput: 3 9 0 \nExplanation: For the given two linked\nlist (4 5) and (3 4 5), after adding\nthe two linked list resultant linked\nlist will be (3 9 0)." }, { "code": null, "e": 664, "s": 653, "text": "Example 2:" }, { "code": null, "e": 855, "s": 664, "text": "Input:\nN = 2\nvalueN[] = {6,3}\nM = 1\nvalueM[] = {7}\nOutput: 7 0\nExplanation: For the given two linked\nlist (6 3) and (7), after adding the\ntwo linked list resultant linked list\nwill be (7 0)." }, { "code": null, "e": 1008, "s": 855, "text": "Your Task:\nThe task is to complete the function addTwoLists() which has node reference of both the linked lists and returns the head of the sum list. " }, { "code": null, "e": 1103, "s": 1008, "text": "Expected Time Complexity: O(N+M)\nExpected Auxiliary Space: O(Max(N,M)) for the resultant list." }, { "code": null, "e": 1134, "s": 1103, "text": "Constraints:\n1 <= N, M <= 5000" }, { "code": null, "e": 1137, "s": 1134, "text": "+1" }, { "code": null, "e": 1167, "s": 1137, "text": "shahabuddinbravo40in 11 hours" }, { "code": null, "e": 3052, "s": 1167, "text": "class Solution{ public: //Function to add two numbers represented by linked list. struct Node* addTwoLists(struct Node* first, struct Node* second) { Node *first_reverse=reverse(first); Node *second_reverse=reverse(second); Node *list=new Node(-1),*sum=list; int carry=0,r,temp; while(first_reverse && second_reverse) { temp=(first_reverse->data+second_reverse->data)+carry; r=temp%10; list->next=new Node(r); list=list->next; first_reverse=first_reverse->next; second_reverse=second_reverse->next; carry=temp/10; } if(first_reverse==NULL){ while(second_reverse) { temp=(second_reverse->data)+carry; r=temp%10; list->next=new Node(r); list=list->next; second_reverse=second_reverse->next; carry=temp/10; } } if(second_reverse==NULL){ while(first_reverse) { temp=(first_reverse->data)+carry; r=temp%10; list->next=new Node(r); list=list->next; first_reverse=first_reverse->next; carry=temp/10; } } if(first_reverse==NULL && second_reverse==NULL && carry!=0){ list->next=new Node(carry); list=list->next; } sum=sum->next; return reverse(sum); } Node* reverse(Node *head){ Node *prev=NULL,*ptr=head,*ptr1=head; while(ptr1) { ptr1=ptr1->next; ptr->next=prev; prev=ptr; ptr=ptr1; } return prev; } };" }, { "code": null, "e": 3054, "s": 3052, "text": "0" }, { "code": null, "e": 3078, "s": 3054, "text": "avikumarking9 hours ago" }, { "code": null, "e": 5708, "s": 3078, "text": "Use pen and paper to understand this better.\nyeah, kind of a lengthy but easy solution.\nclass Solution\n{\n public:\n Node*rev(Node*head,int &len)\n {\n if(!head)\n return head;\n Node*trail=NULL;\n while(head)\n {\n len++;\n Node*temp=head;\n head=head->next;\n temp->next=trail;\n trail=temp;\n }\n return trail;\n }\n struct Node* addTwoLists(struct Node* first, struct Node* second)\n {\n if(!first)\n return second;\n if(!second)\n return first;\n int lenF=0;\n int lenS=0;\n first=rev(first,lenF);\n second=rev(second,lenS);\n if(lenF>=lenS)\n {\n int c=0;\n Node*head=first;\n while(second)\n {\n int ele=first->data+second->data+c;\n c=ele/10;\n ele=ele%10;\n first->data=ele;\n first=first->next;\n second=second->next;\n }\n if(c==0)\n return rev(head,lenF);\n while(first && c!=0)\n {\n int ele=first->data+c;\n c=ele/10;\n ele=ele%10;\n first->data=ele;\n first=first->next;\n }\n if(c!=0)\n {\n first=head;\n Node*trail=NULL;\n while(first)\n {\n trail=first;\n first=first->next;\n }\n trail->next=new Node(c);\n }\n return rev(head,lenF);\n }\n else\n {\n int c=0;\n Node*head=second;\n while(first)\n {\n int ele=first->data+second->data+c;\n c=ele/10;\n ele=ele%10;\n second->data=ele;\n first=first->next;\n second=second->next;\n }\n if(c==0)\n return rev(head,lenS);\n while(second && c!=0)\n {\n int ele=second->data+c;\n c=ele/10;\n ele=ele%10;\n second->data=ele;\n second=second->next;\n }\n if(c!=0)\n {\n second=head;\n Node*trail=NULL;\n while(second)\n {\n trail=second;\n second=second->next;\n }\n trail->next=new Node(c);\n }\n return rev(head,lenF);\n }\n return NULL;\n }\n};" }, { "code": null, "e": 5710, "s": 5708, "text": "0" }, { "code": null, "e": 5740, "s": 5710, "text": "mannukhurana1039721 hours ago" }, { "code": null, "e": 5746, "s": 5740, "text": "java " }, { "code": null, "e": 5770, "s": 5746, "text": "180/200 test cases pass" }, { "code": null, "e": 6698, "s": 5772, "text": "static Node addTwoLists(Node first, Node second){\n \n if(first==null || second==null){\n return first == null?second:first;\n }\n \n String FNum=\"\";\n String SNum=\"\";\n \n \n while(first!=null){\n FNum+=first.data;\n first = first.next;\n }\n while(second!=null){\n SNum+=second.data;\n second = second.next;\n }\n \n java.math.BigInteger n1 = new java.math.BigInteger(FNum);\n java.math.BigInteger n2 = new java.math.BigInteger(SNum);\n String finalStr = n1.add(n2).toString();\n \n first = new Node(0);\n Node temp = first;\n for(int i=0; i<finalStr.length(); i++){\n temp.next = new Node(Integer.parseInt(String.valueOf(finalStr.charAt(i))));\n temp = temp.next;\n }\n \n \n return first.next;\n \n }" }, { "code": null, "e": 6703, "s": 6700, "text": "+1" }, { "code": null, "e": 6726, "s": 6703, "text": "bipulharsh1231 day ago" }, { "code": null, "e": 7323, "s": 6726, "text": "struct Node* addTwoLists(struct Node* first, struct Node* second) { // code here int sum=0; first = reverse(first); second = reverse(second); Node *result=nullptr, *new_n=nullptr; while(first || second || sum){ sum += (first?first->data:0)+(second?second->data:0); if(first) first = first->next; if(second) second = second->next; new_n = new Node(sum%10); new_n->next = result; result = new_n; sum /= 10; // Leaving carry value } return result; }" }, { "code": null, "e": 7325, "s": 7323, "text": "0" }, { "code": null, "e": 7348, "s": 7325, "text": "hk63017359395 days ago" }, { "code": null, "e": 7385, "s": 7348, "text": "JAVA SOLUTION......................." }, { "code": null, "e": 8185, "s": 7385, "text": "class Solution{ //Function to add two numbers represented by linked list. static Node addTwoLists(Node first, Node second){ String s=\"\",s1=\"\"; Node dummy = new Node(0); Node l=dummy; Node temp=first; while(temp!=null){ s+=temp.data; temp=temp.next; } temp=second; while(temp!=null){ s1+=temp.data; temp=temp.next; } java.math.BigInteger n1= new java.math.BigInteger(s); java.math.BigInteger n2= new java.math.BigInteger(s1); java.math.BigInteger n=n1.add(n2); String h=n.toString(); //System.out.println(h); for(int i=0;i<h.length();i++){ l.next=new Node(Integer.parseInt(String.valueOf(h.charAt(i)))); l=l.next; } return dummy.next; }}" }, { "code": null, "e": 8187, "s": 8185, "text": "0" }, { "code": null, "e": 8204, "s": 8187, "text": "dev1711 week ago" }, { "code": null, "e": 8247, "s": 8204, "text": "simple C++ reverse and take carry forward " }, { "code": null, "e": 9477, "s": 8247, "text": " Node *reverse(struct Node* k){\n Node *prev=NULL;\n while(k){\n Node* next=k->next;\n k->next=prev;\n prev=k;\n k=next;\n }\n return prev;\n }\n struct Node* addTwoLists(struct Node* first, struct Node* second)\n {\n // code here\n Node * k=reverse(first);\n Node *j=reverse(second);\n \n int carry=0;\n Node *dummy=new Node(-1),*last=dummy;\n while(k && j){\n int val=k->data+j->data+carry;\n Node *temp=new Node(val%10);\n last->next=temp;\n last=temp;\n carry=val/10;\n k=k->next;\n j=j->next;\n }\n while(k){\n int val=k->data+carry;\n Node *temp=new Node(val%10);\n last->next=temp;\n last=temp;\n carry=val/10;\n k=k->next;\n\n }\n while(j){\n int val=j->data+carry;\n Node *temp=new Node(val%10);\n last->next=temp;\n last=temp;\n carry=val/10;\n j=j->next;\n\n }\n if(carry>0){\n last->next=new Node(carry);\n }\n return reverse(dummy->next);\n \n }" }, { "code": null, "e": 9479, "s": 9477, "text": "0" }, { "code": null, "e": 9504, "s": 9479, "text": "someshthakur901 week ago" }, { "code": null, "e": 9553, "s": 9504, "text": "why my code does not work for large test cases!!" }, { "code": null, "e": 10739, "s": 9553, "text": " static Node addTwoLists(Node first, Node second){ if(first==null&&second==null) { return null; } if(first==null&&second!=null){ return second; } if(first!=null&&second==null){ return first; } long num1=0,num=0,sum=0; while(first!=null){ num1 = num1*10 + first.data; first = first.next; } while(second!=null){ num = num*10 + second.data; second = second.next; } //System.out.println(num); // System.out.println(num1); sum = num1 + num; //System.out.println(sum); long d = sum%10; Node sumList = new Node((int)d); sum=sum/10; Node temp = sumList; temp.next=null; while(temp!=null&&sum!=0){ long D = sum%10; temp.next = new Node((int)D); temp = temp.next; sum = sum/10; } Node current=sumList,prev=null,next=null; while(current!=null){ next = current.next; current.next=prev; prev = current; current = next; } sumList = prev; return sumList;" }, { "code": null, "e": 10743, "s": 10741, "text": "0" }, { "code": null, "e": 10770, "s": 10743, "text": "satyamagarwal2491 week ago" }, { "code": null, "e": 12158, "s": 10770, "text": "import sys\nsys.setrecursionlimit(10**7)\nclass Solution:\n def addTwoLists(self, first, second):\n self.result = None\n l1 = l2 = 0\n \n node = first\n while node:\n node = node.next\n l1 += 1\n \n node = second\n while node:\n node = node.next\n l2 += 1\n \n if l2 > l1:\n first, second = second, first\n l1, l2 = l2, l1\n\n k = l1 - l2\n f = first\n s = second\n while k > 0:\n f = f.next\n k -= 1\n \n self.carry = self.addUtil(f,s)\n # print('self.carry', self.carry)\n carry = self.addRest(first, l1 - l2)\n if carry:\n self.insertBegin(carry)\n return self.result\n\n def addRest(self, f, k):\n if k == 0:\n return self.carry\n carry = self.addRest(f.next, k-1)\n sum_ = f.data + carry\n # print('sum_', sum_)\n self.insertBegin(sum_%10)\n return sum_ // 10\n \n \n def addUtil(self, a, b):\n if a is None:\n return 0\n carry = self.addUtil(a.next, b.next)\n sum_ = a.data + b.data + carry\n self.insertBegin(sum_%10)\n return sum_ // 10\n \n def insertBegin(self, data):\n temp = Node(data)\n temp.next = self.result\n self.result = temp\n" }, { "code": null, "e": 12161, "s": 12158, "text": "+1" }, { "code": null, "e": 12187, "s": 12161, "text": "chinmayanaokar2 weeks ago" }, { "code": null, "e": 12972, "s": 12187, "text": "public Node addTwoLists(Node first, Node second) { if(first ==null || second==null) { return first==null ? second : first; } int carry=0; Node third=new Node(0); while(first !=null || second !=null || carry !=0) { int val_1= ( first ==null ? 0 : first.data); int val_2= ( second ==null ? 0 : second.data); int sum= val_1 + val_2 + carry; int newVal= sum%10; Node p= new Node(newVal); third.next=p; third=p; carry= sum/10; first= ( first==null ? null : first.next ); second= ( second ==null ? null : second.next ); } return third.next;" }, { "code": null, "e": 12975, "s": 12972, "text": "+3" }, { "code": null, "e": 12997, "s": 12975, "text": "souravdas62 weeks ago" }, { "code": null, "e": 13953, "s": 12997, "text": "class Solution{ public: Node*reverse(Node*head){ Node*prev=NULL,*nex=NULL,*curr=head; while(curr!=NULL){ nex=curr->next; curr->next=prev; prev=curr; curr=nex; } return prev; } //Function to add two numbers represented by linked list. struct Node* addTwoLists(struct Node* first, struct Node* second) { first=reverse(first); second=reverse(second); Node*curr=NULL,*res=NULL,*t; int s=0; int c=0; while(first!=NULL or second!=NULL){ s=c+(first?first->data:0)+(second?second->data:0); c=(s>=10)?1:0; s=s%10; t=new Node(s); if(res==NULL)res=t; else curr->next=t; curr=t; if(first)first=first->next; if(second)second=second->next; } if(c>0){ t=new Node(c); curr->next=t; } res=reverse(res); return res; }};" }, { "code": null, "e": 14099, "s": 13953, "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": 14135, "s": 14099, "text": " Login to access your submissions. " }, { "code": null, "e": 14145, "s": 14135, "text": "\nProblem\n" }, { "code": null, "e": 14155, "s": 14145, "text": "\nContest\n" }, { "code": null, "e": 14218, "s": 14155, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 14366, "s": 14218, "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": 14574, "s": 14366, "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": 14680, "s": 14574, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
JFreeChart - Quick Guide
A chart is a graphical representation of information. There are various tools available, which can be used to create different types of charts. The JFreeChart project was founded in February 2000, by David Gilbert. Today, it is the most widely used charting library among Java developers. This tutorial will help you understand what exactly JFreeChart is, why is it required, and the various ways to create different types of charts within a Java-based application or independently. JfreeChart is an open source library developed in Java. It can be used within Java based applications to create a wide range of charts. By using JFreeChart, we can create all the major type of 2D and 3D charts such as pie chart, bar chart, line chart, XY chart and 3D charts. JFreeChart is open source and 100% free, which permits usage in the commercial applications without any cost. We have enlisted here some more points in favor of why you should use JFreeChart − It comes with well documented APIs, which makes it quite easy to understand. It comes with well documented APIs, which makes it quite easy to understand. It supports a wide range of chart types such as Pie Chart, Line Chart, Bar Chart, Area Chart and 3D charts. It supports a wide range of chart types such as Pie Chart, Line Chart, Bar Chart, Area Chart and 3D charts. JFreeChart is easy to extend and can be used in both, the client-side, as well as the server-side applications. JFreeChart is easy to extend and can be used in both, the client-side, as well as the server-side applications. It supports multiple output formats like PNG, JPEG, PDF, SVG etc. It supports multiple output formats like PNG, JPEG, PDF, SVG etc. It allows extensive customizations of charts. It allows extensive customizations of charts. Consider a situation where you are developing an application and you need to show the data in the form of charts, and the data itself is populated dynamically. In such case, displaying the data in the form of charts using JFreeChart programming is very simple. JFreeChart is popular for its efficient chart creation and user-friendly installation setup. This chapter describes the process of setting up JFreeChart on Windows and Linux. User administration is needed while installing JFreeChart. To install JFreeChart, there are three following steps viz... To verify Java installation, open the console and execute the following java command − Once Java installation is done properly, then you should get the following output for both the operating systems − Windows Java version "1.7.0_60" Java (TM) SE Run Time Environment (build 1.7.0_60-b19) Java HotSpot(TM) 64-bit Server VM (build 24.60-b09,mixed mode) Linux java version "1.7.0_25" OpenJDK Runtime Environment (rhel2.3.10.4.el6_4-x86_64) OpenJDK 64-Bit Server VM (build 23.7-b01, mixed mode) If you do not have Java installed, then install the Java Software Development Kit (SDK) from the link − https://www.oracle.com/technetwork/java/javase/downloads/index.html We assume that you have installed Java 1.7.0_60 version before proceeding for this tutorial. Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example, Windows Set Environmental variable JAVA_HOME to C:\ProgramFiles\java\jdk1.7.0_60 Linux export JAVA_HOME=/usr/local/java-current Append Java compiler location to System Path. Windows Append the String; C:\Program Files\Java\jdk1.7.0_60\bin to the end of the system variable PATH. Linux export PATH=$PATH:$JAVA_HOME/bin/ Verify the command java -version from the command prompted as explained above. Download the latest version of JFreeChart.zip from the link http://www.jfree.org/jfreechart/download/ Unzip the downloaded file at any location from where required libraries can be linked into your Java program. The following image shows the structure of the directories and files − Add complete path of jfreechart-1.0.18.jar and jcommon-1.0.22.jar files to the CLASSPATH as shown below − Windows Append the Strings “C:\ jfreechart-1.0.18\lib\ jfreechart-1.0.18.jar” and “C:\ jfreechart-1.0.18\lib\ jcommon-1.0.22.jar” to the end of the user variable CLASSPATH Linux Export CLASSPATH=$CLASSPATH: /usr/share/jfreechart1.0.18/lib/jfreechart-1.0.18.jar: /usr/share/jfreechart-1.0.18/lib/jcommon1.0.22.jar Note − Inorder to communicate with MySql database you need to set the classpath to mysql-connector-java-5.0.8-bin.jar too. This chapter explains basic class level and application level architectures of JFreeChart to give you an idea about how JFreeChart interacts with different classes and how it fits in your Java based application. The class level architecture explains how various classes from the library interact with each other to create various types of charts. Following is the detail of the units used in the above block diagram − File The source having user input to be used for creating a dataset in the file. Database The source having user input to be used for creating a dataset in the database. Create Dataset Accepts the dataset and stores the dataset into dataset object. General Dataset This type of dataset is mainly used for pie charts. Category Dataset This type of dataset is used for bar chart, line chart,etc. Series Dataset This type of dataset is used for storing series of data and construct line charts. Series Collection Dataset The different categories of series datasets are added to series collection dataset. This type of dataset is used for XYLine Charts. Create Chart This is the method which is executed to create final chart. Frame/Image The chart is displayed on a Swing Frame or an image is created. The application level architecture explains where JFreeChart library sits inside a Java Application. The client program receives user data and then it uses standard Java and JFreeChart APIs based on requirements to generate the output in the form of either a frame, which can be displayed directly inside the application or independently in the image formats such as JPEG or PNG. In this chapter, we will discuss about some of the important packages, classes, and methods from JFreeChart library. These packages, classes, and methods are the most frequently used while creating a variety of charts using JFreeChart library. ChartFactory is an abstract class under the org.jfree.chart package. It provides a collection of utility methods for generating standard charts. Following is a list of few of the important methods − ChartFactory() Default constructor of ChartFactory class. createPieChart(java.lang.String title, PieDataset dataset, boolean legend, boolean tooltips, boolean urls) This method creates a pie chart with default settings. It returns JfreeChart type object. createPieChart3D(java.lang.String title, PieDataset dataset, boolean legend, boolean tooltips, boolean urls This method creates a 3D pie chart using the specified dataset. createBarChart(java.lang.String title, java.lang.String categoryAxisLabel, java.lang.String valueAxisLabel, CategoryDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls) The argument java.lang.String categoryAxisLabel is the label for values placed on X-axis. The argument java.lang.String valueAxisLabel is the label for values placed on Y-axis. This method creates a bar chart. createBarChart3D(java.lang.String title, java.lang.String categoryAxisLabel, java.lang.String valueAxisLabel, CategoryDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls) This Method Creates a bar chart with a 3D effect. It returns JfreeChart type object. createLineChart(java.lang.String title, java.lang.String categoryAxisLabel, java.lang.String valueAxisLabel, CategoryDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls) This method creates a line chart with default settings. createLineChart3D(java.lang.String title, java.lang.String categoryAxisLabel, java.lang.String valueAxisLabel, CategoryDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls) This method creates a line chart with 3D effect. createXYLineChart(java.lang.String title, java.lang.String xAxisLabel, java.lang.String yAxisLabel, XYDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls) This method creates a line chart based on XYDataset with default settings. ChartFrame class under the org.jfree.chart package, provides all frame related functions and utilities. ChartFrame class inherits functionalities from parent classes such as Frame, Window, Container, and Component classes. ChartFrame (java.lang.Frame String, JfreeChart chart) It constructs a frame. Chart Frame (java.lang.Frame String, JfreeChart chart, boolean scrollpane) It constructs a frame. getChartPanel() This method returns the chart panel for a frame. ChartPanel class from the org.jfree.chart package is used as a swing GUI component for displaying JfreeChart object. ChartPanel(JFreeChart chart) This constructor constructs a panel that displays the specified chart. ChartPanel(JFreeChart chart, boolean useBuffer) This constructor constructs a panel containing a chart. ChartPanel(JFreeChart chart, boolean properties, boolean save, boolean print, boolean zoom, boolean tooltips) This constructor constructs a JFreeChart panel. setPreferredSize(java.awt.Dimension) This method is used to set the frame size using java.awt. Dimension class object as an argument. This method is taken from javax.swing.JComponent. CharUtilites class from the org.jfree.chart package provides a collection of utility methods of JFreeCharts including methods for converting charts into image file format such as PNG, JPEG, and creating HTML image maps. ChartUtilities() This is a default constructor of a class saveChartAsPNG(java.io.File file, JfreeChart chart, int width, int height) This method converts and saves a chart to the specified file in PNG format. saveChartAsJPEG(java.io.File file, JfreeChart chart, int width, int height) This method converts and saves a chart to the specified file in JPEG format. JFreeChart class is the core class under the org.jfree.chart package. This class provides JFreeChart method to create bar charts, line charts, pie charts, and xy plots including time series data. JfreeChart(Plot plot) This constructor creates a new chart based on the supplied plot. JfreeChart(java.lang.String title, java.awt.Font titleFont, Plot plot, boolean createLegend) This constructor creates a new chart with the given title and plot. JfreeChart(java.lang.String title, Plot plot) This constructor creates a new chart with the given title and plot. getXYPlot() This method Returns the plot chart as XYPlot. Using XYPolt, we can do some utility operations on xy charts. This class is a part of org.jfree.chart.plot package and extends Plot class from the same package. This class provides methods to create Pie Plots. PiePlot() It creates a new plot. PiePlot(PieDataset dataset) It creates a plot that draws a pie chart for the specified dataset. setStartAngle(double angle) This Method sets the starting angle and sends a PlotChangeEvent to all registered listeners PiePlot3D class is a subclass of PiePlot class under the same package. Hence, this class has the same features as PiePlot class, except it is used to create 3D plots. PiePlot3D() This constructor creates a new instance with no dataset. PiePlot3D(PieDataset dataset) This constructor creates a pie chart with three dimensional effect using a specified dataset. setForegroundAlpha(float alpha) It sets the alpha-transparency for the plot and sends a PlotChangeEvent to all registered listeners. This is taken from one of the parent Plot classes. setInteriorGap(double percent) It sets the interior gap and sends a PlotChangeEvent to all registered listeners. This controls the space between the edges of the pie plot and the plot area itself (i. e., the region where the section labels appear). This method is taken from the parent class PiePlot. This is a serialized class available in org.jfree.chart.plot package and it is used to show the orientation of a 2D plot. The orientation can either be vertical or horizontal. It sets the orientation of Y-axis. A conventional plot has a vertical Y- axis. isHorizontal() This method returns true if this orientation is HORIZONTAL, and false otherwise. isVertical() This Method returns true if this orientation is VERTICAL, and false otherwise. This is a general class available in org.jfree.chart.plot package and it is used for the plotting data in the form of (x,y) pairs. This plot can use data from any other class that implements the XYDataSet Interface. XYPlot makes use of a XYItemRenderer to draw each point on the plot. XYPlot() This contractor creates a new XYPlot instance with no dataset, no axes and no renderer. XYPlot(XYDataset dataset, ValueAxis domainAxis, ValueAxis rangeAxis, XYItemRenderer renderer) This constructor creates a new plot with the specified dataset, axis, and renderer. setRenderer(XYItemRenderer renderer) This method sets the renderer for the primary dataset and sends a change event to all registered listeners. This class is available in org.jfree.chart.axis package and it can access the numerical data of any axis. When we set the range of any axis to default, it fits according to the range of the data. But using NumberAxis, class we can set the lower margin and upper margin of domain and range axes. NumberAxis( ) This is a default Constructor of NumberAxis. NumberAxis( java.lang.String label) The constructor NumberAxis uses default values where necessary. setLowerMargin(double margin) It sets the lower margin for the axis (as a percentage of the axis range) and sends an AxisChangeEvent to all registered listeners. This method is taken from parent class of the class ValueAxis. setUpperMargin(double margin) It sets the upper margin for the axis (as a percentage of the axis range) and sends an AxisChangeEvent to all registered listeners. This method is also present in ValueAxis Class. This is the class, available under org.jfree.chart.renderer.xy package, which takes care of connecting data points with lines and draws shapes at each data point. This renderer class is designed for use with the XYPlot class. XYLineAndShapeRenderer() It creates a new renderer with both lines and shapes visible. XYLineAndShapeRenderer (boolean lines, boolean shapes) It creates a new renderer with specific property. setSeriesPaint(int series, java.awt.Paint paint) This method sets the paint used for a series and sends a RendererChangeEvent to all registered listeners. This method is taken from AbstratRenderer abstract class from renderer package in JFreeChart API. setSeriesStroke(int series, java.awt.Stroke stroke) This method Sets the stroke used for a series and sends a RendererChangeEvent to all registered listeners. This method is taken from AbstratRenderer abstract class, which is super class of this package. This is an interface for rendering the format of a single (x, y) item on a XYPlot. The package is org.Jfree.data.general, which has classes and interfaces to define different types of datasets to construct charts. This is an interface used as a general purpose dataset, where values are associated with keys. As the name suggests, you can use this dataset to supply data for pie charts. This interface extends KeyedValues and DataSet interfaces. All the methods used for this interface are taken from KeyedValues, Values, and Dataset interfaces. This is a Default implementation class of a PieDataset interface. DefaultPieDataset() This constructor creates a new dataset, initially empty. DefaultPieDataset(KeyedValues data) It creates a new dataset by copying data from a KeyedValues instance. setValue(java.lang.Comparable key, double value) It sets the data value for a key and sends a DatasetChangeEvent to all registered listeners. setValue(java.lang.Comparable key, java.lang.Number value) It sets the data value for a key and sends a DatasetChangeEvent to all registered listeners. This is an exception class. It raises an exception occurred in the time series of data in the dataset. Exceptions are raised on the occurrence of duplicate or invalid data. The time series must not be applied with duplicates and the format must be valid. This is a default implementation class of CategoryDataset interface. DefaultCategoryDataset() This constructor creates new empty dataset. addValue(double value, java.lang.Comparable rowKey, java.lang.Comparable columnKey) This method adds a value to the table using comparable keys. addValue(java.lang.Number value, java.lang.Comparable rowKey, java.lang.Comparable columnKey) This method adds a value to the table. setValue(double value, java.lang.Comparable rowKey, java.lang.Comparable columnKey) This method adds or updates a value in the table and sends a DatasetChangeEvent to all registered listeners. setValue(java.lang.Number value, java.lang.Comparable rowKey, java.lang.Comparable columnKey) This method adds or updates a value in the table and sends a DatasetChangeEvent to all registered listeners. Refer JFreeChart API for more information on various other methods and fields. The series dataset is used by XY charts. The package is org.Jfree.data.xy, which contains classes and interfaces belonging to xy charts. The core interface is XYDataset. This is an interface through which data in the form of (x,y) items can be accessed. As the name suggests, you can use this dataset to serve XY chart. Some of the methods in this interface are taken from SeriesDateset interface. This is an interface through which data in the form of (x,y,z) items can be accessed. As the name suggests, you can use this dataset to serve XYZ chart. Some of the methods in this interface are taken from SeriesDateset. This is a class, which represents a sequence of zero or more data items in the form (x, y). By default, the items in the series are sorted into ascending order by x-value, and duplicate x-values are permitted. Both the sorting and duplicate defaults can be changed in the constructor. Y-values can be denoted as null to represent missing values. XYSeries(java.lang.Comparable key) This constructor creates a new empty series. XYSeries(java.lang.Comparable key, boolean autoSort) It constructs a new empty series, with the auto-sort flag set as requested, and duplicate values are allowed. XYSeries(java.lang.Comparable key, boolean autoSort, boolean allowDuplicateXValues) It constructs a new xy-series that contains no data. add(double x, double y) This method adds data item into the series. The above method is used in the tutorial example. If you want to learn the remaining methods and fields, please refer JFreeChart API. XYSeriesCollection class has parent classes like AbstractIntervelDataset, AbstractXYDatset, AbstractSeriesDataset and AbstractDataset. Some of the methods in this class belong to parent classes of this class. XYSeriesCollection() It constructs an empty dataset. XYSeriesCollection(XYSeries xyseries) It constructs a dataset and populates it with a single series. addSeries(XYSeries series) This method adds a series to the collection and sends a DatasetChangeEvent to all registered listeners. Refer JFreeChart API for the remaining methods and fields. DefaultXYZDataset class have parent classes like AbstractIntervelDataset, AbstractXYDatset, AbstractSeriesDataset, AbstractDataset and AbstractXYZDataset. Some of the methods in this class belong to parent classes of this class. DefaultXYZDataset() It constructs an empty dataset. addSeries(java.lang.Comparable seriesKey, double[ ][ ] data ) This method adds a series to the collection and sends a DatasetChangeEvent to all registered listeners. Please refer JFreeChart API for the remaining methods and fields. The package is org.jfree.data.time. This package contains classes and interfaces, which are used for the time related data. This class represents a sequence of data items in the form of period values, where period is some instance of RegularTimePeriod abstract class such as Time, Day, Hour, Minute, and Second classes. TimeSeries(java.lang.Comparable name) It creates new empty series. TimeSeries(java.lang.Comarable name, java.lang.String domain, java.lang.Strin range) It creates new time series that contains no data. add(RegularTimePeriod period,double value) This method adds a new data item to the series. Refer JFreeChart API for the remaining methods and fields. This is a class used as a collection of time series objects. This class implements the XYDataset interface, as well as it extends IntervelXYDataset interface. This makes it convenient to collect series data objects. TimeSeriesCollection() It constructs an empty dataset, tied to the default time zone. TimeSeriesCollection(TimeSeries series) It constructs a dataset containing a single series (more can be added), tied to the default time zone. TimeSeriesCollection(TimeSeries series, java.util.TimeZone zone) It constructs a dataset containing a single series (more can be added), tied to a specific time zone. TimeSeriesCollection(java.util.TimeZone zone) It constructs an empty dataset, tied to a specific time zone. addSeries(TimeSeries series) This method adds a series to the collection and sends a DatasetChangeEvent to all registered listeners. Please refer JFreeChart API for the remaining methods and fields. This class represents a second in a particular day. This class is immutable, which is a requirement for all RegularTimePeriod subclass. Second() It constructs a new Second, based on the system date/time. Second(java.util.Date time) It constructs a new instance from the specified date/time and the default time zone. Second(java.util.Date time, java.util.TimeZone zone, java.util.Locale locale) It creates a new second based on the supplied time and time zone. Second(int second, int minute, int hour, int day, int month, int year It creates a new second. Second(int second, Minute minute) It constructs a new Second. getSecond() It returns the second within the minute. next() It returns the second following the present second. Please refer JFreeChart API for the remaining methods and fields. The package is org.jfree.ui. This is the package belongs to JCommons API of JFreeChart. It contains utility classes used for creating frames for pre-configured charts. This is a base class for creating the main frame for simple applications. The frame listens for window closing events, and responds by shutting down the JVM. This is fine for small demo applications. For enterprise applications, you need to use something more robust. The main core methods in this class are taken from Component, Container, Window, Frame, and Jframe classes. ApplicationFrame(java.lang.String title) It creates an application frame with the string title. This class helps to create AWT Frames. This is the reason for why we use this class as super class in this tutorial examples. The methods, which are taken form the parent classes are used for opening a frame, closing a frame, changing the size, changing the background or foreground color, and listeners. This is a class collection of utility methods relating to user interface. centerFrameOnScreen(java.awt.Window frame) It positions the specified frame in the middle of the screen. The above method is used in the tutorial example. Refer JFreeChart API for remaining methods and fields. In a pie chart, the arc length of each sector is proportional to the quantity that it represents. This chapter demonstrates — how we can use JFreeChart to create Pie Chart from a given set of business data. The following example depicts mobile sale with the help of a pie chart. Following is a list of different mobile brands and their sale (units per day). Following is the code to create a Pie Chart by using the above given information. This code helps you to embed a pie chart in any AWT based application. import javax.swing.JPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.data.general.DefaultPieDataset; import org.jfree.data.general.PieDataset; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; public class PieChart_AWT extends ApplicationFrame { public PieChart_AWT( String title ) { super( title ); setContentPane(createDemoPanel( )); } private static PieDataset createDataset( ) { DefaultPieDataset dataset = new DefaultPieDataset( ); dataset.setValue( "IPhone 5s" , new Double( 20 ) ); dataset.setValue( "SamSung Grand" , new Double( 20 ) ); dataset.setValue( "MotoG" , new Double( 40 ) ); dataset.setValue( "Nokia Lumia" , new Double( 10 ) ); return dataset; } private static JFreeChart createChart( PieDataset dataset ) { JFreeChart chart = ChartFactory.createPieChart( "Mobile Sales", // chart title dataset, // data true, // include legend true, false); return chart; } public static JPanel createDemoPanel( ) { JFreeChart chart = createChart(createDataset( ) ); return new ChartPanel( chart ); } public static void main( String[ ] args ) { PieChart_AWT demo = new PieChart_AWT( "Mobile Sales" ); demo.setSize( 560 , 367 ); RefineryUtilities.centerFrameOnScreen( demo ); demo.setVisible( true ); } } Let us keep the above Java code in PieChart_AWT.java file, and then compile and run it from the command prompted as − $javac PieChart_AWT.java $java PieChart_AWT If everything is fine, it will compile and run to generate the following Pie Graph − If you do not need to embed your chart in any application, then you can create chart images at command prompt. JFreeChart allows you to save chart images in either JPG or PNG formats. Let us re-write the above example to generate a JPEG image from a command line. Following are the two APIs provided by JFreeChart library, which you can use to generate either PNG or JPEG image as per your requirement. saveChartAsPNG() − API to save image in PNG format. saveChartAsPNG() − API to save image in PNG format. saveChartAsJPEG() − API to save image in JPEG format. saveChartAsJPEG() − API to save image in JPEG format. import java.io.*; import org.jfree.chart.ChartUtilities; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.data.general.DefaultPieDataset; public class PieChart { public static void main( String[ ] args ) throws Exception { DefaultPieDataset dataset = new DefaultPieDataset( ); dataset.setValue("IPhone 5s", new Double( 20 ) ); dataset.setValue("SamSung Grand", new Double( 20 ) ); dataset.setValue("MotoG", new Double( 40 ) ); dataset.setValue("Nokia Lumia", new Double( 10 ) ); JFreeChart chart = ChartFactory.createPieChart( "Mobile Sales", // chart title dataset, // data true, // include legend true, false); int width = 640; /* Width of the image */ int height = 480; /* Height of the image */ File pieChart = new File( "PieChart.jpeg" ); ChartUtilities.saveChartAsJPEG( pieChart , chart , width , height ); } } Let us keep the above Java code in PieChart.java file, and then compile and run it from the command prompted as − $javac PieChart.java $java PieChart If everything is fine, it will compile and run to create a JPEG image file named PieChart.jpeg in your current directory. This chapter demonstrates how you can use JFreeChart to create Bar Chart from a given set of business data. A bar chart uses different orientation (horizontal or vertical) bars to show comparisons in various categories. One axis (domain axis) of the chart shows the specific domain being compared, and the other axis (range axis) represents discrete values. The following example depicts various car statistics with the help of a bar chart. Following is a list of car brands along with their different characteristics, which we will show using a bar chart − Following is the code to create a Bar Chart from the above given information. This code helps you to embed a bar chart in any AWT based application. import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; public class BarChart_AWT extends ApplicationFrame { public BarChart_AWT( String applicationTitle , String chartTitle ) { super( applicationTitle ); JFreeChart barChart = ChartFactory.createBarChart( chartTitle, "Category", "Score", createDataset(), PlotOrientation.VERTICAL, true, true, false); ChartPanel chartPanel = new ChartPanel( barChart ); chartPanel.setPreferredSize(new java.awt.Dimension( 560 , 367 ) ); setContentPane( chartPanel ); } private CategoryDataset createDataset( ) { final String fiat = "FIAT"; final String audi = "AUDI"; final String ford = "FORD"; final String speed = "Speed"; final String millage = "Millage"; final String userrating = "User Rating"; final String safety = "safety"; final DefaultCategoryDataset dataset = new DefaultCategoryDataset( ); dataset.addValue( 1.0 , fiat , speed ); dataset.addValue( 3.0 , fiat , userrating ); dataset.addValue( 5.0 , fiat , millage ); dataset.addValue( 5.0 , fiat , safety ); dataset.addValue( 5.0 , audi , speed ); dataset.addValue( 6.0 , audi , userrating ); dataset.addValue( 10.0 , audi , millage ); dataset.addValue( 4.0 , audi , safety ); dataset.addValue( 4.0 , ford , speed ); dataset.addValue( 2.0 , ford , userrating ); dataset.addValue( 3.0 , ford , millage ); dataset.addValue( 6.0 , ford , safety ); return dataset; } public static void main( String[ ] args ) { BarChart_AWT chart = new BarChart_AWT("Car Usage Statistics", "Which car do you like?"); chart.pack( ); RefineryUtilities.centerFrameOnScreen( chart ); chart.setVisible( true ); } } Let us keep the above Java code in BarChart_AWT.java file, and then compile and run it from the command prompted as − $javac BarChar_AWT.java $java BarChart_AWT If everything is fine, it will compile and run to generate the following Bar Graph − Let us re-write the above example to generate a JPEG image from a command line. import java.io.*; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.chart.ChartUtilities; public class BarChart { public static void main( String[ ] args )throws Exception { final String fiat = "FIAT"; final String audi = "AUDI"; final String ford = "FORD"; final String speed = "Speed"; final String millage = "Millage"; final String userrating = "User Rating"; final String safety = "safety"; final DefaultCategoryDataset dataset = new DefaultCategoryDataset( ); dataset.addValue( 1.0 , fiat , speed ); dataset.addValue( 3.0 , fiat , userrating ); dataset.addValue( 5.0 , fiat , millage ); dataset.addValue( 5.0 , fiat , safety ); dataset.addValue( 5.0 , audi , speed ); dataset.addValue( 6.0 , audi , userrating ); dataset.addValue( 10.0 , audi , millage ); dataset.addValue( 4.0 , audi , safety ); dataset.addValue( 4.0 , ford , speed ); dataset.addValue( 2.0 , ford , userrating ); dataset.addValue( 3.0 , ford , millage ); dataset.addValue( 6.0 , ford , safety ); JFreeChart barChart = ChartFactory.createBarChart( "CAR USAGE STATIStICS", "Category", "Score", dataset,PlotOrientation.VERTICAL, true, true, false); int width = 640; /* Width of the image */ int height = 480; /* Height of the image */ File BarChart = new File( "BarChart.jpeg" ); ChartUtilities.saveChartAsJPEG( BarChart , barChart , width , height ); } } Let us keep the above Java code in BarChart.java file, and then compile and run it from the command prompted as − $javac BarChart.java $java BarChart If everything is fine, it will compile and run to create a JPEG image file named BarChart.jpeg in your current directory. A line chart or line graph displays information as a series of data points (markers) connected by straight line segments. Line Chart shows how data changes at equal time frequency. This chapter demonstrates how we can use JFreeChart to create Line Chart from a given set of business data. The following example draws a line chart to show a trend of number of schools opened in different years starting from 1970. Given data is as follows − Following is the code to create Line Chart from the information above given. This code helps you to embed a line chart in any AWT based application. import org.jfree.chart.ChartPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; public class LineChart_AWT extends ApplicationFrame { public LineChart_AWT( String applicationTitle , String chartTitle ) { super(applicationTitle); JFreeChart lineChart = ChartFactory.createLineChart( chartTitle, "Years","Number of Schools", createDataset(), PlotOrientation.VERTICAL, true,true,false); ChartPanel chartPanel = new ChartPanel( lineChart ); chartPanel.setPreferredSize( new java.awt.Dimension( 560 , 367 ) ); setContentPane( chartPanel ); } private DefaultCategoryDataset createDataset( ) { DefaultCategoryDataset dataset = new DefaultCategoryDataset( ); dataset.addValue( 15 , "schools" , "1970" ); dataset.addValue( 30 , "schools" , "1980" ); dataset.addValue( 60 , "schools" , "1990" ); dataset.addValue( 120 , "schools" , "2000" ); dataset.addValue( 240 , "schools" , "2010" ); dataset.addValue( 300 , "schools" , "2014" ); return dataset; } public static void main( String[ ] args ) { LineChart_AWT chart = new LineChart_AWT( "School Vs Years" , "Numer of Schools vs years"); chart.pack( ); RefineryUtilities.centerFrameOnScreen( chart ); chart.setVisible( true ); } } Let us keep the above Java code in LineChart_AWT.java file, and then compile and run it from the command prompted as − $javac LineChart_AWT.java $java LineChart_AWT If everything is fine, it will compile and run to generate the following Line Graph − Let us re-write the above example to generate a JPEG image from a command line. import java.io.*; import org.jfree.chart.JFreeChart; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; public class LineChart { public static void main( String[ ] args ) throws Exception { DefaultCategoryDataset line_chart_dataset = new DefaultCategoryDataset(); line_chart_dataset.addValue( 15 , "schools" , "1970" ); line_chart_dataset.addValue( 30 , "schools" , "1980" ); line_chart_dataset.addValue( 60 , "schools" , "1990" ); line_chart_dataset.addValue( 120 , "schools" , "2000" ); line_chart_dataset.addValue( 240 , "schools" , "2010" ); line_chart_dataset.addValue( 300 , "schools" , "2014" ); JFreeChart lineChartObject = ChartFactory.createLineChart( "Schools Vs Years","Year", "Schools Count", line_chart_dataset,PlotOrientation.VERTICAL, true,true,false); int width = 640; /* Width of the image */ int height = 480; /* Height of the image */ File lineChart = new File( "LineChart.jpeg" ); ChartUtilities.saveChartAsJPEG(lineChart ,lineChartObject, width ,height); } } Let us keep the above Java code in LineChart.java file, and then compile and run it from the command prompted as − $javac LineChart.java $java LineChart If everything is fine, it will compile and execute to create a JPEG image file named LineChart.jpeg in your current directory. The XY chart (scatter) is based on one data series consisting of a list of X and Y values. Each value pair (X,Y) is a point in a coordinate system. Here, one value determines the horizontal (X) position, and the other determines the vertical (Y) position. This chapter demonstrates — how we can use JFreeChart to create XY Chart from a given set of business data. Consider an example where we want to create an XY chart for all major browsers. Here, different performance scores are gathered from different categories of people as shown below − Following is the code to create an XY Chart from the above given information. This code helps you to embed an XY chart in any AWT based application. import java.awt.Color; import java.awt.BasicStroke; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.ChartFactory; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; public class XYLineChart_AWT extends ApplicationFrame { public XYLineChart_AWT( String applicationTitle, String chartTitle ) { super(applicationTitle); JFreeChart xylineChart = ChartFactory.createXYLineChart( chartTitle , "Category" , "Score" , createDataset() , PlotOrientation.VERTICAL , true , true , false); ChartPanel chartPanel = new ChartPanel( xylineChart ); chartPanel.setPreferredSize( new java.awt.Dimension( 560 , 367 ) ); final XYPlot plot = xylineChart.getXYPlot( ); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer( ); renderer.setSeriesPaint( 0 , Color.RED ); renderer.setSeriesPaint( 1 , Color.GREEN ); renderer.setSeriesPaint( 2 , Color.YELLOW ); renderer.setSeriesStroke( 0 , new BasicStroke( 4.0f ) ); renderer.setSeriesStroke( 1 , new BasicStroke( 3.0f ) ); renderer.setSeriesStroke( 2 , new BasicStroke( 2.0f ) ); plot.setRenderer( renderer ); setContentPane( chartPanel ); } private XYDataset createDataset( ) { final XYSeries firefox = new XYSeries( "Firefox" ); firefox.add( 1.0 , 1.0 ); firefox.add( 2.0 , 4.0 ); firefox.add( 3.0 , 3.0 ); final XYSeries chrome = new XYSeries( "Chrome" ); chrome.add( 1.0 , 4.0 ); chrome.add( 2.0 , 5.0 ); chrome.add( 3.0 , 6.0 ); final XYSeries iexplorer = new XYSeries( "InternetExplorer" ); iexplorer.add( 3.0 , 4.0 ); iexplorer.add( 4.0 , 5.0 ); iexplorer.add( 5.0 , 4.0 ); final XYSeriesCollection dataset = new XYSeriesCollection( ); dataset.addSeries( firefox ); dataset.addSeries( chrome ); dataset.addSeries( iexplorer ); return dataset; } public static void main( String[ ] args ) { XYLineChart_AWT chart = new XYLineChart_AWT("Browser Usage Statistics", "Which Browser are you using?"); chart.pack( ); RefineryUtilities.centerFrameOnScreen( chart ); chart.setVisible( true ); } } Let us keep the above Java code in XYLineChart_AWT.java file, and then compile and run it from the command prompted as: $javac XYLineChart_AWT.java $java XYLineChart_AWT If everything is fine, it will compile and run to generate the following XY Graph − Let us re-write the above example to generate a JPEG image from the command line. import java.io.*; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.data.xy.XYSeries; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.chart.ChartUtilities; public class XYLineChart_image { public static void main( String[ ] args )throws Exception { final XYSeries firefox = new XYSeries( "Firefox" ); firefox.add( 1.0 , 1.0 ); firefox.add( 2.0 , 4.0 ); firefox.add( 3.0 , 3.0 ); final XYSeries chrome = new XYSeries( "Chrome" ); chrome.add( 1.0 , 4.0 ); chrome.add( 2.0 , 5.0 ); chrome.add( 3.0 , 6.0 ); final XYSeries iexplorer = new XYSeries( "InternetExplorer" ); iexplorer.add( 3.0 , 4.0 ); iexplorer.add( 4.0 , 5.0 ); iexplorer.add( 5.0 , 4.0 ); final XYSeriesCollection dataset = new XYSeriesCollection( ); dataset.addSeries( firefox ); dataset.addSeries( chrome ); dataset.addSeries( iexplorer ); JFreeChart xylineChart = ChartFactory.createXYLineChart( "Browser usage statastics", "Category", "Score", dataset, PlotOrientation.VERTICAL, true, true, false); int width = 640; /* Width of the image */ int height = 480; /* Height of the image */ File XYChart = new File( "XYLineChart.jpeg" ); ChartUtilities.saveChartAsJPEG( XYChart, xylineChart, width, height); } } Let us keep the above Java code in XYLineChart_image.java file, and then compile and run it from the command prompted as − $javac XYLineChart_image.java $java XYLineChart_image If everything is fine, it will compile and run to create a JPEG image file named XYLineChart.jpeg in your current directory. The 3D charts are the ones, which appear in a three-dimensional format. You can use these charts to provide better display and clear information. A 3D Pie chart is same as the pie chart additionally with a nice 3D effect. A 3D effect can be achieved by adding a little extra code, which will take care of creating 3D effect in a pie chart. Consider the following example to illustrate mobile sale with the help of a 3D pie chart. Following is a list of different mobile brands and their sale (units per day). Following is the code to create 3D Pie Chart from the above given information. This code helps you to embed a pie chart in any AWT based application. import java.io.*; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PiePlot3D; import org.jfree.data.general.DefaultPieDataset; import org.jfree.chart.ChartUtilities; public class PieChart3D { public static void main( String[ ] args )throws Exception { DefaultPieDataset dataset = new DefaultPieDataset( ); dataset.setValue( "IPhone 5s" , new Double( 20 ) ); dataset.setValue( "SamSung Grand" , new Double( 20 ) ); dataset.setValue( "MotoG" , new Double( 40 ) ); dataset.setValue( "Nokia Lumia" , new Double( 10 ) ); JFreeChart chart = ChartFactory.createPieChart3D( "Mobile Sales" , // chart title dataset , // data true , // include legend true, false); final PiePlot3D plot = ( PiePlot3D ) chart.getPlot( ); plot.setStartAngle( 270 ); plot.setForegroundAlpha( 0.60f ); plot.setInteriorGap( 0.02 ); int width = 640; /* Width of the image */ int height = 480; /* Height of the image */ File pieChart3D = new File( "pie_Chart3D.jpeg" ); ChartUtilities.saveChartAsJPEG( pieChart3D , chart , width , height ); } } Let us keep the above Java code in PieChart3D.java file, and then compile and run it from the command prompted as − $javac PieChart3D.java $java PieChart3D If everything is fine, it will compile and run to create a JPEG image file named PieChart3D.jpeg having the following 3D Pie Chart − A 3D Bar chart is same as the bar chart additionally with a nice 3D effect. A 3D effect can achieved by adding a little extra code, which will take care of creating 3D effect in a bar chart. Consider the following example that depicts various car statistics with the help of a 3D bar chart. Following is a list of car brands along with their different characteristics, which we will show using a bar chart − The following code creates 3D Bar Chart from the above given information. This code helps you to embed a bar chart in any AWT based application. import java.io.*; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.chart.ChartUtilities; public class BarChart3D { public static void main( String[ ] args )throws Exception { final String fait = "FAIT"; final String audi = "AUDI"; final String ford = "FORD"; final String speed = "Speed"; final String popular = "Popular"; final String mailage = "Mailage"; final String userrating = "User Rating"; final String safety = "safety"; final DefaultCategoryDataset dataset = new DefaultCategoryDataset( ); dataset.addValue( 1.0 , fait , speed ); dataset.addValue( 4.0 , fait , popular ); dataset.addValue( 3.0 , fait , userrating ); dataset.addValue( 5.0 , fait , mailage ); dataset.addValue( 5.0 , fait , safety ); dataset.addValue( 5.0 , audi , speed ); dataset.addValue( 7.0 , audi , popular ); dataset.addValue( 6.0 , audi , userrating ); dataset.addValue( 10.0 , audi , mailage ); dataset.addValue( 4.0 , audi , safety ); dataset.addValue( 4.0 , ford , speed ); dataset.addValue( 3.0 , ford , popular ); dataset.addValue( 2.0 , ford , userrating ); dataset.addValue( 3.0 , ford , mailage ); dataset.addValue( 6.0 , ford , safety ); JFreeChart barChart = ChartFactory.createBarChart3D( "Car Usage Statistics", "Category", "Score", dataset, PlotOrientation.VERTICAL, true, true, false); int width = 640; /* Width of the image */ int height = 480; /* Height of the image */ File barChart3D = new File( "barChart3D.jpeg" ); ChartUtilities.saveChartAsJPEG( barChart3D, barChart, width, height); } } Let us keep the above Java code in BarChart3D.java file, and then compile and run it from the command prompted as − $javac BarChart3D.java $java BarChart3 If everything is fine with your environment, it will compile and run to create a JPEG image file BarChart3D.jpeg having the following 3D Bar Chart − This chapter demonstrates how you can use JFreeChart to create Bubble Chart from a given set of business data. A bubble chart displays information in three-dimensional way. A bubble is plotted at the place where (x, y) coordinate intersect. The size of the bubble is considered as range or quantity of X and Y axis. Let us consider different persons along with their age, weight, and work capacities. The wok capacity can be treated as number of hours that is plotted as bubbles in the chart. Following is the code to create Bubble Chart from the above given information. This code helps you to embed a Bubble chart in any AWT based application. import java.awt.Color; import java.awt.Dimension; import javax.swing.JPanel; import org.jfree.chart.*; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.data.xy.DefaultXYZDataset; import org.jfree.data.xy.XYZDataset; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; public class BubbleChart_AWT extends ApplicationFrame { public BubbleChart_AWT( String s ) { super( s ); JPanel jpanel = createDemoPanel( ); jpanel.setPreferredSize(new Dimension( 560 , 370 ) ); setContentPane( jpanel ); } private static JFreeChart createChart( XYZDataset xyzdataset ) { JFreeChart jfreechart = ChartFactory.createBubbleChart( "AGE vs WEIGHT vs WORK", "Weight", "AGE", xyzdataset, PlotOrientation.HORIZONTAL, true, true, false); XYPlot xyplot = ( XYPlot )jfreechart.getPlot( ); xyplot.setForegroundAlpha( 0.65F ); XYItemRenderer xyitemrenderer = xyplot.getRenderer( ); xyitemrenderer.setSeriesPaint( 0 , Color.blue ); NumberAxis numberaxis = ( NumberAxis )xyplot.getDomainAxis( ); numberaxis.setLowerMargin( 0.2 ); numberaxis.setUpperMargin( 0.5 ); NumberAxis numberaxis1 = ( NumberAxis )xyplot.getRangeAxis( ); numberaxis1.setLowerMargin( 0.8 ); numberaxis1.setUpperMargin( 0.9 ); return jfreechart; } public static XYZDataset createDataset( ) { DefaultXYZDataset defaultxyzdataset = new DefaultXYZDataset(); double ad[ ] = { 30 , 40 , 50 , 60 , 70 , 80 }; double ad1[ ] = { 10 , 20 , 30 , 40 , 50 , 60 }; double ad2[ ] = { 4 , 5 , 10 , 8 , 9 , 6 }; double ad3[][] = { ad , ad1 , ad2 }; defaultxyzdataset.addSeries( "Series 1" , ad3 ); return defaultxyzdataset; } public static JPanel createDemoPanel( ) { JFreeChart jfreechart = createChart( createDataset( ) ); ChartPanel chartpanel = new ChartPanel( jfreechart ); chartpanel.setDomainZoomable( true ); chartpanel.setRangeZoomable( true ); return chartpanel; } public static void main( String args[ ] ) { BubbleChart_AWT bubblechart = new BubbleChart_AWT( "Bubble Chart_frame" ); bubblechart.pack( ); RefineryUtilities.centerFrameOnScreen( bubblechart ); bubblechart.setVisible( true ); } } Let us keep the above Java code in BubbleChart_AWT.java file, and then compile and run it from the command prompted as − $javac BubbleChart_AWT.java $java BubbleChart_AW If everything is fine, it will compile and run to generate the following Bubble Graph − Let us re-write the above example to generate a JPEG image from a command line. import java.io.*; import java.awt.Color; import org.jfree.chart.*; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.data.xy.DefaultXYZDataset; import org.jfree.chart.ChartUtilities; public class BubbleChart_image { public static void main( String args[ ] )throws Exception { DefaultXYZDataset defaultxyzdataset = new DefaultXYZDataset( ); double ad[ ] = { 30 , 40 , 50 , 60 , 70 , 80 }; double ad1[ ] = { 10 , 20 , 30 , 40 , 50 , 60 }; double ad2[ ] = { 4 , 5 , 10 , 8 , 9 , 6 }; double ad3[ ][ ] = { ad , ad1 , ad2 }; defaultxyzdataset.addSeries( "Series 1" , ad3 ); JFreeChart jfreechart = ChartFactory.createBubbleChart( "AGE vs WEIGHT vs WORK", "Weight", "AGE", defaultxyzdataset, PlotOrientation.HORIZONTAL, true, true, false); XYPlot xyplot = ( XYPlot )jfreechart.getPlot( ); xyplot.setForegroundAlpha( 0.65F ); XYItemRenderer xyitemrenderer = xyplot.getRenderer( ); xyitemrenderer.setSeriesPaint( 0 , Color.blue ); NumberAxis numberaxis = ( NumberAxis )xyplot.getDomainAxis( ); numberaxis.setLowerMargin( 0.2 ); numberaxis.setUpperMargin( 0.5 ); NumberAxis numberaxis1 = ( NumberAxis )xyplot.getRangeAxis( ); numberaxis1.setLowerMargin( 0.8 ); numberaxis1.setUpperMargin( 0.9 ); int width = 560; /* Width of the image */ int height = 370; /* Height of the image */ File bubbleChart = new File("BubbleChart.jpeg"); ChartUtilities.saveChartAsJPEG(bubbleChart,jfreechart,width,height); } } Let us keep the above Java code in BubbleChart_image.java file, and then compile and run it from the command prompted as − $javac BubbleChart_image.java $java BubbleChart_image If everything is fine, it will compile and run to create a JPEG image file named BubbleChart.jpeg in your current directory. A time series chart displays sequence of data points, which varies at equal intervals of time. This chapter demonstrates — how we can use JFreeChart to create Time Series Chart from a given set of business data. Let us consider various random numbers generated by using standard Java API Math.random(). We use these numbers to generate a Time Series Chart. You can generate similar chart for total number of errors occurring in your website at a given interval of time. Following is the code to create Time Series Chart from the numbers generated by Math.random() at a given time internal. import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.data.general.SeriesException; import org.jfree.data.time.Second; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.xy.XYDataset; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; public class TimeSeries_AWT extends ApplicationFrame { public TimeSeries_AWT( final String title ) { super( title ); final XYDataset dataset = createDataset( ); final JFreeChart chart = createChart( dataset ); final ChartPanel chartPanel = new ChartPanel( chart ); chartPanel.setPreferredSize( new java.awt.Dimension( 560 , 370 ) ); chartPanel.setMouseZoomable( true , false ); setContentPane( chartPanel ); } private XYDataset createDataset( ) { final TimeSeries series = new TimeSeries( "Random Data" ); Second current = new Second( ); double value = 100.0; for (int i = 0; i < 4000; i++) { try { value = value + Math.random( ) - 0.5; series.add(current, new Double( value ) ); current = ( Second ) current.next( ); } catch ( SeriesException e ) { System.err.println("Error adding to series"); } } return new TimeSeriesCollection(series); } private JFreeChart createChart( final XYDataset dataset ) { return ChartFactory.createTimeSeriesChart( "Computing Test", "Seconds", "Value", dataset, false, false, false); } public static void main( final String[ ] args ) { final String title = "Time Series Management"; final TimeSeries_AWT demo = new TimeSeries_AWT( title ); demo.pack( ); RefineryUtilities.positionFrameRandomly( demo ); demo.setVisible( true ); } } Let us keep the above Java code in TimeSeries_AWT.java file, and then compile and run it from the command prompted as − $javac TimeSeries_AWT.java $java TImeSeries_AWT If everything is fine, it will compile and run to generate the following Time Series Graph − Let us re-write the above example to generate a JPEG image from a command line. import java.io.*; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.data.general.SeriesException; import org.jfree.data.time.Second; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.xy.XYDataset; import org.jfree.chart.ChartUtilities; public class TimeSeriesChart { public static void main( final String[ ] args )throws Exception { final TimeSeries series = new TimeSeries( "Random Data" ); Second current = new Second(); double value = 100.0; for ( int i = 0 ; i < 4000 ; i++ ) { try { value = value + Math.random( ) - 0.5; series.add( current , new Double( value ) ); current = ( Second ) current.next( ); } catch ( SeriesException e ) { System.err.println( "Error adding to series" ); } } final XYDataset dataset=( XYDataset )new TimeSeriesCollection(series); JFreeChart timechart = ChartFactory.createTimeSeriesChart( "Computing Test", "Seconds", "Value", dataset, false, false, false); int width = 560; /* Width of the image */ int height = 370; /* Height of the image */ File timeChart = new File( "TimeChart.jpeg" ); ChartUtilities.saveChartAsJPEG( timeChart, timechart, width, height ); } } Let us keep the above Java code in TimeSeriesChart.java file, and then compile and run it from the command prompted as − $javac TimeSeriesChart.java $java TimeSeriesChart If everything is fine with your environment, it will compile and run to create a JPEG image file TimeChart.jpeg file in your current directory. So far we studied how to create various types of charts using JFreeChart APIs using static data. But in production environment, data is provided in the form of text file with a predefined format, or it comes directly from the database. This chapter will explain — how we can read a simple data from a given text file from a given location and then use JFreeChart to create a chart of your choice. Consider we have a file named mobile.txt, having different mobile brands and their sale (units per day) separated by a simple comma (,) − Iphone 5S, 20 Samsung Grand, 20 MOTO G, 40 Nokia Lumia, 10 Following is the code to create a Pie Chart based on the information provided in mobile.txt − import java.io.*; import java.util.StringTokenizer; import org.jfree.chart.ChartUtilities; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.data.general.DefaultPieDataset; public class PieChart_File { public static void main( String[ ] args )throws Exception { String mobilebrands[ ] = { "IPhone 5s" , "SamSung Grand" , "MotoG" , "Nokia Lumia" }; InputStream in = new FileInputStream( new File( "C:/temp/test.txt" ) ); BufferedReader reader = new BufferedReader(new InputStreamReader(in ) ); StringBuilder out = new StringBuilder(); String line; DefaultPieDataset dataset = new DefaultPieDataset(); while (( line = reader.readLine() ) != null ) { out.append( line ); } StringTokenizer s = new StringTokenizer( out.toString(), "," ); int i = 0; while( s.hasMoreTokens( ) && ( mobilebrands [i] != null ) ) { dataset.setValue(mobilebrands[i], Double.parseDouble( s.nextToken( ) )); i++; } JFreeChart chart = ChartFactory.createPieChart( "Mobile Sales", // chart title dataset, // data true, // include legend true, false); int width = 560; /* Width of the image */ int height = 370; /* Height of the image */ File pieChart = new File( "pie_Chart.jpeg" ); ChartUtilities.saveChartAsJPEG( pieChart, chart, width, height); } } Let us keep the above Java code in PieChart_File.java file, and then compile and run it from the command prompted as − $javac PieChart_File.java $java PieChart_File If everything is fine, it will compile and run to create a JPEG image file named PieChart.jpeg that contains the following chart. This chapter explains how you can read simple data from a database table and then use JFreeChart to create a chart of your choice. Consider we have the following MySQL table mobile_tbl(mobile_brand VARCHAR(100) NOT NULL, unit_sale INT NO NULL); Consider this table is having the following records − Following is the code to create a Pie Chart based on the information provided in mobile_tbl table available in test_db in a MySQL database. Based on your requirements, you can use any other database. import java.io.*; import java.sql.*; import org.jfree.chart.ChartUtilities; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.data.general.DefaultPieDataset; public class PieChart_DB { public static void main( String[ ] args )throws Exception { String mobilebrands[] = { "IPhone 5s", "SamSung Grand", "MotoG", "Nokia Lumia" }; /* Create MySQL Database Connection */ Class.forName( "com.mysql.jdbc.Driver" ); Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/jf_testdb" , "root", "root123"); Statement statement = connect.createStatement( ); ResultSet resultSet = statement.executeQuery("select * from mobile_data" ); DefaultPieDataset dataset = new DefaultPieDataset( ); while( resultSet.next( ) ) { dataset.setValue( resultSet.getString( "mobile_brand" ) , Double.parseDouble( resultSet.getString( "unit_sale" ))); } JFreeChart chart = ChartFactory.createPieChart( "Mobile Sales", // chart title dataset, // data true, // include legend true, false ); int width = 560; /* Width of the image */ int height = 370; /* Height of the image */ File pieChart = new File( "Pie_Chart.jpeg" ); ChartUtilities.saveChartAsJPEG( pieChart , chart , width , height ); } } Let us keep the above Java code in PieChart_DB.java file, and then compile and run it from the command prompted as − $javac PieChart_DB.java $java PieChart_DB If everything is fine, it will compile and run to create a JPEG image file named Pie_Chart.jpeg having the following chart. Print Add Notes Bookmark this page
[ { "code": null, "e": 2230, "s": 1941, "text": "A chart is a graphical representation of information. There are various tools available, which can be used to create different types of charts. The JFreeChart project was founded in February 2000, by David Gilbert. Today, it is the most widely used charting library among Java developers." }, { "code": null, "e": 2424, "s": 2230, "text": "This tutorial will help you understand what exactly JFreeChart is, why is it required, and the various ways to create different types of charts within a Java-based application or independently." }, { "code": null, "e": 2700, "s": 2424, "text": "JfreeChart is an open source library developed in Java. It can be used within Java based applications to create a wide range of charts. By using JFreeChart, we can create all the major type of 2D and 3D charts such as pie chart, bar chart, line chart, XY chart and 3D charts." }, { "code": null, "e": 2893, "s": 2700, "text": "JFreeChart is open source and 100% free, which permits usage in the commercial applications without any cost. We have enlisted here some more points in favor of why you should use JFreeChart −" }, { "code": null, "e": 2970, "s": 2893, "text": "It comes with well documented APIs, which makes it quite easy to understand." }, { "code": null, "e": 3047, "s": 2970, "text": "It comes with well documented APIs, which makes it quite easy to understand." }, { "code": null, "e": 3155, "s": 3047, "text": "It supports a wide range of chart types such as Pie Chart, Line Chart, Bar Chart, Area Chart and 3D charts." }, { "code": null, "e": 3263, "s": 3155, "text": "It supports a wide range of chart types such as Pie Chart, Line Chart, Bar Chart, Area Chart and 3D charts." }, { "code": null, "e": 3375, "s": 3263, "text": "JFreeChart is easy to extend and can be used in both, the client-side, as well as the server-side applications." }, { "code": null, "e": 3487, "s": 3375, "text": "JFreeChart is easy to extend and can be used in both, the client-side, as well as the server-side applications." }, { "code": null, "e": 3553, "s": 3487, "text": "It supports multiple output formats like PNG, JPEG, PDF, SVG etc." }, { "code": null, "e": 3619, "s": 3553, "text": "It supports multiple output formats like PNG, JPEG, PDF, SVG etc." }, { "code": null, "e": 3665, "s": 3619, "text": "It allows extensive customizations of charts." }, { "code": null, "e": 3711, "s": 3665, "text": "It allows extensive customizations of charts." }, { "code": null, "e": 3972, "s": 3711, "text": "Consider a situation where you are developing an application and you need to show the data in the form of charts, and the data itself is populated dynamically. In such case, displaying the data in the form of charts using JFreeChart programming is very simple." }, { "code": null, "e": 4206, "s": 3972, "text": "JFreeChart is popular for its efficient chart creation and user-friendly installation setup. This chapter describes the process of setting up JFreeChart on Windows and Linux. User administration is needed while installing JFreeChart." }, { "code": null, "e": 4268, "s": 4206, "text": "To install JFreeChart, there are three following steps viz..." }, { "code": null, "e": 4355, "s": 4268, "text": "To verify Java installation, open the console and execute the following java command −" }, { "code": null, "e": 4470, "s": 4355, "text": "Once Java installation is done properly, then you should get the following output for both the operating systems −" }, { "code": null, "e": 4478, "s": 4470, "text": "Windows" }, { "code": null, "e": 4620, "s": 4478, "text": "Java version \"1.7.0_60\" Java (TM) SE Run Time Environment (build 1.7.0_60-b19) Java HotSpot(TM) 64-bit Server VM (build 24.60-b09,mixed mode)" }, { "code": null, "e": 4626, "s": 4620, "text": "Linux" }, { "code": null, "e": 4760, "s": 4626, "text": "java version \"1.7.0_25\" OpenJDK Runtime Environment (rhel2.3.10.4.el6_4-x86_64) OpenJDK 64-Bit Server VM (build 23.7-b01, mixed mode)" }, { "code": null, "e": 4864, "s": 4760, "text": "If you do not have Java installed, then install the Java Software Development Kit (SDK) from the link −" }, { "code": null, "e": 4932, "s": 4864, "text": "https://www.oracle.com/technetwork/java/javase/downloads/index.html" }, { "code": null, "e": 5025, "s": 4932, "text": "We assume that you have installed Java 1.7.0_60 version before proceeding for this tutorial." }, { "code": null, "e": 5158, "s": 5025, "text": "Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example," }, { "code": null, "e": 5166, "s": 5158, "text": "Windows" }, { "code": null, "e": 5239, "s": 5166, "text": "Set Environmental variable JAVA_HOME to C:\\ProgramFiles\\java\\jdk1.7.0_60" }, { "code": null, "e": 5245, "s": 5239, "text": "Linux" }, { "code": null, "e": 5286, "s": 5245, "text": "export JAVA_HOME=/usr/local/java-current" }, { "code": null, "e": 5332, "s": 5286, "text": "Append Java compiler location to System Path." }, { "code": null, "e": 5340, "s": 5332, "text": "Windows" }, { "code": null, "e": 5437, "s": 5340, "text": "Append the String; C:\\Program Files\\Java\\jdk1.7.0_60\\bin to the end of the system variable PATH." }, { "code": null, "e": 5443, "s": 5437, "text": "Linux" }, { "code": null, "e": 5477, "s": 5443, "text": "export PATH=$PATH:$JAVA_HOME/bin/" }, { "code": null, "e": 5556, "s": 5477, "text": "Verify the command java -version from the command prompted as explained above." }, { "code": null, "e": 5839, "s": 5556, "text": "Download the latest version of JFreeChart.zip from the link http://www.jfree.org/jfreechart/download/ Unzip the downloaded file at any location from where required libraries can be linked into your Java program. The following image shows the structure of the directories and files −" }, { "code": null, "e": 5945, "s": 5839, "text": "Add complete path of jfreechart-1.0.18.jar and jcommon-1.0.22.jar files to the CLASSPATH as shown below −" }, { "code": null, "e": 5953, "s": 5945, "text": "Windows" }, { "code": null, "e": 6117, "s": 5953, "text": "Append the Strings “C:\\ jfreechart-1.0.18\\lib\\ jfreechart-1.0.18.jar” and “C:\\ jfreechart-1.0.18\\lib\\ jcommon-1.0.22.jar” to the end of the user variable CLASSPATH" }, { "code": null, "e": 6123, "s": 6117, "text": "Linux" }, { "code": null, "e": 6258, "s": 6123, "text": "Export CLASSPATH=$CLASSPATH: /usr/share/jfreechart1.0.18/lib/jfreechart-1.0.18.jar: /usr/share/jfreechart-1.0.18/lib/jcommon1.0.22.jar" }, { "code": null, "e": 6381, "s": 6258, "text": "Note − Inorder to communicate with MySql database you need to set the classpath to mysql-connector-java-5.0.8-bin.jar too." }, { "code": null, "e": 6593, "s": 6381, "text": "This chapter explains basic class level and application level architectures of JFreeChart to give you an idea about how JFreeChart interacts with different classes and how it fits in your Java based application." }, { "code": null, "e": 6728, "s": 6593, "text": "The class level architecture explains how various classes from the library interact with each other to create various types of charts." }, { "code": null, "e": 6799, "s": 6728, "text": "Following is the detail of the units used in the above block diagram −" }, { "code": null, "e": 6804, "s": 6799, "text": "File" }, { "code": null, "e": 6880, "s": 6804, "text": "The source having user input to be used for creating a dataset in the file." }, { "code": null, "e": 6889, "s": 6880, "text": "Database" }, { "code": null, "e": 6969, "s": 6889, "text": "The source having user input to be used for creating a dataset in the database." }, { "code": null, "e": 6984, "s": 6969, "text": "Create Dataset" }, { "code": null, "e": 7048, "s": 6984, "text": "Accepts the dataset and stores the dataset into dataset object." }, { "code": null, "e": 7064, "s": 7048, "text": "General Dataset" }, { "code": null, "e": 7116, "s": 7064, "text": "This type of dataset is mainly used for pie charts." }, { "code": null, "e": 7133, "s": 7116, "text": "Category Dataset" }, { "code": null, "e": 7193, "s": 7133, "text": "This type of dataset is used for bar chart, line chart,etc." }, { "code": null, "e": 7208, "s": 7193, "text": "Series Dataset" }, { "code": null, "e": 7291, "s": 7208, "text": "This type of dataset is used for storing series of data and construct line charts." }, { "code": null, "e": 7317, "s": 7291, "text": "Series Collection Dataset" }, { "code": null, "e": 7449, "s": 7317, "text": "The different categories of series datasets are added to series collection dataset. This type of dataset is used for XYLine Charts." }, { "code": null, "e": 7462, "s": 7449, "text": "Create Chart" }, { "code": null, "e": 7522, "s": 7462, "text": "This is the method which is executed to create final chart." }, { "code": null, "e": 7534, "s": 7522, "text": "Frame/Image" }, { "code": null, "e": 7598, "s": 7534, "text": "The chart is displayed on a Swing Frame or an image is created." }, { "code": null, "e": 7699, "s": 7598, "text": "The application level architecture explains where JFreeChart library sits inside a Java Application." }, { "code": null, "e": 7978, "s": 7699, "text": "The client program receives user data and then it uses standard Java and JFreeChart APIs based on requirements to generate the output in the form of either a frame, which can be displayed directly inside the application or independently in the image formats such as JPEG or PNG." }, { "code": null, "e": 8222, "s": 7978, "text": "In this chapter, we will discuss about some of the important packages, classes, and methods from JFreeChart library. These packages, classes, and methods are the most frequently used while creating a variety of charts using JFreeChart library." }, { "code": null, "e": 8367, "s": 8222, "text": "ChartFactory is an abstract class under the org.jfree.chart package. It provides a collection of utility methods for generating standard charts." }, { "code": null, "e": 8421, "s": 8367, "text": "Following is a list of few of the important methods −" }, { "code": null, "e": 8436, "s": 8421, "text": "ChartFactory()" }, { "code": null, "e": 8479, "s": 8436, "text": "Default constructor of ChartFactory class." }, { "code": null, "e": 8586, "s": 8479, "text": "createPieChart(java.lang.String title, PieDataset dataset, boolean legend, boolean tooltips, boolean urls)" }, { "code": null, "e": 8676, "s": 8586, "text": "This method creates a pie chart with default settings. It returns JfreeChart type object." }, { "code": null, "e": 8784, "s": 8676, "text": "createPieChart3D(java.lang.String title, PieDataset dataset, boolean legend, boolean tooltips, boolean urls" }, { "code": null, "e": 8848, "s": 8784, "text": "This method creates a 3D pie chart using the specified dataset." }, { "code": null, "e": 9058, "s": 8848, "text": "createBarChart(java.lang.String title, java.lang.String categoryAxisLabel, java.lang.String valueAxisLabel, CategoryDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls)" }, { "code": null, "e": 9235, "s": 9058, "text": "The argument java.lang.String categoryAxisLabel is the label for values placed on X-axis. The argument java.lang.String valueAxisLabel is the label for values placed on Y-axis." }, { "code": null, "e": 9268, "s": 9235, "text": "This method creates a bar chart." }, { "code": null, "e": 9480, "s": 9268, "text": "createBarChart3D(java.lang.String title, java.lang.String categoryAxisLabel, java.lang.String valueAxisLabel, CategoryDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls)" }, { "code": null, "e": 9565, "s": 9480, "text": "This Method Creates a bar chart with a 3D effect. It returns JfreeChart type object." }, { "code": null, "e": 9776, "s": 9565, "text": "createLineChart(java.lang.String title, java.lang.String categoryAxisLabel, java.lang.String valueAxisLabel, CategoryDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls)" }, { "code": null, "e": 9832, "s": 9776, "text": "This method creates a line chart with default settings." }, { "code": null, "e": 10045, "s": 9832, "text": "createLineChart3D(java.lang.String title, java.lang.String categoryAxisLabel, java.lang.String valueAxisLabel, CategoryDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls)" }, { "code": null, "e": 10094, "s": 10045, "text": "This method creates a line chart with 3D effect." }, { "code": null, "e": 10290, "s": 10094, "text": "createXYLineChart(java.lang.String title, java.lang.String xAxisLabel, java.lang.String yAxisLabel, XYDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls)" }, { "code": null, "e": 10365, "s": 10290, "text": "This method creates a line chart based on XYDataset with default settings." }, { "code": null, "e": 10588, "s": 10365, "text": "ChartFrame class under the org.jfree.chart package, provides all frame related functions and utilities. ChartFrame class inherits functionalities from parent classes such as Frame, Window, Container, and Component classes." }, { "code": null, "e": 10642, "s": 10588, "text": "ChartFrame (java.lang.Frame String, JfreeChart chart)" }, { "code": null, "e": 10665, "s": 10642, "text": "It constructs a frame." }, { "code": null, "e": 10740, "s": 10665, "text": "Chart Frame (java.lang.Frame String, JfreeChart chart, boolean scrollpane)" }, { "code": null, "e": 10763, "s": 10740, "text": "It constructs a frame." }, { "code": null, "e": 10779, "s": 10763, "text": "getChartPanel()" }, { "code": null, "e": 10828, "s": 10779, "text": "This method returns the chart panel for a frame." }, { "code": null, "e": 10945, "s": 10828, "text": "ChartPanel class from the org.jfree.chart package is used as a swing GUI component for displaying JfreeChart object." }, { "code": null, "e": 10974, "s": 10945, "text": "ChartPanel(JFreeChart chart)" }, { "code": null, "e": 11045, "s": 10974, "text": "This constructor constructs a panel that displays the specified chart." }, { "code": null, "e": 11093, "s": 11045, "text": "ChartPanel(JFreeChart chart, boolean useBuffer)" }, { "code": null, "e": 11149, "s": 11093, "text": "This constructor constructs a panel containing a chart." }, { "code": null, "e": 11259, "s": 11149, "text": "ChartPanel(JFreeChart chart, boolean properties, boolean save, boolean print, boolean zoom, boolean tooltips)" }, { "code": null, "e": 11307, "s": 11259, "text": "This constructor constructs a JFreeChart panel." }, { "code": null, "e": 11344, "s": 11307, "text": "setPreferredSize(java.awt.Dimension)" }, { "code": null, "e": 11491, "s": 11344, "text": "This method is used to set the frame size using java.awt. Dimension class object as an argument. This method is taken from javax.swing.JComponent." }, { "code": null, "e": 11711, "s": 11491, "text": "CharUtilites class from the org.jfree.chart package provides a collection of utility methods of JFreeCharts including methods for converting charts into image file format such as PNG, JPEG, and creating HTML image maps." }, { "code": null, "e": 11728, "s": 11711, "text": "ChartUtilities()" }, { "code": null, "e": 11769, "s": 11728, "text": "This is a default constructor of a class" }, { "code": null, "e": 11844, "s": 11769, "text": "saveChartAsPNG(java.io.File file, JfreeChart chart, int width, int height)" }, { "code": null, "e": 11920, "s": 11844, "text": "This method converts and saves a chart to the specified file in PNG format." }, { "code": null, "e": 11996, "s": 11920, "text": "saveChartAsJPEG(java.io.File file, JfreeChart chart, int width, int height)" }, { "code": null, "e": 12073, "s": 11996, "text": "This method converts and saves a chart to the specified file in JPEG format." }, { "code": null, "e": 12269, "s": 12073, "text": "JFreeChart class is the core class under the org.jfree.chart package. This class provides JFreeChart method to create bar charts, line charts, pie charts, and xy plots including time series data." }, { "code": null, "e": 12291, "s": 12269, "text": "JfreeChart(Plot plot)" }, { "code": null, "e": 12356, "s": 12291, "text": "This constructor creates a new chart based on the supplied plot." }, { "code": null, "e": 12449, "s": 12356, "text": "JfreeChart(java.lang.String title, java.awt.Font titleFont, Plot plot, boolean createLegend)" }, { "code": null, "e": 12517, "s": 12449, "text": "This constructor creates a new chart with the given title and plot." }, { "code": null, "e": 12563, "s": 12517, "text": "JfreeChart(java.lang.String title, Plot plot)" }, { "code": null, "e": 12631, "s": 12563, "text": "This constructor creates a new chart with the given title and plot." }, { "code": null, "e": 12643, "s": 12631, "text": "getXYPlot()" }, { "code": null, "e": 12751, "s": 12643, "text": "This method Returns the plot chart as XYPlot. Using XYPolt, we can do some utility operations on xy charts." }, { "code": null, "e": 12899, "s": 12751, "text": "This class is a part of org.jfree.chart.plot package and extends Plot class from the same package. This class provides methods to create Pie Plots." }, { "code": null, "e": 12909, "s": 12899, "text": "PiePlot()" }, { "code": null, "e": 12932, "s": 12909, "text": "It creates a new plot." }, { "code": null, "e": 12960, "s": 12932, "text": "PiePlot(PieDataset dataset)" }, { "code": null, "e": 13028, "s": 12960, "text": "It creates a plot that draws a pie chart for the specified dataset." }, { "code": null, "e": 13056, "s": 13028, "text": "setStartAngle(double angle)" }, { "code": null, "e": 13148, "s": 13056, "text": "This Method sets the starting angle and sends a PlotChangeEvent to all registered listeners" }, { "code": null, "e": 13315, "s": 13148, "text": "PiePlot3D class is a subclass of PiePlot class under the same package. Hence, this class has the same features as PiePlot class, except it is used to create 3D plots." }, { "code": null, "e": 13327, "s": 13315, "text": "PiePlot3D()" }, { "code": null, "e": 13384, "s": 13327, "text": "This constructor creates a new instance with no dataset." }, { "code": null, "e": 13414, "s": 13384, "text": "PiePlot3D(PieDataset dataset)" }, { "code": null, "e": 13508, "s": 13414, "text": "This constructor creates a pie chart with three dimensional effect using a specified dataset." }, { "code": null, "e": 13540, "s": 13508, "text": "setForegroundAlpha(float alpha)" }, { "code": null, "e": 13692, "s": 13540, "text": "It sets the alpha-transparency for the plot and sends a PlotChangeEvent to all registered listeners. This is taken from one of the parent Plot classes." }, { "code": null, "e": 13723, "s": 13692, "text": "setInteriorGap(double percent)" }, { "code": null, "e": 13993, "s": 13723, "text": "It sets the interior gap and sends a PlotChangeEvent to all registered listeners. This controls the space between the edges of the pie plot and the plot area itself (i. e., the region where the section labels appear). This method is taken from the parent class PiePlot." }, { "code": null, "e": 14248, "s": 13993, "text": "This is a serialized class available in org.jfree.chart.plot package and it is used to show the orientation of a 2D plot. The orientation can either be vertical or horizontal. It sets the orientation of Y-axis. A conventional plot has a vertical Y- axis." }, { "code": null, "e": 14263, "s": 14248, "text": "isHorizontal()" }, { "code": null, "e": 14344, "s": 14263, "text": "This method returns true if this orientation is HORIZONTAL, and false otherwise." }, { "code": null, "e": 14357, "s": 14344, "text": "isVertical()" }, { "code": null, "e": 14436, "s": 14357, "text": "This Method returns true if this orientation is VERTICAL, and false otherwise." }, { "code": null, "e": 14721, "s": 14436, "text": "This is a general class available in org.jfree.chart.plot package and it is used for the plotting data in the form of (x,y) pairs. This plot can use data from any other class that implements the XYDataSet Interface. XYPlot makes use of a XYItemRenderer to draw each point on the plot." }, { "code": null, "e": 14730, "s": 14721, "text": "XYPlot()" }, { "code": null, "e": 14818, "s": 14730, "text": "This contractor creates a new XYPlot instance with no dataset, no axes and no renderer." }, { "code": null, "e": 14912, "s": 14818, "text": "XYPlot(XYDataset dataset, ValueAxis domainAxis, ValueAxis rangeAxis, XYItemRenderer renderer)" }, { "code": null, "e": 14996, "s": 14912, "text": "This constructor creates a new plot with the specified dataset, axis, and renderer." }, { "code": null, "e": 15033, "s": 14996, "text": "setRenderer(XYItemRenderer renderer)" }, { "code": null, "e": 15141, "s": 15033, "text": "This method sets the renderer for the primary dataset and sends a change event to all registered listeners." }, { "code": null, "e": 15436, "s": 15141, "text": "This class is available in org.jfree.chart.axis package and it can access the numerical data of any axis. When we set the range of any axis to default, it fits according to the range of the data. But using NumberAxis, class we can set the lower margin and upper margin of domain and range axes." }, { "code": null, "e": 15450, "s": 15436, "text": "NumberAxis( )" }, { "code": null, "e": 15495, "s": 15450, "text": "This is a default Constructor of NumberAxis." }, { "code": null, "e": 15531, "s": 15495, "text": "NumberAxis( java.lang.String label)" }, { "code": null, "e": 15595, "s": 15531, "text": "The constructor NumberAxis uses default values where necessary." }, { "code": null, "e": 15625, "s": 15595, "text": "setLowerMargin(double margin)" }, { "code": null, "e": 15820, "s": 15625, "text": "It sets the lower margin for the axis (as a percentage of the axis range) and sends an AxisChangeEvent to all registered listeners. This method is taken from parent class of the class ValueAxis." }, { "code": null, "e": 15850, "s": 15820, "text": "setUpperMargin(double margin)" }, { "code": null, "e": 16030, "s": 15850, "text": "It sets the upper margin for the axis (as a percentage of the axis range) and sends an AxisChangeEvent to all registered listeners. This method is also present in ValueAxis Class." }, { "code": null, "e": 16256, "s": 16030, "text": "This is the class, available under org.jfree.chart.renderer.xy package, which takes care of connecting data points with lines and draws shapes at each data point. This renderer class is designed for use with the XYPlot class." }, { "code": null, "e": 16281, "s": 16256, "text": "XYLineAndShapeRenderer()" }, { "code": null, "e": 16343, "s": 16281, "text": "It creates a new renderer with both lines and shapes visible." }, { "code": null, "e": 16398, "s": 16343, "text": "XYLineAndShapeRenderer (boolean lines, boolean shapes)" }, { "code": null, "e": 16448, "s": 16398, "text": "It creates a new renderer with specific property." }, { "code": null, "e": 16497, "s": 16448, "text": "setSeriesPaint(int series, java.awt.Paint paint)" }, { "code": null, "e": 16701, "s": 16497, "text": "This method sets the paint used for a series and sends a RendererChangeEvent to all registered listeners. This method is taken from AbstratRenderer abstract class from renderer package in JFreeChart API." }, { "code": null, "e": 16753, "s": 16701, "text": "setSeriesStroke(int series, java.awt.Stroke stroke)" }, { "code": null, "e": 16956, "s": 16753, "text": "This method Sets the stroke used for a series and sends a RendererChangeEvent to all registered listeners. This method is taken from AbstratRenderer abstract class, which is super class of this package." }, { "code": null, "e": 17170, "s": 16956, "text": "This is an interface for rendering the format of a single (x, y) item on a XYPlot. The package is org.Jfree.data.general, which has classes and interfaces to define different types of datasets to construct charts." }, { "code": null, "e": 17502, "s": 17170, "text": "This is an interface used as a general purpose dataset, where values are associated with keys. As the name suggests, you can use this dataset to supply data for pie charts. This interface extends KeyedValues and DataSet interfaces. All the methods used for this interface are taken from KeyedValues, Values, and Dataset interfaces." }, { "code": null, "e": 17568, "s": 17502, "text": "This is a Default implementation class of a PieDataset interface." }, { "code": null, "e": 17588, "s": 17568, "text": "DefaultPieDataset()" }, { "code": null, "e": 17645, "s": 17588, "text": "This constructor creates a new dataset, initially empty." }, { "code": null, "e": 17681, "s": 17645, "text": "DefaultPieDataset(KeyedValues data)" }, { "code": null, "e": 17751, "s": 17681, "text": "It creates a new dataset by copying data from a KeyedValues instance." }, { "code": null, "e": 17800, "s": 17751, "text": "setValue(java.lang.Comparable key, double value)" }, { "code": null, "e": 17893, "s": 17800, "text": "It sets the data value for a key and sends a DatasetChangeEvent to all registered listeners." }, { "code": null, "e": 17952, "s": 17893, "text": "setValue(java.lang.Comparable key, java.lang.Number value)" }, { "code": null, "e": 18045, "s": 17952, "text": "It sets the data value for a key and sends a DatasetChangeEvent to all registered listeners." }, { "code": null, "e": 18300, "s": 18045, "text": "This is an exception class. It raises an exception occurred in the time series of data in the dataset. Exceptions are raised on the occurrence of duplicate or invalid data. The time series must not be applied with duplicates and the format must be valid." }, { "code": null, "e": 18369, "s": 18300, "text": "This is a default implementation class of CategoryDataset interface." }, { "code": null, "e": 18394, "s": 18369, "text": "DefaultCategoryDataset()" }, { "code": null, "e": 18438, "s": 18394, "text": "This constructor creates new empty dataset." }, { "code": null, "e": 18522, "s": 18438, "text": "addValue(double value, java.lang.Comparable rowKey, java.lang.Comparable columnKey)" }, { "code": null, "e": 18583, "s": 18522, "text": "This method adds a value to the table using comparable keys." }, { "code": null, "e": 18677, "s": 18583, "text": "addValue(java.lang.Number value, java.lang.Comparable rowKey, java.lang.Comparable columnKey)" }, { "code": null, "e": 18716, "s": 18677, "text": "This method adds a value to the table." }, { "code": null, "e": 18800, "s": 18716, "text": "setValue(double value, java.lang.Comparable rowKey, java.lang.Comparable columnKey)" }, { "code": null, "e": 18909, "s": 18800, "text": "This method adds or updates a value in the table and sends a DatasetChangeEvent to all registered listeners." }, { "code": null, "e": 19003, "s": 18909, "text": "setValue(java.lang.Number value, java.lang.Comparable rowKey, java.lang.Comparable columnKey)" }, { "code": null, "e": 19112, "s": 19003, "text": "This method adds or updates a value in the table and sends a DatasetChangeEvent to all registered listeners." }, { "code": null, "e": 19191, "s": 19112, "text": "Refer JFreeChart API for more information on various other methods and fields." }, { "code": null, "e": 19361, "s": 19191, "text": "The series dataset is used by XY charts. The package is org.Jfree.data.xy, which contains classes and interfaces belonging to xy charts. The core interface is XYDataset." }, { "code": null, "e": 19589, "s": 19361, "text": "This is an interface through which data in the form of (x,y) items can be accessed. As the name suggests, you can use this dataset to serve XY chart. Some of the methods in this interface are taken from SeriesDateset interface." }, { "code": null, "e": 19810, "s": 19589, "text": "This is an interface through which data in the form of (x,y,z) items can be accessed. As the name suggests, you can use this dataset to serve XYZ chart. Some of the methods in this interface are taken from SeriesDateset." }, { "code": null, "e": 20156, "s": 19810, "text": "This is a class, which represents a sequence of zero or more data items in the form (x, y). By default, the items in the series are sorted into ascending order by x-value, and duplicate x-values are permitted. Both the sorting and duplicate defaults can be changed in the constructor. Y-values can be denoted as null to represent missing values." }, { "code": null, "e": 20191, "s": 20156, "text": "XYSeries(java.lang.Comparable key)" }, { "code": null, "e": 20236, "s": 20191, "text": "This constructor creates a new empty series." }, { "code": null, "e": 20289, "s": 20236, "text": "XYSeries(java.lang.Comparable key, boolean autoSort)" }, { "code": null, "e": 20399, "s": 20289, "text": "It constructs a new empty series, with the auto-sort flag set as requested, and duplicate values are allowed." }, { "code": null, "e": 20483, "s": 20399, "text": "XYSeries(java.lang.Comparable key, boolean autoSort, boolean allowDuplicateXValues)" }, { "code": null, "e": 20536, "s": 20483, "text": "It constructs a new xy-series that contains no data." }, { "code": null, "e": 20560, "s": 20536, "text": "add(double x, double y)" }, { "code": null, "e": 20604, "s": 20560, "text": "This method adds data item into the series." }, { "code": null, "e": 20738, "s": 20604, "text": "The above method is used in the tutorial example. If you want to learn the remaining methods and fields, please refer JFreeChart API." }, { "code": null, "e": 20947, "s": 20738, "text": "XYSeriesCollection class has parent classes like AbstractIntervelDataset, AbstractXYDatset, AbstractSeriesDataset and AbstractDataset. Some of the methods in this class belong to parent classes of this class." }, { "code": null, "e": 20968, "s": 20947, "text": "XYSeriesCollection()" }, { "code": null, "e": 21000, "s": 20968, "text": "It constructs an empty dataset." }, { "code": null, "e": 21038, "s": 21000, "text": "XYSeriesCollection(XYSeries xyseries)" }, { "code": null, "e": 21101, "s": 21038, "text": "It constructs a dataset and populates it with a single series." }, { "code": null, "e": 21128, "s": 21101, "text": "addSeries(XYSeries series)" }, { "code": null, "e": 21232, "s": 21128, "text": "This method adds a series to the collection and sends a DatasetChangeEvent to all registered listeners." }, { "code": null, "e": 21291, "s": 21232, "text": "Refer JFreeChart API for the remaining methods and fields." }, { "code": null, "e": 21520, "s": 21291, "text": "DefaultXYZDataset class have parent classes like AbstractIntervelDataset, AbstractXYDatset, AbstractSeriesDataset, AbstractDataset and AbstractXYZDataset. Some of the methods in this class belong to parent classes of this class." }, { "code": null, "e": 21540, "s": 21520, "text": "DefaultXYZDataset()" }, { "code": null, "e": 21572, "s": 21540, "text": "It constructs an empty dataset." }, { "code": null, "e": 21634, "s": 21572, "text": "addSeries(java.lang.Comparable seriesKey, double[ ][ ] data )" }, { "code": null, "e": 21738, "s": 21634, "text": "This method adds a series to the collection and sends a DatasetChangeEvent to all registered listeners." }, { "code": null, "e": 21804, "s": 21738, "text": "Please refer JFreeChart API for the remaining methods and fields." }, { "code": null, "e": 21928, "s": 21804, "text": "The package is org.jfree.data.time. This package contains classes and interfaces, which are used for the time related data." }, { "code": null, "e": 22124, "s": 21928, "text": "This class represents a sequence of data items in the form of period values, where period is some instance of RegularTimePeriod abstract class such as Time, Day, Hour, Minute, and Second classes." }, { "code": null, "e": 22162, "s": 22124, "text": "TimeSeries(java.lang.Comparable name)" }, { "code": null, "e": 22191, "s": 22162, "text": "It creates new empty series." }, { "code": null, "e": 22278, "s": 22191, "text": "TimeSeries(java.lang.Comarable name, java.lang.String domain, java.lang.Strin range) " }, { "code": null, "e": 22328, "s": 22278, "text": "It creates new time series that contains no data." }, { "code": null, "e": 22371, "s": 22328, "text": "add(RegularTimePeriod period,double value)" }, { "code": null, "e": 22419, "s": 22371, "text": "This method adds a new data item to the series." }, { "code": null, "e": 22478, "s": 22419, "text": "Refer JFreeChart API for the remaining methods and fields." }, { "code": null, "e": 22694, "s": 22478, "text": "This is a class used as a collection of time series objects. This class implements the XYDataset interface, as well as it extends IntervelXYDataset interface. This makes it convenient to collect series data objects." }, { "code": null, "e": 22717, "s": 22694, "text": "TimeSeriesCollection()" }, { "code": null, "e": 22780, "s": 22717, "text": "It constructs an empty dataset, tied to the default time zone." }, { "code": null, "e": 22820, "s": 22780, "text": "TimeSeriesCollection(TimeSeries series)" }, { "code": null, "e": 22923, "s": 22820, "text": "It constructs a dataset containing a single series (more can be added), tied to the default time zone." }, { "code": null, "e": 22988, "s": 22923, "text": "TimeSeriesCollection(TimeSeries series, java.util.TimeZone zone)" }, { "code": null, "e": 23091, "s": 22988, "text": " It constructs a dataset containing a single series (more can be added), tied to a specific time zone." }, { "code": null, "e": 23137, "s": 23091, "text": "TimeSeriesCollection(java.util.TimeZone zone)" }, { "code": null, "e": 23199, "s": 23137, "text": "It constructs an empty dataset, tied to a specific time zone." }, { "code": null, "e": 23228, "s": 23199, "text": "addSeries(TimeSeries series)" }, { "code": null, "e": 23332, "s": 23228, "text": "This method adds a series to the collection and sends a DatasetChangeEvent to all registered listeners." }, { "code": null, "e": 23398, "s": 23332, "text": "Please refer JFreeChart API for the remaining methods and fields." }, { "code": null, "e": 23534, "s": 23398, "text": "This class represents a second in a particular day. This class is immutable, which is a requirement for all RegularTimePeriod subclass." }, { "code": null, "e": 23543, "s": 23534, "text": "Second()" }, { "code": null, "e": 23602, "s": 23543, "text": "It constructs a new Second, based on the system date/time." }, { "code": null, "e": 23630, "s": 23602, "text": "Second(java.util.Date time)" }, { "code": null, "e": 23715, "s": 23630, "text": "It constructs a new instance from the specified date/time and the default time zone." }, { "code": null, "e": 23793, "s": 23715, "text": "Second(java.util.Date time, java.util.TimeZone zone, java.util.Locale locale)" }, { "code": null, "e": 23859, "s": 23793, "text": "It creates a new second based on the supplied time and time zone." }, { "code": null, "e": 23929, "s": 23859, "text": "Second(int second, int minute, int hour, int day, int month, int year" }, { "code": null, "e": 23954, "s": 23929, "text": "It creates a new second." }, { "code": null, "e": 23988, "s": 23954, "text": "Second(int second, Minute minute)" }, { "code": null, "e": 24016, "s": 23988, "text": "It constructs a new Second." }, { "code": null, "e": 24028, "s": 24016, "text": "getSecond()" }, { "code": null, "e": 24069, "s": 24028, "text": "It returns the second within the minute." }, { "code": null, "e": 24076, "s": 24069, "text": "next()" }, { "code": null, "e": 24128, "s": 24076, "text": "It returns the second following the present second." }, { "code": null, "e": 24194, "s": 24128, "text": "Please refer JFreeChart API for the remaining methods and fields." }, { "code": null, "e": 24362, "s": 24194, "text": "The package is org.jfree.ui. This is the package belongs to JCommons API of JFreeChart. It contains utility classes used for creating frames for pre-configured charts." }, { "code": null, "e": 24738, "s": 24362, "text": "This is a base class for creating the main frame for simple applications. The frame listens for window closing events, and responds by shutting down the JVM. This is fine for small demo applications. For enterprise applications, you need to use something more robust. The main core methods in this class are taken from Component, Container, Window, Frame, and Jframe classes." }, { "code": null, "e": 24779, "s": 24738, "text": "ApplicationFrame(java.lang.String title)" }, { "code": null, "e": 24834, "s": 24779, "text": "It creates an application frame with the string title." }, { "code": null, "e": 24960, "s": 24834, "text": "This class helps to create AWT Frames. This is the reason for why we use this class as super class in this tutorial examples." }, { "code": null, "e": 25139, "s": 24960, "text": "The methods, which are taken form the parent classes are used for opening a frame, closing a frame, changing the size, changing the background or foreground color, and listeners." }, { "code": null, "e": 25213, "s": 25139, "text": "This is a class collection of utility methods relating to user interface." }, { "code": null, "e": 25256, "s": 25213, "text": "centerFrameOnScreen(java.awt.Window frame)" }, { "code": null, "e": 25318, "s": 25256, "text": "It positions the specified frame in the middle of the screen." }, { "code": null, "e": 25423, "s": 25318, "text": "The above method is used in the tutorial example. Refer JFreeChart API for remaining methods and fields." }, { "code": null, "e": 25630, "s": 25423, "text": "In a pie chart, the arc length of each sector is proportional to the quantity that it represents. This chapter demonstrates — how we can use JFreeChart to create Pie Chart from a given set of business data." }, { "code": null, "e": 25781, "s": 25630, "text": "The following example depicts mobile sale with the help of a pie chart. Following is a list of different mobile brands and their sale (units per day)." }, { "code": null, "e": 25934, "s": 25781, "text": "Following is the code to create a Pie Chart by using the above given information. This code helps you to embed a pie chart in any AWT based application." }, { "code": null, "e": 27515, "s": 25934, "text": "import javax.swing.JPanel;\n\nimport org.jfree.chart.ChartFactory;\nimport org.jfree.chart.ChartPanel;\nimport org.jfree.chart.JFreeChart;\nimport org.jfree.data.general.DefaultPieDataset;\nimport org.jfree.data.general.PieDataset;\nimport org.jfree.ui.ApplicationFrame;\nimport org.jfree.ui.RefineryUtilities;\n \npublic class PieChart_AWT extends ApplicationFrame {\n \n public PieChart_AWT( String title ) {\n super( title ); \n setContentPane(createDemoPanel( ));\n }\n \n private static PieDataset createDataset( ) {\n DefaultPieDataset dataset = new DefaultPieDataset( );\n dataset.setValue( \"IPhone 5s\" , new Double( 20 ) ); \n dataset.setValue( \"SamSung Grand\" , new Double( 20 ) ); \n dataset.setValue( \"MotoG\" , new Double( 40 ) ); \n dataset.setValue( \"Nokia Lumia\" , new Double( 10 ) ); \n return dataset; \n }\n \n private static JFreeChart createChart( PieDataset dataset ) {\n JFreeChart chart = ChartFactory.createPieChart( \n \"Mobile Sales\", // chart title \n dataset, // data \n true, // include legend \n true, \n false);\n\n return chart;\n }\n \n public static JPanel createDemoPanel( ) {\n JFreeChart chart = createChart(createDataset( ) ); \n return new ChartPanel( chart ); \n }\n\n public static void main( String[ ] args ) {\n PieChart_AWT demo = new PieChart_AWT( \"Mobile Sales\" ); \n demo.setSize( 560 , 367 ); \n RefineryUtilities.centerFrameOnScreen( demo ); \n demo.setVisible( true ); \n }\n}" }, { "code": null, "e": 27633, "s": 27515, "text": "Let us keep the above Java code in PieChart_AWT.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 27680, "s": 27633, "text": "$javac PieChart_AWT.java \n$java PieChart_AWT\n" }, { "code": null, "e": 27765, "s": 27680, "text": "If everything is fine, it will compile and run to generate the following Pie Graph −" }, { "code": null, "e": 27949, "s": 27765, "text": "If you do not need to embed your chart in any application, then you can create chart images at command prompt. JFreeChart allows you to save chart images in either JPG or PNG formats." }, { "code": null, "e": 28168, "s": 27949, "text": "Let us re-write the above example to generate a JPEG image from a command line. Following are the two APIs provided by JFreeChart library, which you can use to generate either PNG or JPEG image as per your requirement." }, { "code": null, "e": 28220, "s": 28168, "text": "saveChartAsPNG() − API to save image in PNG format." }, { "code": null, "e": 28272, "s": 28220, "text": "saveChartAsPNG() − API to save image in PNG format." }, { "code": null, "e": 28326, "s": 28272, "text": "saveChartAsJPEG() − API to save image in JPEG format." }, { "code": null, "e": 28380, "s": 28326, "text": "saveChartAsJPEG() − API to save image in JPEG format." }, { "code": null, "e": 29393, "s": 28380, "text": "import java.io.*;\n\nimport org.jfree.chart.ChartUtilities;\nimport org.jfree.chart.ChartFactory;\nimport org.jfree.chart.JFreeChart;\nimport org.jfree.data.general.DefaultPieDataset;\n\npublic class PieChart {\n \n public static void main( String[ ] args ) throws Exception {\n DefaultPieDataset dataset = new DefaultPieDataset( );\n dataset.setValue(\"IPhone 5s\", new Double( 20 ) );\n dataset.setValue(\"SamSung Grand\", new Double( 20 ) );\n dataset.setValue(\"MotoG\", new Double( 40 ) );\n dataset.setValue(\"Nokia Lumia\", new Double( 10 ) );\n\n JFreeChart chart = ChartFactory.createPieChart(\n \"Mobile Sales\", // chart title\n dataset, // data\n true, // include legend\n true,\n false);\n \n int width = 640; /* Width of the image */\n int height = 480; /* Height of the image */ \n File pieChart = new File( \"PieChart.jpeg\" ); \n ChartUtilities.saveChartAsJPEG( pieChart , chart , width , height );\n }\n}" }, { "code": null, "e": 29507, "s": 29393, "text": "Let us keep the above Java code in PieChart.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 29546, "s": 29507, "text": "$javac PieChart.java \n$java PieChart\n" }, { "code": null, "e": 29668, "s": 29546, "text": "If everything is fine, it will compile and run to create a JPEG image file named PieChart.jpeg in your current directory." }, { "code": null, "e": 29776, "s": 29668, "text": "This chapter demonstrates how you can use JFreeChart to create Bar Chart from a given set of business data." }, { "code": null, "e": 30026, "s": 29776, "text": "A bar chart uses different orientation (horizontal or vertical) bars to show comparisons in various categories. One axis (domain axis) of the chart shows the specific domain being compared, and the other axis (range axis) represents discrete values." }, { "code": null, "e": 30226, "s": 30026, "text": "The following example depicts various car statistics with the help of a bar chart. Following is a list of car brands along with their different characteristics, which we will show using a bar chart −" }, { "code": null, "e": 30375, "s": 30226, "text": "Following is the code to create a Bar Chart from the above given information. This code helps you to embed a bar chart in any AWT based application." }, { "code": null, "e": 32786, "s": 30375, "text": "import org.jfree.chart.ChartFactory;\nimport org.jfree.chart.ChartPanel; \nimport org.jfree.chart.JFreeChart; \nimport org.jfree.chart.plot.PlotOrientation;\nimport org.jfree.data.category.CategoryDataset; \nimport org.jfree.data.category.DefaultCategoryDataset; \nimport org.jfree.ui.ApplicationFrame; \nimport org.jfree.ui.RefineryUtilities; \n\npublic class BarChart_AWT extends ApplicationFrame {\n \n public BarChart_AWT( String applicationTitle , String chartTitle ) {\n super( applicationTitle ); \n JFreeChart barChart = ChartFactory.createBarChart(\n chartTitle, \n \"Category\", \n \"Score\", \n createDataset(), \n PlotOrientation.VERTICAL, \n true, true, false);\n \n ChartPanel chartPanel = new ChartPanel( barChart ); \n chartPanel.setPreferredSize(new java.awt.Dimension( 560 , 367 ) ); \n setContentPane( chartPanel ); \n }\n \n private CategoryDataset createDataset( ) {\n final String fiat = \"FIAT\"; \n final String audi = \"AUDI\"; \n final String ford = \"FORD\"; \n final String speed = \"Speed\"; \n final String millage = \"Millage\"; \n final String userrating = \"User Rating\"; \n final String safety = \"safety\"; \n final DefaultCategoryDataset dataset = \n new DefaultCategoryDataset( ); \n\n dataset.addValue( 1.0 , fiat , speed ); \n dataset.addValue( 3.0 , fiat , userrating ); \n dataset.addValue( 5.0 , fiat , millage ); \n dataset.addValue( 5.0 , fiat , safety ); \n\n dataset.addValue( 5.0 , audi , speed ); \n dataset.addValue( 6.0 , audi , userrating ); \n dataset.addValue( 10.0 , audi , millage ); \n dataset.addValue( 4.0 , audi , safety );\n\n dataset.addValue( 4.0 , ford , speed ); \n dataset.addValue( 2.0 , ford , userrating ); \n dataset.addValue( 3.0 , ford , millage ); \n dataset.addValue( 6.0 , ford , safety ); \n\n return dataset; \n }\n \n public static void main( String[ ] args ) {\n BarChart_AWT chart = new BarChart_AWT(\"Car Usage Statistics\", \n \"Which car do you like?\");\n chart.pack( ); \n RefineryUtilities.centerFrameOnScreen( chart ); \n chart.setVisible( true ); \n }\n}" }, { "code": null, "e": 32904, "s": 32786, "text": "Let us keep the above Java code in BarChart_AWT.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 32950, "s": 32904, "text": "$javac BarChar_AWT.java \n$java BarChart_AWT\n" }, { "code": null, "e": 33035, "s": 32950, "text": "If everything is fine, it will compile and run to generate the following Bar Graph −" }, { "code": null, "e": 33115, "s": 33035, "text": "Let us re-write the above example to generate a JPEG image from a command line." }, { "code": null, "e": 34803, "s": 33115, "text": "import java.io.*;\n\nimport org.jfree.chart.ChartFactory;\nimport org.jfree.chart.JFreeChart;\nimport org.jfree.chart.plot.PlotOrientation;\nimport org.jfree.data.category.DefaultCategoryDataset;\nimport org.jfree.chart.ChartUtilities;\n\npublic class BarChart {\n \n public static void main( String[ ] args )throws Exception {\n final String fiat = \"FIAT\";\n final String audi = \"AUDI\";\n final String ford = \"FORD\";\n final String speed = \"Speed\";\n final String millage = \"Millage\";\n final String userrating = \"User Rating\";\n final String safety = \"safety\";\n\n final DefaultCategoryDataset dataset = new DefaultCategoryDataset( );\n dataset.addValue( 1.0 , fiat , speed );\n dataset.addValue( 3.0 , fiat , userrating );\n dataset.addValue( 5.0 , fiat , millage );\n dataset.addValue( 5.0 , fiat , safety );\n\n dataset.addValue( 5.0 , audi , speed );\n dataset.addValue( 6.0 , audi , userrating );\n dataset.addValue( 10.0 , audi , millage );\n dataset.addValue( 4.0 , audi , safety );\n\n dataset.addValue( 4.0 , ford , speed );\n dataset.addValue( 2.0 , ford , userrating );\n dataset.addValue( 3.0 , ford , millage );\n dataset.addValue( 6.0 , ford , safety );\n\n JFreeChart barChart = ChartFactory.createBarChart(\n \"CAR USAGE STATIStICS\", \n \"Category\", \"Score\", \n dataset,PlotOrientation.VERTICAL, \n true, true, false);\n \n int width = 640; /* Width of the image */\n int height = 480; /* Height of the image */ \n File BarChart = new File( \"BarChart.jpeg\" ); \n ChartUtilities.saveChartAsJPEG( BarChart , barChart , width , height );\n }\n}" }, { "code": null, "e": 34917, "s": 34803, "text": "Let us keep the above Java code in BarChart.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 34957, "s": 34917, "text": "$javac BarChart.java \n$java BarChart \n" }, { "code": null, "e": 35079, "s": 34957, "text": "If everything is fine, it will compile and run to create a JPEG image file named BarChart.jpeg in your current directory." }, { "code": null, "e": 35260, "s": 35079, "text": "A line chart or line graph displays information as a series of data points (markers) connected by straight line segments. Line Chart shows how data changes at equal time frequency." }, { "code": null, "e": 35368, "s": 35260, "text": "This chapter demonstrates how we can use JFreeChart to create Line Chart from a given set of business data." }, { "code": null, "e": 35492, "s": 35368, "text": "The following example draws a line chart to show a trend of number of schools opened in different years starting from 1970." }, { "code": null, "e": 35519, "s": 35492, "text": "Given data is as follows −" }, { "code": null, "e": 35668, "s": 35519, "text": "Following is the code to create Line Chart from the information above given. This code helps you to embed a line chart in any AWT based application." }, { "code": null, "e": 37244, "s": 35668, "text": "import org.jfree.chart.ChartPanel;\nimport org.jfree.chart.ChartFactory;\nimport org.jfree.chart.JFreeChart;\nimport org.jfree.ui.ApplicationFrame;\nimport org.jfree.ui.RefineryUtilities;\nimport org.jfree.chart.plot.PlotOrientation;\nimport org.jfree.data.category.DefaultCategoryDataset;\n\npublic class LineChart_AWT extends ApplicationFrame {\n\n public LineChart_AWT( String applicationTitle , String chartTitle ) {\n super(applicationTitle);\n JFreeChart lineChart = ChartFactory.createLineChart(\n chartTitle,\n \"Years\",\"Number of Schools\",\n createDataset(),\n PlotOrientation.VERTICAL,\n true,true,false);\n \n ChartPanel chartPanel = new ChartPanel( lineChart );\n chartPanel.setPreferredSize( new java.awt.Dimension( 560 , 367 ) );\n setContentPane( chartPanel );\n }\n\n private DefaultCategoryDataset createDataset( ) {\n DefaultCategoryDataset dataset = new DefaultCategoryDataset( );\n dataset.addValue( 15 , \"schools\" , \"1970\" );\n dataset.addValue( 30 , \"schools\" , \"1980\" );\n dataset.addValue( 60 , \"schools\" , \"1990\" );\n dataset.addValue( 120 , \"schools\" , \"2000\" );\n dataset.addValue( 240 , \"schools\" , \"2010\" );\n dataset.addValue( 300 , \"schools\" , \"2014\" );\n return dataset;\n }\n \n public static void main( String[ ] args ) {\n LineChart_AWT chart = new LineChart_AWT(\n \"School Vs Years\" ,\n \"Numer of Schools vs years\");\n\n chart.pack( );\n RefineryUtilities.centerFrameOnScreen( chart );\n chart.setVisible( true );\n }\n}" }, { "code": null, "e": 37363, "s": 37244, "text": "Let us keep the above Java code in LineChart_AWT.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 37413, "s": 37363, "text": "$javac LineChart_AWT.java \n$java LineChart_AWT \n" }, { "code": null, "e": 37499, "s": 37413, "text": "If everything is fine, it will compile and run to generate the following Line Graph −" }, { "code": null, "e": 37579, "s": 37499, "text": "Let us re-write the above example to generate a JPEG image from a command line." }, { "code": null, "e": 38815, "s": 37579, "text": "import java.io.*;\n\nimport org.jfree.chart.JFreeChart; \nimport org.jfree.chart.ChartFactory; \nimport org.jfree.chart.ChartUtilities; \nimport org.jfree.chart.plot.PlotOrientation;\nimport org.jfree.data.category.DefaultCategoryDataset;\n\npublic class LineChart {\n\n public static void main( String[ ] args ) throws Exception {\n DefaultCategoryDataset line_chart_dataset = new DefaultCategoryDataset();\n line_chart_dataset.addValue( 15 , \"schools\" , \"1970\" );\n line_chart_dataset.addValue( 30 , \"schools\" , \"1980\" );\n line_chart_dataset.addValue( 60 , \"schools\" , \"1990\" );\n line_chart_dataset.addValue( 120 , \"schools\" , \"2000\" );\n line_chart_dataset.addValue( 240 , \"schools\" , \"2010\" ); \n line_chart_dataset.addValue( 300 , \"schools\" , \"2014\" );\n\n JFreeChart lineChartObject = ChartFactory.createLineChart(\n \"Schools Vs Years\",\"Year\",\n \"Schools Count\",\n line_chart_dataset,PlotOrientation.VERTICAL,\n true,true,false);\n\n int width = 640; /* Width of the image */\n int height = 480; /* Height of the image */ \n File lineChart = new File( \"LineChart.jpeg\" ); \n ChartUtilities.saveChartAsJPEG(lineChart ,lineChartObject, width ,height);\n }\n}" }, { "code": null, "e": 38930, "s": 38815, "text": "Let us keep the above Java code in LineChart.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 38971, "s": 38930, "text": "$javac LineChart.java \n$java LineChart\n" }, { "code": null, "e": 39098, "s": 38971, "text": "If everything is fine, it will compile and execute to create a JPEG image file named LineChart.jpeg in your current directory." }, { "code": null, "e": 39462, "s": 39098, "text": "The XY chart (scatter) is based on one data series consisting of a list of X and Y values. Each value pair (X,Y) is a point in a coordinate system. Here, one value determines the horizontal (X) position, and the other determines the vertical (Y) position. This chapter demonstrates — how we can use JFreeChart to create XY Chart from a given set of business data." }, { "code": null, "e": 39643, "s": 39462, "text": "Consider an example where we want to create an XY chart for all major browsers. Here, different performance scores are gathered from different categories of people as shown below −" }, { "code": null, "e": 39792, "s": 39643, "text": "Following is the code to create an XY Chart from the above given information. This code helps you to embed an XY chart in any AWT based application." }, { "code": null, "e": 42568, "s": 39792, "text": "import java.awt.Color; \nimport java.awt.BasicStroke; \n\nimport org.jfree.chart.ChartPanel; \nimport org.jfree.chart.JFreeChart; \nimport org.jfree.data.xy.XYDataset; \nimport org.jfree.data.xy.XYSeries; \nimport org.jfree.ui.ApplicationFrame; \nimport org.jfree.ui.RefineryUtilities; \nimport org.jfree.chart.plot.XYPlot; \nimport org.jfree.chart.ChartFactory; \nimport org.jfree.chart.plot.PlotOrientation; \nimport org.jfree.data.xy.XYSeriesCollection; \nimport org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;\n\npublic class XYLineChart_AWT extends ApplicationFrame {\n\n public XYLineChart_AWT( String applicationTitle, String chartTitle ) {\n super(applicationTitle);\n JFreeChart xylineChart = ChartFactory.createXYLineChart(\n chartTitle ,\n \"Category\" ,\n \"Score\" ,\n createDataset() ,\n PlotOrientation.VERTICAL ,\n true , true , false);\n \n ChartPanel chartPanel = new ChartPanel( xylineChart );\n chartPanel.setPreferredSize( new java.awt.Dimension( 560 , 367 ) );\n final XYPlot plot = xylineChart.getXYPlot( );\n \n XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer( );\n renderer.setSeriesPaint( 0 , Color.RED );\n renderer.setSeriesPaint( 1 , Color.GREEN );\n renderer.setSeriesPaint( 2 , Color.YELLOW );\n renderer.setSeriesStroke( 0 , new BasicStroke( 4.0f ) );\n renderer.setSeriesStroke( 1 , new BasicStroke( 3.0f ) );\n renderer.setSeriesStroke( 2 , new BasicStroke( 2.0f ) );\n plot.setRenderer( renderer ); \n setContentPane( chartPanel ); \n }\n \n private XYDataset createDataset( ) {\n final XYSeries firefox = new XYSeries( \"Firefox\" ); \n firefox.add( 1.0 , 1.0 ); \n firefox.add( 2.0 , 4.0 ); \n firefox.add( 3.0 , 3.0 ); \n \n final XYSeries chrome = new XYSeries( \"Chrome\" ); \n chrome.add( 1.0 , 4.0 ); \n chrome.add( 2.0 , 5.0 ); \n chrome.add( 3.0 , 6.0 ); \n \n final XYSeries iexplorer = new XYSeries( \"InternetExplorer\" ); \n iexplorer.add( 3.0 , 4.0 ); \n iexplorer.add( 4.0 , 5.0 ); \n iexplorer.add( 5.0 , 4.0 ); \n \n final XYSeriesCollection dataset = new XYSeriesCollection( ); \n dataset.addSeries( firefox ); \n dataset.addSeries( chrome ); \n dataset.addSeries( iexplorer );\n return dataset;\n }\n\n public static void main( String[ ] args ) {\n XYLineChart_AWT chart = new XYLineChart_AWT(\"Browser Usage Statistics\",\n \"Which Browser are you using?\");\n chart.pack( ); \n RefineryUtilities.centerFrameOnScreen( chart ); \n chart.setVisible( true ); \n }\n}" }, { "code": null, "e": 42688, "s": 42568, "text": "Let us keep the above Java code in XYLineChart_AWT.java file, and then compile and run it from the command prompted as:" }, { "code": null, "e": 42742, "s": 42688, "text": "$javac XYLineChart_AWT.java \n$java XYLineChart_AWT \n" }, { "code": null, "e": 42826, "s": 42742, "text": "If everything is fine, it will compile and run to generate the following XY Graph −" }, { "code": null, "e": 42908, "s": 42826, "text": "Let us re-write the above example to generate a JPEG image from the command line." }, { "code": null, "e": 44405, "s": 42908, "text": "import java.io.*;\n\nimport org.jfree.chart.ChartFactory;\nimport org.jfree.chart.JFreeChart;\nimport org.jfree.data.xy.XYSeries;\nimport org.jfree.chart.plot.PlotOrientation;\nimport org.jfree.data.xy.XYSeriesCollection;\nimport org.jfree.chart.ChartUtilities; \n\npublic class XYLineChart_image {\n\n public static void main( String[ ] args )throws Exception {\n final XYSeries firefox = new XYSeries( \"Firefox\" );\n firefox.add( 1.0 , 1.0 );\n firefox.add( 2.0 , 4.0 );\n firefox.add( 3.0 , 3.0 );\n \n final XYSeries chrome = new XYSeries( \"Chrome\" );\n chrome.add( 1.0 , 4.0 );\n chrome.add( 2.0 , 5.0 );\n chrome.add( 3.0 , 6.0 );\n \n final XYSeries iexplorer = new XYSeries( \"InternetExplorer\" );\n iexplorer.add( 3.0 , 4.0 );\n iexplorer.add( 4.0 , 5.0 );\n iexplorer.add( 5.0 , 4.0 );\n \n final XYSeriesCollection dataset = new XYSeriesCollection( );\n dataset.addSeries( firefox );\n dataset.addSeries( chrome );\n dataset.addSeries( iexplorer );\n\n JFreeChart xylineChart = ChartFactory.createXYLineChart(\n \"Browser usage statastics\", \n \"Category\",\n \"Score\", \n dataset,\n PlotOrientation.VERTICAL, \n true, true, false);\n \n int width = 640; /* Width of the image */\n int height = 480; /* Height of the image */ \n File XYChart = new File( \"XYLineChart.jpeg\" ); \n ChartUtilities.saveChartAsJPEG( XYChart, xylineChart, width, height);\n }\n}" }, { "code": null, "e": 44528, "s": 44405, "text": "Let us keep the above Java code in XYLineChart_image.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 44585, "s": 44528, "text": "$javac XYLineChart_image.java \n$java XYLineChart_image\n" }, { "code": null, "e": 44710, "s": 44585, "text": "If everything is fine, it will compile and run to create a JPEG image file named XYLineChart.jpeg in your current directory." }, { "code": null, "e": 45050, "s": 44710, "text": "The 3D charts are the ones, which appear in a three-dimensional format. You can use these charts to provide better display and clear information. A 3D Pie chart is same as the pie chart additionally with a nice 3D effect. A 3D effect can be achieved by adding a little extra code, which will take care of creating 3D effect in a pie chart." }, { "code": null, "e": 45219, "s": 45050, "text": "Consider the following example to illustrate mobile sale with the help of a 3D pie chart. Following is a list of different mobile brands and their sale (units per day)." }, { "code": null, "e": 45369, "s": 45219, "text": "Following is the code to create 3D Pie Chart from the above given information. This code helps you to embed a pie chart in any AWT based application." }, { "code": null, "e": 46817, "s": 45369, "text": "import java.io.*; \n\nimport org.jfree.chart.ChartFactory; \nimport org.jfree.chart.JFreeChart; \nimport org.jfree.chart.plot.PiePlot3D; \nimport org.jfree.data.general.DefaultPieDataset; \nimport org.jfree.chart.ChartUtilities;\n\npublic class PieChart3D {\n\n public static void main( String[ ] args )throws Exception {\n DefaultPieDataset dataset = new DefaultPieDataset( ); \n dataset.setValue( \"IPhone 5s\" , new Double( 20 ) ); \n dataset.setValue( \"SamSung Grand\" , new Double( 20 ) ); \n dataset.setValue( \"MotoG\" , new Double( 40 ) ); \n dataset.setValue( \"Nokia Lumia\" , new Double( 10 ) ); \n\n JFreeChart chart = ChartFactory.createPieChart3D( \n \"Mobile Sales\" , // chart title \n dataset , // data \n true , // include legend \n true, \n false);\n\n final PiePlot3D plot = ( PiePlot3D ) chart.getPlot( ); \n plot.setStartAngle( 270 ); \n plot.setForegroundAlpha( 0.60f ); \n plot.setInteriorGap( 0.02 ); \n int width = 640; /* Width of the image */ \n int height = 480; /* Height of the image */ \n File pieChart3D = new File( \"pie_Chart3D.jpeg\" ); \n ChartUtilities.saveChartAsJPEG( pieChart3D , chart , width , height ); \n }\n}" }, { "code": null, "e": 46933, "s": 46817, "text": "Let us keep the above Java code in PieChart3D.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 46977, "s": 46933, "text": "$javac PieChart3D.java \n$java PieChart3D \n" }, { "code": null, "e": 47110, "s": 46977, "text": "If everything is fine, it will compile and run to create a JPEG image file named PieChart3D.jpeg having the following 3D Pie Chart −" }, { "code": null, "e": 47518, "s": 47110, "text": "A 3D Bar chart is same as the bar chart additionally with a nice 3D effect. A 3D effect can achieved by adding a little extra code, which will take care of creating 3D effect in a bar chart. Consider the following example that depicts various car statistics with the help of a 3D bar chart. Following is a list of car brands along with their different characteristics, which we will show using a bar chart −" }, { "code": null, "e": 47663, "s": 47518, "text": "The following code creates 3D Bar Chart from the above given information. This code helps you to embed a bar chart in any AWT based application." }, { "code": null, "e": 50017, "s": 47663, "text": "import java.io.*; \n\nimport org.jfree.chart.ChartFactory; \nimport org.jfree.chart.JFreeChart; \nimport org.jfree.chart.plot.PlotOrientation; \nimport org.jfree.data.category.DefaultCategoryDataset; \nimport org.jfree.chart.ChartUtilities; \n\npublic class BarChart3D {\n \n public static void main( String[ ] args )throws Exception {\n final String fait = \"FAIT\"; \n final String audi = \"AUDI\"; \n final String ford = \"FORD\"; \n final String speed = \"Speed\"; \n final String popular = \"Popular\"; \n final String mailage = \"Mailage\"; \n final String userrating = \"User Rating\"; \n final String safety = \"safety\"; \n final DefaultCategoryDataset dataset = new DefaultCategoryDataset( ); \n\n dataset.addValue( 1.0 , fait , speed ); \n dataset.addValue( 4.0 , fait , popular ); \n dataset.addValue( 3.0 , fait , userrating ); \n dataset.addValue( 5.0 , fait , mailage ); \n dataset.addValue( 5.0 , fait , safety ); \n \n dataset.addValue( 5.0 , audi , speed ); \n dataset.addValue( 7.0 , audi , popular ); \n dataset.addValue( 6.0 , audi , userrating ); \n dataset.addValue( 10.0 , audi , mailage ); \n dataset.addValue( 4.0 , audi , safety ); \n \n dataset.addValue( 4.0 , ford , speed ); \n dataset.addValue( 3.0 , ford , popular ); \n dataset.addValue( 2.0 , ford , userrating ); \n dataset.addValue( 3.0 , ford , mailage ); \n dataset.addValue( 6.0 , ford , safety ); \n \n JFreeChart barChart = ChartFactory.createBarChart3D(\n \"Car Usage Statistics\", \n \"Category\", \n \"Score\", \n dataset, \n PlotOrientation.VERTICAL, \n true, true, false);\n \n int width = 640; /* Width of the image */ \n int height = 480; /* Height of the image */ \n File barChart3D = new File( \"barChart3D.jpeg\" ); \n ChartUtilities.saveChartAsJPEG( barChart3D, barChart, width, height);\n }\n}" }, { "code": null, "e": 50133, "s": 50017, "text": "Let us keep the above Java code in BarChart3D.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 50175, "s": 50133, "text": "$javac BarChart3D.java \n$java BarChart3\n" }, { "code": null, "e": 50324, "s": 50175, "text": "If everything is fine with your environment, it will compile and run to create a JPEG image file BarChart3D.jpeg having the following 3D Bar Chart −" }, { "code": null, "e": 50640, "s": 50324, "text": "This chapter demonstrates how you can use JFreeChart to create Bubble Chart from a given set of business data. A bubble chart displays information in three-dimensional way. A bubble is plotted at the place where (x, y) coordinate intersect. The size of the bubble is considered as range or quantity of X and Y axis." }, { "code": null, "e": 50817, "s": 50640, "text": "Let us consider different persons along with their age, weight, and work capacities. The wok capacity can be treated as number of hours that is plotted as bubbles in the chart." }, { "code": null, "e": 50970, "s": 50817, "text": "Following is the code to create Bubble Chart from the above given information. This code helps you to embed a Bubble chart in any AWT based application." }, { "code": null, "e": 53985, "s": 50970, "text": "import java.awt.Color; \nimport java.awt.Dimension; \n\nimport javax.swing.JPanel; \n\nimport org.jfree.chart.*; \nimport org.jfree.chart.axis.NumberAxis; \nimport org.jfree.chart.plot.PlotOrientation; \nimport org.jfree.chart.plot.XYPlot; \nimport org.jfree.chart.renderer.xy.XYItemRenderer; \nimport org.jfree.data.xy.DefaultXYZDataset; \nimport org.jfree.data.xy.XYZDataset; \nimport org.jfree.ui.ApplicationFrame; \nimport org.jfree.ui.RefineryUtilities;\n \npublic class BubbleChart_AWT extends ApplicationFrame {\n\n public BubbleChart_AWT( String s ) {\n super( s ); \n JPanel jpanel = createDemoPanel( ); \n jpanel.setPreferredSize(new Dimension( 560 , 370 ) ); \n setContentPane( jpanel ); \n }\n\n private static JFreeChart createChart( XYZDataset xyzdataset ) {\n JFreeChart jfreechart = ChartFactory.createBubbleChart(\n \"AGE vs WEIGHT vs WORK\", \n \"Weight\", \n \"AGE\", \n xyzdataset, \n PlotOrientation.HORIZONTAL, \n true, true, false);\n \n XYPlot xyplot = ( XYPlot )jfreechart.getPlot( ); \n xyplot.setForegroundAlpha( 0.65F ); \n XYItemRenderer xyitemrenderer = xyplot.getRenderer( );\n xyitemrenderer.setSeriesPaint( 0 , Color.blue ); \n NumberAxis numberaxis = ( NumberAxis )xyplot.getDomainAxis( ); \n numberaxis.setLowerMargin( 0.2 ); \n numberaxis.setUpperMargin( 0.5 ); \n NumberAxis numberaxis1 = ( NumberAxis )xyplot.getRangeAxis( ); \n numberaxis1.setLowerMargin( 0.8 ); \n numberaxis1.setUpperMargin( 0.9 );\n \n return jfreechart;\n }\n\n public static XYZDataset createDataset( ) {\n DefaultXYZDataset defaultxyzdataset = new DefaultXYZDataset(); \n double ad[ ] = { 30 , 40 , 50 , 60 , 70 , 80 }; \n double ad1[ ] = { 10 , 20 , 30 , 40 , 50 , 60 }; \n double ad2[ ] = { 4 , 5 , 10 , 8 , 9 , 6 }; \n double ad3[][] = { ad , ad1 , ad2 }; \n defaultxyzdataset.addSeries( \"Series 1\" , ad3 );\n \n return defaultxyzdataset; \n }\n\n public static JPanel createDemoPanel( ) {\n JFreeChart jfreechart = createChart( createDataset( ) ); \n ChartPanel chartpanel = new ChartPanel( jfreechart );\n \n chartpanel.setDomainZoomable( true ); \n chartpanel.setRangeZoomable( true );\n \n return chartpanel;\n }\n\n public static void main( String args[ ] ) {\n BubbleChart_AWT bubblechart = new BubbleChart_AWT( \"Bubble Chart_frame\" ); \n bubblechart.pack( ); \n RefineryUtilities.centerFrameOnScreen( bubblechart ); \n bubblechart.setVisible( true ); \n }\n}" }, { "code": null, "e": 54106, "s": 53985, "text": "Let us keep the above Java code in BubbleChart_AWT.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 54159, "s": 54106, "text": "$javac BubbleChart_AWT.java \n$java BubbleChart_AW \n" }, { "code": null, "e": 54247, "s": 54159, "text": "If everything is fine, it will compile and run to generate the following Bubble Graph −" }, { "code": null, "e": 54327, "s": 54247, "text": "Let us re-write the above example to generate a JPEG image from a command line." }, { "code": null, "e": 56069, "s": 54327, "text": "import java.io.*;\n\nimport java.awt.Color; \n\nimport org.jfree.chart.*; \nimport org.jfree.chart.axis.NumberAxis;\nimport org.jfree.chart.plot.PlotOrientation;\nimport org.jfree.chart.plot.XYPlot;\nimport org.jfree.chart.renderer.xy.XYItemRenderer;\nimport org.jfree.data.xy.DefaultXYZDataset;\nimport org.jfree.chart.ChartUtilities;\n\npublic class BubbleChart_image {\n \n public static void main( String args[ ] )throws Exception {\n DefaultXYZDataset defaultxyzdataset = new DefaultXYZDataset( );\n double ad[ ] = { 30 , 40 , 50 , 60 , 70 , 80 };\n double ad1[ ] = { 10 , 20 , 30 , 40 , 50 , 60 };\n double ad2[ ] = { 4 , 5 , 10 , 8 , 9 , 6 };\n double ad3[ ][ ] = { ad , ad1 , ad2 };\n defaultxyzdataset.addSeries( \"Series 1\" , ad3 );\n\n JFreeChart jfreechart = ChartFactory.createBubbleChart(\n \"AGE vs WEIGHT vs WORK\", \n \"Weight\", \n \"AGE\", \n defaultxyzdataset, \n PlotOrientation.HORIZONTAL, \n true, true, false);\n\n XYPlot xyplot = ( XYPlot )jfreechart.getPlot( );\n xyplot.setForegroundAlpha( 0.65F );\n XYItemRenderer xyitemrenderer = xyplot.getRenderer( );\n xyitemrenderer.setSeriesPaint( 0 , Color.blue );\n NumberAxis numberaxis = ( NumberAxis )xyplot.getDomainAxis( );\n numberaxis.setLowerMargin( 0.2 );\n numberaxis.setUpperMargin( 0.5 );\n NumberAxis numberaxis1 = ( NumberAxis )xyplot.getRangeAxis( );\n numberaxis1.setLowerMargin( 0.8 );\n numberaxis1.setUpperMargin( 0.9 );\n\n int width = 560; /* Width of the image */\n int height = 370; /* Height of the image */ \n File bubbleChart = new File(\"BubbleChart.jpeg\"); \n ChartUtilities.saveChartAsJPEG(bubbleChart,jfreechart,width,height);\n }\n}" }, { "code": null, "e": 56192, "s": 56069, "text": "Let us keep the above Java code in BubbleChart_image.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 56249, "s": 56192, "text": "$javac BubbleChart_image.java \n$java BubbleChart_image\n" }, { "code": null, "e": 56374, "s": 56249, "text": "If everything is fine, it will compile and run to create a JPEG image file named BubbleChart.jpeg in your current directory." }, { "code": null, "e": 56586, "s": 56374, "text": "A time series chart displays sequence of data points, which varies at equal intervals of time. This chapter demonstrates — how we can use JFreeChart to create Time Series Chart from a given set of business data." }, { "code": null, "e": 56844, "s": 56586, "text": "Let us consider various random numbers generated by using standard Java API Math.random(). We use these numbers to generate a Time Series Chart. You can generate similar chart for total number of errors occurring in your website at a given interval of time." }, { "code": null, "e": 56964, "s": 56844, "text": "Following is the code to create Time Series Chart from the numbers generated by Math.random() at a given time internal." }, { "code": null, "e": 59168, "s": 56964, "text": "import org.jfree.chart.ChartFactory; \nimport org.jfree.chart.ChartPanel; \nimport org.jfree.chart.JFreeChart; \nimport org.jfree.data.general.SeriesException; \nimport org.jfree.data.time.Second; \nimport org.jfree.data.time.TimeSeries; \nimport org.jfree.data.time.TimeSeriesCollection; \nimport org.jfree.data.xy.XYDataset; \nimport org.jfree.ui.ApplicationFrame; \nimport org.jfree.ui.RefineryUtilities;\n\npublic class TimeSeries_AWT extends ApplicationFrame {\n\n public TimeSeries_AWT( final String title ) {\n super( title ); \n final XYDataset dataset = createDataset( ); \n final JFreeChart chart = createChart( dataset ); \n final ChartPanel chartPanel = new ChartPanel( chart ); \n chartPanel.setPreferredSize( new java.awt.Dimension( 560 , 370 ) ); \n chartPanel.setMouseZoomable( true , false ); \n setContentPane( chartPanel );\n }\n\n private XYDataset createDataset( ) {\n final TimeSeries series = new TimeSeries( \"Random Data\" ); \n Second current = new Second( ); \n double value = 100.0; \n \n for (int i = 0; i < 4000; i++) {\n \n try {\n value = value + Math.random( ) - 0.5; \n series.add(current, new Double( value ) ); \n current = ( Second ) current.next( ); \n } catch ( SeriesException e ) {\n System.err.println(\"Error adding to series\");\n }\n }\n\n return new TimeSeriesCollection(series);\n } \n\n private JFreeChart createChart( final XYDataset dataset ) {\n return ChartFactory.createTimeSeriesChart( \n \"Computing Test\", \n \"Seconds\", \n \"Value\", \n dataset, \n false, \n false, \n false);\n }\n\n public static void main( final String[ ] args ) {\n final String title = \"Time Series Management\"; \n final TimeSeries_AWT demo = new TimeSeries_AWT( title ); \n demo.pack( ); \n RefineryUtilities.positionFrameRandomly( demo ); \n demo.setVisible( true );\n }\n} " }, { "code": null, "e": 59288, "s": 59168, "text": "Let us keep the above Java code in TimeSeries_AWT.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 59340, "s": 59288, "text": "$javac TimeSeries_AWT.java \n$java TImeSeries_AWT \n" }, { "code": null, "e": 59433, "s": 59340, "text": "If everything is fine, it will compile and run to generate the following Time Series Graph −" }, { "code": null, "e": 59513, "s": 59433, "text": "Let us re-write the above example to generate a JPEG image from a command line." }, { "code": null, "e": 60972, "s": 59513, "text": "import java.io.*;\n\nimport org.jfree.chart.ChartFactory;\nimport org.jfree.chart.JFreeChart;\nimport org.jfree.data.general.SeriesException;\nimport org.jfree.data.time.Second;\nimport org.jfree.data.time.TimeSeries;\nimport org.jfree.data.time.TimeSeriesCollection;\nimport org.jfree.data.xy.XYDataset;\nimport org.jfree.chart.ChartUtilities;\n\npublic class TimeSeriesChart {\n \n public static void main( final String[ ] args )throws Exception {\n final TimeSeries series = new TimeSeries( \"Random Data\" );\n Second current = new Second();\n double value = 100.0;\n \n for ( int i = 0 ; i < 4000 ; i++ ) {\n \n try {\n value = value + Math.random( ) - 0.5;\n series.add( current , new Double( value ) );\n current = ( Second ) current.next( );\n } catch ( SeriesException e ) {\n System.err.println( \"Error adding to series\" );\n }\n }\n \n final XYDataset dataset=( XYDataset )new TimeSeriesCollection(series);\n JFreeChart timechart = ChartFactory.createTimeSeriesChart(\n \"Computing Test\", \n \"Seconds\", \n \"Value\", \n dataset,\n false, \n false, \n false);\n \n int width = 560; /* Width of the image */\n int height = 370; /* Height of the image */ \n File timeChart = new File( \"TimeChart.jpeg\" ); \n ChartUtilities.saveChartAsJPEG( timeChart, timechart, width, height );\n }\n}" }, { "code": null, "e": 61093, "s": 60972, "text": "Let us keep the above Java code in TimeSeriesChart.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 61146, "s": 61093, "text": "$javac TimeSeriesChart.java \n$java TimeSeriesChart\n" }, { "code": null, "e": 61290, "s": 61146, "text": "If everything is fine with your environment, it will compile and run to create a JPEG image file TimeChart.jpeg file in your current directory." }, { "code": null, "e": 61526, "s": 61290, "text": "So far we studied how to create various types of charts using JFreeChart APIs using static data. But in production environment, data is provided in the form of text file with a predefined format, or it comes directly from the database." }, { "code": null, "e": 61687, "s": 61526, "text": "This chapter will explain — how we can read a simple data from a given text file from a given location and then use JFreeChart to create a chart of your choice." }, { "code": null, "e": 61825, "s": 61687, "text": "Consider we have a file named mobile.txt, having different mobile brands and their sale (units per day) separated by a simple comma (,) −" }, { "code": null, "e": 61895, "s": 61825, "text": "Iphone 5S, 20 \nSamsung Grand, 20 \nMOTO G, 40 Nokia \nLumia, 10 \n" }, { "code": null, "e": 61989, "s": 61895, "text": "Following is the code to create a Pie Chart based on the information provided in mobile.txt −" }, { "code": null, "e": 63735, "s": 61989, "text": "import java.io.*; \n\nimport java.util.StringTokenizer; \n\nimport org.jfree.chart.ChartUtilities; \nimport org.jfree.chart.ChartFactory; \nimport org.jfree.chart.JFreeChart; \nimport org.jfree.data.general.DefaultPieDataset;\n\npublic class PieChart_File {\n \n public static void main( String[ ] args )throws Exception {\n \n String mobilebrands[ ] = { \n \"IPhone 5s\" , \n \"SamSung Grand\" , \n \"MotoG\" , \n \"Nokia Lumia\" \n };\n \n InputStream in = new FileInputStream( new File( \"C:/temp/test.txt\" ) ); \n BufferedReader reader = new BufferedReader(new InputStreamReader(in ) ); \n StringBuilder out = new StringBuilder(); \n String line; \n DefaultPieDataset dataset = new DefaultPieDataset(); \n\n while (( line = reader.readLine() ) != null ) {\n out.append( line );\n }\n \n StringTokenizer s = new StringTokenizer( out.toString(), \",\" );\n int i = 0; \n \n while( s.hasMoreTokens( ) && ( mobilebrands [i] != null ) ) {\n dataset.setValue(mobilebrands[i], Double.parseDouble( s.nextToken( ) ));\n i++;\n }\n \n JFreeChart chart = ChartFactory.createPieChart( \n \"Mobile Sales\", // chart title \n dataset, // data \n true, // include legend \n true, \n false);\n \n int width = 560; /* Width of the image */ \n int height = 370; /* Height of the image */ \n File pieChart = new File( \"pie_Chart.jpeg\" ); \n ChartUtilities.saveChartAsJPEG( pieChart, chart, width, height); \n }\n}" }, { "code": null, "e": 63854, "s": 63735, "text": "Let us keep the above Java code in PieChart_File.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 63904, "s": 63854, "text": "$javac PieChart_File.java \n$java PieChart_File \n" }, { "code": null, "e": 64034, "s": 63904, "text": "If everything is fine, it will compile and run to create a JPEG image file named PieChart.jpeg that contains the following chart." }, { "code": null, "e": 64165, "s": 64034, "text": "This chapter explains how you can read simple data from a database table and then use JFreeChart to create a chart of your choice." }, { "code": null, "e": 64279, "s": 64165, "text": "Consider we have the following MySQL table mobile_tbl(mobile_brand VARCHAR(100) NOT\nNULL, unit_sale INT NO NULL);" }, { "code": null, "e": 64333, "s": 64279, "text": "Consider this table is having the following records −" }, { "code": null, "e": 64533, "s": 64333, "text": "Following is the code to create a Pie Chart based on the information provided in mobile_tbl table available in test_db in a MySQL database. Based on your requirements, you can use any other database." }, { "code": null, "e": 66139, "s": 64533, "text": "import java.io.*; \nimport java.sql.*; \n\nimport org.jfree.chart.ChartUtilities;\nimport org.jfree.chart.ChartFactory; \nimport org.jfree.chart.JFreeChart; \nimport org.jfree.data.general.DefaultPieDataset;\n\npublic class PieChart_DB {\n \n public static void main( String[ ] args )throws Exception {\n \n String mobilebrands[] = {\n \"IPhone 5s\", \n \"SamSung Grand\", \n \"MotoG\", \n \"Nokia Lumia\" \n };\n \n /* Create MySQL Database Connection */\n Class.forName( \"com.mysql.jdbc.Driver\" );\n Connection connect = DriverManager.getConnection( \n \"jdbc:mysql://localhost:3306/jf_testdb\" , \n \"root\", \n \"root123\");\n \n Statement statement = connect.createStatement( );\n ResultSet resultSet = statement.executeQuery(\"select * from mobile_data\" );\n DefaultPieDataset dataset = new DefaultPieDataset( );\n \n while( resultSet.next( ) ) {\n dataset.setValue( \n resultSet.getString( \"mobile_brand\" ) ,\n Double.parseDouble( resultSet.getString( \"unit_sale\" )));\n }\n \n JFreeChart chart = ChartFactory.createPieChart(\n \"Mobile Sales\", // chart title \n dataset, // data \n true, // include legend \n true, \n false );\n\n int width = 560; /* Width of the image */\n int height = 370; /* Height of the image */ \n File pieChart = new File( \"Pie_Chart.jpeg\" );\n ChartUtilities.saveChartAsJPEG( pieChart , chart , width , height );\n }\n}" }, { "code": null, "e": 66256, "s": 66139, "text": "Let us keep the above Java code in PieChart_DB.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 66301, "s": 66256, "text": "$javac PieChart_DB.java \n$java PieChart_DB\n" }, { "code": null, "e": 66425, "s": 66301, "text": "If everything is fine, it will compile and run to create a JPEG image file named Pie_Chart.jpeg having the following chart." }, { "code": null, "e": 66432, "s": 66425, "text": " Print" }, { "code": null, "e": 66443, "s": 66432, "text": " Add Notes" } ]
Tensorflow Serving with Docker. How to deploy ML models to production. | by Vijay Gupta | Towards Data Science
This article will guide you through how you can build and train a simple CNN model and later use this trained model to be served as an endpoint using Tensorflow Serving. Whether you are an Amateur, ML Engineer, Data Scientist or the DevOps guys, I am sure you will be able to deploy the ML model by the end of this article. Tensorflow Serving is an API designed by Google for production machine learning systems, Google and many big tech companies use this extensively. It makes it easy to deploy your model with the same server architecture and APIs. It works best with a TensorFlow model but I guess it can be extended to serve other kinds of models as well. The above diagrams show a brief image of how all this process looks like from building the model to serving that model to an endpoint using Tensorflow Serving. The best option to serve most kinds of models might be to run a centralized model on a server where any kind of device maybe it’s desktop, mobile, or embedded devices can request from. Then the server would do the inference for you and return the predictions. From that prediction, you can render it to any device. A big advantage in this type of architecture is that suppose you have several clients accessing your endpoint which is centralized on a server. Everyone gets to access the same model version and can enjoy the updated version seamlessly also scaling for large number requests becomes easy by just adding load balancers. It would have become difficult if you would have deployed the model on each client machine, hence managing versions and putting out new updates becomes challenging. Now let us get into the WORK MODE. We will be training a neural network model to classify images on clothing (i.e mnist fashion dataset), saving trained TensorFlow based model and serve it with Tensorflow Serving. Although, more focus will be on serving the model part. You will find all the codes in the below Git Repository. Star this repository and follow me on Medium, I will be posting more updates in the coming weeks on Tensorflow algorithms, ML Model pipelines and examples to integrate with cloud services like AWS and Azure. It will be easy if you run these codes in Google Collab. github.com import sys# Confirm that we're using Python 3assert sys.version_info.major is 3, 'Oops, not running Python 3.'import tensorflow as tffrom tensorflow import kerasimport numpy as npimport osimport subprocess Pre-Processing Data before feeding it to the model. # Model VersionVERSION = '00000123'fashion_mnist = keras.datasets.fashion_mnist(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()# scale the values to 0.0 to 1.0train_images = train_images / 255.0test_images = test_images / 255.0# reshape for feeding into the modeltrain_images = train_images.reshape(train_images.shape[0], 28, 28, 1)test_images = test_images.reshape(test_images.shape[0], 28, 28, 1)print('\ntrain_images.shape: {}, of {}'.format(train_images.shape, train_images.dtype))print('test_images.shape: {}, of {}'.format(test_images.shape, test_images.dtype)) Building and Training the CNN Model on Fashion MNIST Data model = keras.Sequential([keras.layers.Conv2D(input_shape=(28,28,1), filters=8, kernel_size=3,strides=2, activation='relu', name='Conv1'),keras.layers.Flatten(),keras.layers.Dense(10, activation=tf.nn.softmax, name='Softmax')])model.summary()epochs = 15model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])model.fit(train_images, train_labels, epochs=epochs)test_loss, test_acc = model.evaluate(test_images, test_labels)print('\nTest accuracy: {}'.format(test_acc)) Saving the trained model in TensorFlow protobuf format. saved_model_path = model.save(f"./tmp/{VERSION}", save_format='tf') SavedModel CLI helps you to examine your model and inspect the model’s SignatureDef's. It gives you details about the input Tensor dtype and shape the model was trained on. So, you have to give input to the model in the same format and get the output as defined by SignatureDef's. import subprocesssubprocess.run([f"saved_model_cli show --dir ./tmp/{VERSION}/ --all"],shell=True)# Zipping the model as model.tar.gzsubprocess.run([f"tar cvfz model.tar.gz tmp/{VERSION}/"],shell=True) We will be serving the model on our local machine, so we need the compressed model file and the JSON file which will be input to the model.Download the compressed model file, so that you can deploy it on your local machine( assuming you have ran the whole code in Google Collab). from google.colab import filesfiles.download('model.tar.gz') Making a JSON file which will be containing the inputSignatureDef's required for the model, this will then be passed to the model endpoint. import json# Wrap bitstring in JSONdata = json.dumps({"signature_name": "serving_default", "instances": test_images[0:3].tolist()})json_file = open('predict.json', 'w')json_file.write(data)json_file.close()files.download('predict.json') Install Docker from their official site. Quick links to download: Docker for macOS Docker for Windows 10 Pro or later Let us start with pulling the latest Tensorflow Serving image docker pull tensorflow/serving Running the Serving image with our model deployed on the REST API endpoint. docker run -p 8501:8501 --mount type=bind,source=/path/to/the/unzipped/model/tmp/,target=/models/fashion_mnist -e MODEL_NAME=fashion_mnist -t tensorflow/serving Now your docker container is running with Tensorflow Serving Model Server, binding the REST API port 8501 and mapped the model from our host to where models are expected in the container. Also an environment variable is passed which is important to query our model. You can query the model using predict API curl -d ‘{"signature_name": "serving_default", "instances": [[[[0.0], [0.0]................[0.0]]]]}’ -X POST http://localhost:8501/v1/models/fashion_mnist:predict Or you can run the below script in your local machine to get the prediction Awesome, Now your model just won’t get lost in your local system but you can deploy your model to production so that people can make use of it. You have successfully created an endpoint using Tensorflow Serving in your local system. I will be posting more future blogs to run this same and several other types of model on cloud services. If this helped you, Tweet about the post and let people deploy their model because this is a bit complex and crucial part of the machine learning lifecycle. Star this repository and follow me on Medium, I will be posting more updates in the coming weeks on Tensorflow algorithms, ML Model pipelines and examples to integrate with cloud services like AWS and Azure.
[ { "code": null, "e": 496, "s": 172, "text": "This article will guide you through how you can build and train a simple CNN model and later use this trained model to be served as an endpoint using Tensorflow Serving. Whether you are an Amateur, ML Engineer, Data Scientist or the DevOps guys, I am sure you will be able to deploy the ML model by the end of this article." }, { "code": null, "e": 833, "s": 496, "text": "Tensorflow Serving is an API designed by Google for production machine learning systems, Google and many big tech companies use this extensively. It makes it easy to deploy your model with the same server architecture and APIs. It works best with a TensorFlow model but I guess it can be extended to serve other kinds of models as well." }, { "code": null, "e": 1792, "s": 833, "text": "The above diagrams show a brief image of how all this process looks like from building the model to serving that model to an endpoint using Tensorflow Serving. The best option to serve most kinds of models might be to run a centralized model on a server where any kind of device maybe it’s desktop, mobile, or embedded devices can request from. Then the server would do the inference for you and return the predictions. From that prediction, you can render it to any device. A big advantage in this type of architecture is that suppose you have several clients accessing your endpoint which is centralized on a server. Everyone gets to access the same model version and can enjoy the updated version seamlessly also scaling for large number requests becomes easy by just adding load balancers. It would have become difficult if you would have deployed the model on each client machine, hence managing versions and putting out new updates becomes challenging." }, { "code": null, "e": 1827, "s": 1792, "text": "Now let us get into the WORK MODE." }, { "code": null, "e": 2062, "s": 1827, "text": "We will be training a neural network model to classify images on clothing (i.e mnist fashion dataset), saving trained TensorFlow based model and serve it with Tensorflow Serving. Although, more focus will be on serving the model part." }, { "code": null, "e": 2327, "s": 2062, "text": "You will find all the codes in the below Git Repository. Star this repository and follow me on Medium, I will be posting more updates in the coming weeks on Tensorflow algorithms, ML Model pipelines and examples to integrate with cloud services like AWS and Azure." }, { "code": null, "e": 2384, "s": 2327, "text": "It will be easy if you run these codes in Google Collab." }, { "code": null, "e": 2395, "s": 2384, "text": "github.com" }, { "code": null, "e": 2601, "s": 2395, "text": "import sys# Confirm that we're using Python 3assert sys.version_info.major is 3, 'Oops, not running Python 3.'import tensorflow as tffrom tensorflow import kerasimport numpy as npimport osimport subprocess" }, { "code": null, "e": 2653, "s": 2601, "text": "Pre-Processing Data before feeding it to the model." }, { "code": null, "e": 3257, "s": 2653, "text": "# Model VersionVERSION = '00000123'fashion_mnist = keras.datasets.fashion_mnist(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()# scale the values to 0.0 to 1.0train_images = train_images / 255.0test_images = test_images / 255.0# reshape for feeding into the modeltrain_images = train_images.reshape(train_images.shape[0], 28, 28, 1)test_images = test_images.reshape(test_images.shape[0], 28, 28, 1)print('\\ntrain_images.shape: {}, of {}'.format(train_images.shape, train_images.dtype))print('test_images.shape: {}, of {}'.format(test_images.shape, test_images.dtype))" }, { "code": null, "e": 3315, "s": 3257, "text": "Building and Training the CNN Model on Fashion MNIST Data" }, { "code": null, "e": 3819, "s": 3315, "text": "model = keras.Sequential([keras.layers.Conv2D(input_shape=(28,28,1), filters=8, kernel_size=3,strides=2, activation='relu', name='Conv1'),keras.layers.Flatten(),keras.layers.Dense(10, activation=tf.nn.softmax, name='Softmax')])model.summary()epochs = 15model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])model.fit(train_images, train_labels, epochs=epochs)test_loss, test_acc = model.evaluate(test_images, test_labels)print('\\nTest accuracy: {}'.format(test_acc))" }, { "code": null, "e": 3875, "s": 3819, "text": "Saving the trained model in TensorFlow protobuf format." }, { "code": null, "e": 3943, "s": 3875, "text": "saved_model_path = model.save(f\"./tmp/{VERSION}\", save_format='tf')" }, { "code": null, "e": 4224, "s": 3943, "text": "SavedModel CLI helps you to examine your model and inspect the model’s SignatureDef's. It gives you details about the input Tensor dtype and shape the model was trained on. So, you have to give input to the model in the same format and get the output as defined by SignatureDef's." }, { "code": null, "e": 4426, "s": 4224, "text": "import subprocesssubprocess.run([f\"saved_model_cli show --dir ./tmp/{VERSION}/ --all\"],shell=True)# Zipping the model as model.tar.gzsubprocess.run([f\"tar cvfz model.tar.gz tmp/{VERSION}/\"],shell=True)" }, { "code": null, "e": 4706, "s": 4426, "text": "We will be serving the model on our local machine, so we need the compressed model file and the JSON file which will be input to the model.Download the compressed model file, so that you can deploy it on your local machine( assuming you have ran the whole code in Google Collab)." }, { "code": null, "e": 4767, "s": 4706, "text": "from google.colab import filesfiles.download('model.tar.gz')" }, { "code": null, "e": 4907, "s": 4767, "text": "Making a JSON file which will be containing the inputSignatureDef's required for the model, this will then be passed to the model endpoint." }, { "code": null, "e": 5144, "s": 4907, "text": "import json# Wrap bitstring in JSONdata = json.dumps({\"signature_name\": \"serving_default\", \"instances\": test_images[0:3].tolist()})json_file = open('predict.json', 'w')json_file.write(data)json_file.close()files.download('predict.json')" }, { "code": null, "e": 5185, "s": 5144, "text": "Install Docker from their official site." }, { "code": null, "e": 5210, "s": 5185, "text": "Quick links to download:" }, { "code": null, "e": 5227, "s": 5210, "text": "Docker for macOS" }, { "code": null, "e": 5262, "s": 5227, "text": "Docker for Windows 10 Pro or later" }, { "code": null, "e": 5324, "s": 5262, "text": "Let us start with pulling the latest Tensorflow Serving image" }, { "code": null, "e": 5355, "s": 5324, "text": "docker pull tensorflow/serving" }, { "code": null, "e": 5431, "s": 5355, "text": "Running the Serving image with our model deployed on the REST API endpoint." }, { "code": null, "e": 5592, "s": 5431, "text": "docker run -p 8501:8501 --mount type=bind,source=/path/to/the/unzipped/model/tmp/,target=/models/fashion_mnist -e MODEL_NAME=fashion_mnist -t tensorflow/serving" }, { "code": null, "e": 5858, "s": 5592, "text": "Now your docker container is running with Tensorflow Serving Model Server, binding the REST API port 8501 and mapped the model from our host to where models are expected in the container. Also an environment variable is passed which is important to query our model." }, { "code": null, "e": 5900, "s": 5858, "text": "You can query the model using predict API" }, { "code": null, "e": 6064, "s": 5900, "text": "curl -d ‘{\"signature_name\": \"serving_default\", \"instances\": [[[[0.0], [0.0]................[0.0]]]]}’ -X POST http://localhost:8501/v1/models/fashion_mnist:predict" }, { "code": null, "e": 6140, "s": 6064, "text": "Or you can run the below script in your local machine to get the prediction" }, { "code": null, "e": 6284, "s": 6140, "text": "Awesome, Now your model just won’t get lost in your local system but you can deploy your model to production so that people can make use of it." }, { "code": null, "e": 6478, "s": 6284, "text": "You have successfully created an endpoint using Tensorflow Serving in your local system. I will be posting more future blogs to run this same and several other types of model on cloud services." }, { "code": null, "e": 6635, "s": 6478, "text": "If this helped you, Tweet about the post and let people deploy their model because this is a bit complex and crucial part of the machine learning lifecycle." } ]
Ant - Creating WAR files
Creating WAR files with Ant is extremely simple, and very similar to the creating JAR files task. After all, WAR file, like JAR file is just another ZIP file. The WAR task is an extension to the JAR task, but it has some nice additions to manipulate what goes into the WEB-INF/classes folder, and generating the web.xml file. The WAR task is useful to specify a particular layout of the WAR file. Since the WAR task is an extension of the JAR task, all attributes of the JAR task apply to the WAR task. webxml Path to the web.xml file lib A grouping to specify what goes into the WEB-INF\lib folder. classes A grouping to specify what goes into the WEB-INF\classes folder. metainf Specifies the instructions for generating the MANIFEST.MF file. Continuing our Hello World Fax Application project, let us add a new target to produce the jar files. But before that let us consider the war task. Consider the following example − <war destfile = "fax.war" webxml = "${web.dir}/web.xml"> <fileset dir = "${web.dir}/WebContent"> <include name = "**/*.*"/> </fileset> <lib dir = "thirdpartyjars"> <exclude name = "portlet.jar"/> </lib> <classes dir = "${build.dir}/web"/> </war> As per the previous examples, the web.dir variable refers to the source web folder, i.e, the folder that contains the JSP, css, javascript files etc. The build.dir variable refers to the output folder - This is where the classes for the WAR package can be found. Typically, the classes will be bundled into the WEB-INF/classes folder of the WAR file. In this example, we are creating a war file called fax.war. The WEB.XML file is obtained from the web source folder. All files from the 'WebContent' folder under web are copied into the WAR file. The WEB-INF/lib folder is populated with the jar files from the thirdpartyjars folder. However, we are excluding the portlet.jar as this is already present in the application server's lib folder. Finally, we are copying all classes from the build directory's web folder and putting into the WEB-INF/classes folder. Wrap the war task inside an Ant target (usually package) and run it. This will create the WAR file in the specified location. It is entirely possible to nest the classes, lib, metainf and webinf directors so that they live in scattered folders anywhere in the project structure. But best practices suggest that your Web project should have the Web Content structure that is similar to the structure of the WAR file. The Fax Application project has its structure outlined using this basic principle. To execute the war task, wrap it inside a target, most commonly, the build or package target, and run them. <target name = "build-war"> <war destfile = "fax.war" webxml = "${web.dir}/web.xml"> <fileset dir = "${web.dir}/WebContent"> <include name = "**/*.*"/> </fileset> <lib dir = "thirdpartyjars"> <exclude name = "portlet.jar"/> </lib> <classes dir = "${build.dir}/web"/> </war> </target> Running Ant on this file will create the fax.war file for us. The following outcome is the result of running the Ant file − C:\>ant build-war Buildfile: C:\build.xml BUILD SUCCESSFUL Total time: 12.3 seconds The fax.war file is now placed in the output folder. The contents of the war file will be − fax.war: +---jsp This folder contains the jsp files +---css This folder contains the stylesheet files +---js This folder contains the javascript files +---images This folder contains the image files +---META-INF This folder contains the Manifest.Mf +---WEB-INF +---classes This folder contains the compiled classes +---lib Third party libraries and the utility jar files WEB.xml Configuration file that defines the WAR package 20 Lectures 2 hours Deepti Trivedi 19 Lectures 2.5 hours Deepti Trivedi 139 Lectures 14 hours Er. Himanshu Vasishta 30 Lectures 1.5 hours Pushpendu Mondal 65 Lectures 6.5 hours Ridhi Arora 10 Lectures 2 hours Manish Gupta Print Add Notes Bookmark this page
[ { "code": null, "e": 2257, "s": 2097, "text": "Creating WAR files with Ant is extremely simple, and very similar to the creating JAR files task. After all, WAR file, like JAR file is just another ZIP file." }, { "code": null, "e": 2495, "s": 2257, "text": "The WAR task is an extension to the JAR task, but it has some nice additions to manipulate what goes into the WEB-INF/classes folder, and generating the web.xml file. The WAR task is useful to specify a particular layout of the WAR file." }, { "code": null, "e": 2601, "s": 2495, "text": "Since the WAR task is an extension of the JAR task, all attributes of the JAR task apply to the WAR task." }, { "code": null, "e": 2608, "s": 2601, "text": "webxml" }, { "code": null, "e": 2633, "s": 2608, "text": "Path to the web.xml file" }, { "code": null, "e": 2637, "s": 2633, "text": "lib" }, { "code": null, "e": 2698, "s": 2637, "text": "A grouping to specify what goes into the WEB-INF\\lib folder." }, { "code": null, "e": 2706, "s": 2698, "text": "classes" }, { "code": null, "e": 2771, "s": 2706, "text": "A grouping to specify what goes into the WEB-INF\\classes folder." }, { "code": null, "e": 2779, "s": 2771, "text": "metainf" }, { "code": null, "e": 2843, "s": 2779, "text": "Specifies the instructions for generating the MANIFEST.MF file." }, { "code": null, "e": 3024, "s": 2843, "text": "Continuing our Hello World Fax Application project, let us add a new target to produce the jar files. But before that let us consider the war task. Consider the following example −" }, { "code": null, "e": 3305, "s": 3024, "text": "<war destfile = \"fax.war\" webxml = \"${web.dir}/web.xml\">\n <fileset dir = \"${web.dir}/WebContent\">\n <include name = \"**/*.*\"/>\n </fileset>\n \n <lib dir = \"thirdpartyjars\">\n <exclude name = \"portlet.jar\"/>\n </lib>\n \n <classes dir = \"${build.dir}/web\"/>\n</war>" }, { "code": null, "e": 3455, "s": 3305, "text": "As per the previous examples, the web.dir variable refers to the source web folder, i.e, the folder that contains the JSP, css, javascript files etc." }, { "code": null, "e": 3656, "s": 3455, "text": "The build.dir variable refers to the output folder - This is where the classes for the WAR package can be found. Typically, the classes will be bundled into the WEB-INF/classes folder of the WAR file." }, { "code": null, "e": 3852, "s": 3656, "text": "In this example, we are creating a war file called fax.war. The WEB.XML file is obtained from the web source folder. All files from the 'WebContent' folder under web are copied into the WAR file." }, { "code": null, "e": 4167, "s": 3852, "text": "The WEB-INF/lib folder is populated with the jar files from the thirdpartyjars folder. However, we are excluding the portlet.jar as this is already present in the application server's lib folder. Finally, we are copying all classes from the build directory's web folder and putting into the WEB-INF/classes folder." }, { "code": null, "e": 4293, "s": 4167, "text": "Wrap the war task inside an Ant target (usually package) and run it. This will create the WAR file in the specified location." }, { "code": null, "e": 4666, "s": 4293, "text": "It is entirely possible to nest the classes, lib, metainf and webinf directors so that they live in scattered folders anywhere in the project structure. But best practices suggest that your Web project should have the Web Content structure that is similar to the structure of the WAR file. The Fax Application project has its structure outlined using this basic principle." }, { "code": null, "e": 4774, "s": 4666, "text": "To execute the war task, wrap it inside a target, most commonly, the build or package target, and run them." }, { "code": null, "e": 5126, "s": 4774, "text": "<target name = \"build-war\">\n <war destfile = \"fax.war\" webxml = \"${web.dir}/web.xml\">\n <fileset dir = \"${web.dir}/WebContent\">\n <include name = \"**/*.*\"/>\n </fileset>\n \n <lib dir = \"thirdpartyjars\">\n <exclude name = \"portlet.jar\"/>\n </lib>\n \n <classes dir = \"${build.dir}/web\"/>\n </war>\n</target>" }, { "code": null, "e": 5188, "s": 5126, "text": "Running Ant on this file will create the fax.war file for us." }, { "code": null, "e": 5250, "s": 5188, "text": "The following outcome is the result of running the Ant file −" }, { "code": null, "e": 5336, "s": 5250, "text": "C:\\>ant build-war\nBuildfile: C:\\build.xml\n\nBUILD SUCCESSFUL\nTotal time: 12.3 seconds\n" }, { "code": null, "e": 5428, "s": 5336, "text": "The fax.war file is now placed in the output folder. The contents of the war file will be −" }, { "code": null, "e": 5959, "s": 5428, "text": "fax.war:\n +---jsp This folder contains the jsp files\n +---css This folder contains the stylesheet files\n +---js This folder contains the javascript files\n +---images This folder contains the image files\n +---META-INF This folder contains the Manifest.Mf\n +---WEB-INF\n +---classes This folder contains the compiled classes\n +---lib Third party libraries and the utility jar files\n WEB.xml Configuration file that defines the WAR package\n" }, { "code": null, "e": 5992, "s": 5959, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 6008, "s": 5992, "text": " Deepti Trivedi" }, { "code": null, "e": 6043, "s": 6008, "text": "\n 19 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6059, "s": 6043, "text": " Deepti Trivedi" }, { "code": null, "e": 6094, "s": 6059, "text": "\n 139 Lectures \n 14 hours \n" }, { "code": null, "e": 6117, "s": 6094, "text": " Er. Himanshu Vasishta" }, { "code": null, "e": 6152, "s": 6117, "text": "\n 30 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6170, "s": 6152, "text": " Pushpendu Mondal" }, { "code": null, "e": 6205, "s": 6170, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 6218, "s": 6205, "text": " Ridhi Arora" }, { "code": null, "e": 6251, "s": 6218, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 6265, "s": 6251, "text": " Manish Gupta" }, { "code": null, "e": 6272, "s": 6265, "text": " Print" }, { "code": null, "e": 6283, "s": 6272, "text": " Add Notes" } ]
How to find the first character of a string in C#?
To get the first character, use the substring() method. Let’s say the following isour string − string str = "Welcome to the Planet!"; Now to get the first character, set the value 1 in the substring() method. string res = str.Substring(0, 1); Let us see the complete code − Live Demo using System; public class Demo { public static void Main() { string str = "Welcome to the Planet!"; string res = str.Substring(0, 1); Console.WriteLine(res); } } W
[ { "code": null, "e": 1118, "s": 1062, "text": "To get the first character, use the substring() method." }, { "code": null, "e": 1157, "s": 1118, "text": "Let’s say the following isour string −" }, { "code": null, "e": 1196, "s": 1157, "text": "string str = \"Welcome to the Planet!\";" }, { "code": null, "e": 1271, "s": 1196, "text": "Now to get the first character, set the value 1 in the substring() method." }, { "code": null, "e": 1305, "s": 1271, "text": "string res = str.Substring(0, 1);" }, { "code": null, "e": 1336, "s": 1305, "text": "Let us see the complete code −" }, { "code": null, "e": 1347, "s": 1336, "text": " Live Demo" }, { "code": null, "e": 1534, "s": 1347, "text": "using System;\npublic class Demo {\n public static void Main() {\n string str = \"Welcome to the Planet!\";\n string res = str.Substring(0, 1);\n Console.WriteLine(res);\n }\n}" }, { "code": null, "e": 1536, "s": 1534, "text": "W" } ]
Sentiment Analysis with Transformer Models and a Twist of Psychology | by Sats Sehgal | Towards Data Science
So you’ve been pouring hours and hours into developing hot marketing content or writing your next big article (kind of like this one) and want to convey a certain emotion to your audience. You want to know whether your content is going to resonate with your audience and draw a particular feeling whether that be joy, anger, sadness all to understand how different people react to your content. Text analytics, more specifically sentiment analysis isn’t a new concept by any means, however it too has gone through several iterations of models that have gotten better over time. First we started with a bag of words approach to understand whether certain words would convey a certain emotion. We then moved to RNN/LSTMs that use far more sophisticated models to help us understand emotion though require significant training tho lack parallelization making it very slow and resource intensive. In 2017, researchers at google brought forward the concept of the transformer model (fig 1) which is a lot more efficient than its predecessors. First, the input embedding is multi-dimensional in the sense that it can process complete sentences and not a series of words one by one. Second, it has a powerful multi-headed attention mechanism that enables sentences to maintain context and relationships between words within a sentence. It performs this attention analysis for each word several times to ensure adequate sampling. Finally, it uses a feed forward neural network to normalize the results and provide a sentiment (or polarity) prediction. To learn more about the transformer architecture be sure to visit the huggingface website Now that we understand the transformer model, let’s double click on the crux of this article and that is performing a sentiment analysis on a document and not necessarily a sentence. The input embeddings that are consumed by the transformer model are sentence embeddings and not total paragraphs or documents. For us to analyze a document we’ll need to break the sentence down into sentences. To do this, I use spacy and define a function to take some raw text and break it down into smaller sentences. Take for example the sentence below. We would take this sentence and put it through a spacy model that would analyze the text and break it into grammatical sentences as a list. Here is a function to help us accomplish this task and the output class Sentiment:# Constructor with raw text passed to the init function def __init__(self, raw_text): self.raw_text=raw_text.lower() def breakSentence(self, text_content): self.text_content=text_content nlp = English() nlp.add_pipe(nlp.create_pipe(‘sentencizer’)) doc = nlp(self.text_content) sentences = [sent.string.strip() for sent in doc.sents] return sentences Once you have a list of sentences, we would loop it through the transformer model to help us predict whether each sentence was positive or negative and with what score. You would end up with a result that provides something similar to below (fig 3) Now once we have these sentences, one can assume that you just average out your positives and negatives and come with a final polarity score. There are a few challenges with this assumptions. First we assume each sentence holds the same weight, which isn’t always the case (more on that later) and second, we are including sentences that the model had a relatively low confidence in identifying as negative (60% negative, 40% positive). For my research I wanted to filter out any sentence that didn’t have at least a 90% score either as negative or positive. So here is some code I developed to do just that and the result. In this code I also define a before and after result which helps me understand how many sentences I started with and how many were filtered out. Finally it returns the appropriate sentences and a matrix with how each filtered sentence was categorized, 1 for positive and -1 for negative. def findRawTextPolarity(self): confidence_level=0.9 nlpSA = pipeline("sentiment-analysis") sentences=self.breakSentence(self.raw_text) print('Before: ', len(sentences)) result = [{'sentence' : sentences[i],'label':nlpSA(sentences[i])[0]['label']} for i in range(len(sentences)) if nlpSA(sentences[i])[0]['score']>confidence_level] print('After: ', len(result)) sentences= [result[i]['sentence'].lower() for i in range(len(result))] labels= [result[i]['label'] for i in range(len(result))] map_polarity={'NEGATIVE': -1, 'POSITIVE': 1} matrix_result=[map_polarity[k] for k in labels] return sentences, matrix_result Ok so to this point we should have a list of filtered sentences with at least 90% prediction either way and a matrix of polarities. Now comes the interesting part around reading psychology. When readers read a document they tend to remember more of what they read towards the end of the document and less towards the beginning. Second, readers tend to remember the peak or climax of the document. What did the writer want the reader to remember? These statements are true if you consider the peak end rule. The peak end rule states “it is the theory that states the overall rating is determined by the peak intensity of the experience and end of the experience. It does not care about the averages throughout the experience” So understanding what peak end rule means and linking that to our use case, it’s true that when we give the model a large corpus of text, we endeavor to understand the peak of the article and give it slightly more weight as well as identify a mechanism to provide more weight to sentences that come later in the document. How do we do this? To identify the peak of the article, my hypothesis is that we would need to understand how a machine would classify the climax and one such way is to use text summarization. Text summarization extract the key concepts from a document to help pull out the key points as that is what will provide the best understanding as to what the author wants you to remember. Second, we need to define a decay factor such that as you move further down the document each preceding sentence loses some weight. Ok so let’s define the function to do each of these tasks. First let’s take a corpus of text and use the transformer pre-trained model to perform text summary. This function returns to the peak sentences. def findPeak(self): summarizer = pipeline("summarization") peak = (summarizer(self.raw_text))[0]['summary_text'] peak_sentences=self.breakSentence(peak) return peak_sentences Next we’re going to find the position of these peak sentences in the article list of sentences defined earlier in this article. If a sentence is part of the peak we will retain a value of 1 but if it’s not a peak sentence we’ll drop it down. I’ve used 0.9 but you can test something that works for your use case. The following function can accomplish this task. def getPeakposition(self): peak_weight_red=0.9 peak=self.findPeak() sentences = self.findRawTextPolarity()[0] matches=[[1 if operator.contains(s.replace(' .', ''),p.replace(' .', '')) else 0 for s in sentences] for p in peak] match_filter=[m for m in matches if sum(m)>0] sum_matrix=np.sum(np.array(match_filter),0) map_polarity={1: 1, 0: 1* peak_weight_red} matrix_result=[map_polarity[k] for k in sum_matrix] return matrix_result Ok now we need to create a mechanism to introduce a decay factor that will remove some degree of weight as a sentence gets older to the human brain within an article. I’ve created a function that will take it down using a linear decay factor but i’ve also used exponential decay that works well. def textWeights(self): decay=0.01 matrix=self.findRawTextPolarity() matrix_size=len(matrix[1]) decay_matrix=[1-(decay*i) for i in range(matrix_size)] return decay_matrix Alright we should now have three matrices Provides a decay weight factorProvides weight to peak sentencesPolarity of filtered sentences Provides a decay weight factor Provides weight to peak sentences Polarity of filtered sentences Now it gets easy. We multiply the three together which will give us a weighted result for each sentence in the document. Now that these are weighted we can take the weighted average for a final score for the entire document. I’ve gone ahead and defined my own categorization scale but you can define whatever makes sense for your own use case. To get the final score here is the code I developed followed by the result I received. def getFinalScore(self): peakposition=self.getPeakposition() decay=self.textWeightsexp() sent_polarity=self.findRawTextPolarity()[1] fin_score = [a*b*c for a,b,c in zip(peakposition,decay, sent_polarity)] fin_sent_fct = lambda x: 'POSITIVE' if x>0.5 else ('NEUTRAL' if 0.49>x>-0.5 else 'NEGATIVE') fin_sent=fin_sent_fct(np.mean(fin_score)) print('This document is categorized as {} with a final score of {}'.format(fin_sent, np.mean(fin_score))) So is this the end? No. Sentiment analysis is actually a very tricky subject that needs proper consideration. First, sentiment can be subjective and interpretation depends on different people. For example, I may enjoy the peak of a particular article while someone else may view a different sentence as the peak and therefore introduce a lot of subjectivity. Second, we leveraged a pre-trained model but the model should be trained with your own data and particular use case. There are various models you can leverage, a popular one being BERT, but you can use several others again depending on your use case. Sentiment analysis again is a great way for you to analyze text if done right and can unlock a plethora of insights to help you better make data drive decisions. To see a video example of this please visit the following the link on youtube https://youtu.be/sZOV5pD4ELg Sources: The Transformer architecture as present in the Attention is all you need paper by Google The Transformer architecture as present in the Attention is all you need paper by Google
[ { "code": null, "e": 566, "s": 171, "text": "So you’ve been pouring hours and hours into developing hot marketing content or writing your next big article (kind of like this one) and want to convey a certain emotion to your audience. You want to know whether your content is going to resonate with your audience and draw a particular feeling whether that be joy, anger, sadness all to understand how different people react to your content." }, { "code": null, "e": 1805, "s": 566, "text": "Text analytics, more specifically sentiment analysis isn’t a new concept by any means, however it too has gone through several iterations of models that have gotten better over time. First we started with a bag of words approach to understand whether certain words would convey a certain emotion. We then moved to RNN/LSTMs that use far more sophisticated models to help us understand emotion though require significant training tho lack parallelization making it very slow and resource intensive. In 2017, researchers at google brought forward the concept of the transformer model (fig 1) which is a lot more efficient than its predecessors. First, the input embedding is multi-dimensional in the sense that it can process complete sentences and not a series of words one by one. Second, it has a powerful multi-headed attention mechanism that enables sentences to maintain context and relationships between words within a sentence. It performs this attention analysis for each word several times to ensure adequate sampling. Finally, it uses a feed forward neural network to normalize the results and provide a sentiment (or polarity) prediction. To learn more about the transformer architecture be sure to visit the huggingface website" }, { "code": null, "e": 2308, "s": 1805, "text": "Now that we understand the transformer model, let’s double click on the crux of this article and that is performing a sentiment analysis on a document and not necessarily a sentence. The input embeddings that are consumed by the transformer model are sentence embeddings and not total paragraphs or documents. For us to analyze a document we’ll need to break the sentence down into sentences. To do this, I use spacy and define a function to take some raw text and break it down into smaller sentences." }, { "code": null, "e": 2551, "s": 2308, "text": "Take for example the sentence below. We would take this sentence and put it through a spacy model that would analyze the text and break it into grammatical sentences as a list. Here is a function to help us accomplish this task and the output" }, { "code": null, "e": 2952, "s": 2551, "text": "class Sentiment:# Constructor with raw text passed to the init function def __init__(self, raw_text): self.raw_text=raw_text.lower() def breakSentence(self, text_content): self.text_content=text_content nlp = English() nlp.add_pipe(nlp.create_pipe(‘sentencizer’)) doc = nlp(self.text_content) sentences = [sent.string.strip() for sent in doc.sents] return sentences" }, { "code": null, "e": 3201, "s": 2952, "text": "Once you have a list of sentences, we would loop it through the transformer model to help us predict whether each sentence was positive or negative and with what score. You would end up with a result that provides something similar to below (fig 3)" }, { "code": null, "e": 4113, "s": 3201, "text": "Now once we have these sentences, one can assume that you just average out your positives and negatives and come with a final polarity score. There are a few challenges with this assumptions. First we assume each sentence holds the same weight, which isn’t always the case (more on that later) and second, we are including sentences that the model had a relatively low confidence in identifying as negative (60% negative, 40% positive). For my research I wanted to filter out any sentence that didn’t have at least a 90% score either as negative or positive. So here is some code I developed to do just that and the result. In this code I also define a before and after result which helps me understand how many sentences I started with and how many were filtered out. Finally it returns the appropriate sentences and a matrix with how each filtered sentence was categorized, 1 for positive and -1 for negative." }, { "code": null, "e": 4761, "s": 4113, "text": "def findRawTextPolarity(self): confidence_level=0.9 nlpSA = pipeline(\"sentiment-analysis\") sentences=self.breakSentence(self.raw_text) print('Before: ', len(sentences)) result = [{'sentence' : sentences[i],'label':nlpSA(sentences[i])[0]['label']} for i in range(len(sentences)) if nlpSA(sentences[i])[0]['score']>confidence_level] print('After: ', len(result)) sentences= [result[i]['sentence'].lower() for i in range(len(result))] labels= [result[i]['label'] for i in range(len(result))] map_polarity={'NEGATIVE': -1, 'POSITIVE': 1} matrix_result=[map_polarity[k] for k in labels] return sentences, matrix_result" }, { "code": null, "e": 4951, "s": 4761, "text": "Ok so to this point we should have a list of filtered sentences with at least 90% prediction either way and a matrix of polarities. Now comes the interesting part around reading psychology." }, { "code": null, "e": 5486, "s": 4951, "text": "When readers read a document they tend to remember more of what they read towards the end of the document and less towards the beginning. Second, readers tend to remember the peak or climax of the document. What did the writer want the reader to remember? These statements are true if you consider the peak end rule. The peak end rule states “it is the theory that states the overall rating is determined by the peak intensity of the experience and end of the experience. It does not care about the averages throughout the experience”" }, { "code": null, "e": 5827, "s": 5486, "text": "So understanding what peak end rule means and linking that to our use case, it’s true that when we give the model a large corpus of text, we endeavor to understand the peak of the article and give it slightly more weight as well as identify a mechanism to provide more weight to sentences that come later in the document. How do we do this?" }, { "code": null, "e": 6381, "s": 5827, "text": "To identify the peak of the article, my hypothesis is that we would need to understand how a machine would classify the climax and one such way is to use text summarization. Text summarization extract the key concepts from a document to help pull out the key points as that is what will provide the best understanding as to what the author wants you to remember. Second, we need to define a decay factor such that as you move further down the document each preceding sentence loses some weight. Ok so let’s define the function to do each of these tasks." }, { "code": null, "e": 6527, "s": 6381, "text": "First let’s take a corpus of text and use the transformer pre-trained model to perform text summary. This function returns to the peak sentences." }, { "code": null, "e": 6714, "s": 6527, "text": "def findPeak(self): summarizer = pipeline(\"summarization\") peak = (summarizer(self.raw_text))[0]['summary_text'] peak_sentences=self.breakSentence(peak) return peak_sentences" }, { "code": null, "e": 7076, "s": 6714, "text": "Next we’re going to find the position of these peak sentences in the article list of sentences defined earlier in this article. If a sentence is part of the peak we will retain a value of 1 but if it’s not a peak sentence we’ll drop it down. I’ve used 0.9 but you can test something that works for your use case. The following function can accomplish this task." }, { "code": null, "e": 7535, "s": 7076, "text": "def getPeakposition(self): peak_weight_red=0.9 peak=self.findPeak() sentences = self.findRawTextPolarity()[0] matches=[[1 if operator.contains(s.replace(' .', ''),p.replace(' .', '')) else 0 for s in sentences] for p in peak] match_filter=[m for m in matches if sum(m)>0] sum_matrix=np.sum(np.array(match_filter),0) map_polarity={1: 1, 0: 1* peak_weight_red} matrix_result=[map_polarity[k] for k in sum_matrix] return matrix_result" }, { "code": null, "e": 7831, "s": 7535, "text": "Ok now we need to create a mechanism to introduce a decay factor that will remove some degree of weight as a sentence gets older to the human brain within an article. I’ve created a function that will take it down using a linear decay factor but i’ve also used exponential decay that works well." }, { "code": null, "e": 8016, "s": 7831, "text": "def textWeights(self): decay=0.01 matrix=self.findRawTextPolarity() matrix_size=len(matrix[1]) decay_matrix=[1-(decay*i) for i in range(matrix_size)] return decay_matrix" }, { "code": null, "e": 8058, "s": 8016, "text": "Alright we should now have three matrices" }, { "code": null, "e": 8152, "s": 8058, "text": "Provides a decay weight factorProvides weight to peak sentencesPolarity of filtered sentences" }, { "code": null, "e": 8183, "s": 8152, "text": "Provides a decay weight factor" }, { "code": null, "e": 8217, "s": 8183, "text": "Provides weight to peak sentences" }, { "code": null, "e": 8248, "s": 8217, "text": "Polarity of filtered sentences" }, { "code": null, "e": 8592, "s": 8248, "text": "Now it gets easy. We multiply the three together which will give us a weighted result for each sentence in the document. Now that these are weighted we can take the weighted average for a final score for the entire document. I’ve gone ahead and defined my own categorization scale but you can define whatever makes sense for your own use case." }, { "code": null, "e": 8679, "s": 8592, "text": "To get the final score here is the code I developed followed by the result I received." }, { "code": null, "e": 9146, "s": 8679, "text": "def getFinalScore(self): peakposition=self.getPeakposition() decay=self.textWeightsexp() sent_polarity=self.findRawTextPolarity()[1] fin_score = [a*b*c for a,b,c in zip(peakposition,decay, sent_polarity)] fin_sent_fct = lambda x: 'POSITIVE' if x>0.5 else ('NEUTRAL' if 0.49>x>-0.5 else 'NEGATIVE') fin_sent=fin_sent_fct(np.mean(fin_score)) print('This document is categorized as {} with a final score of {}'.format(fin_sent, np.mean(fin_score)))" }, { "code": null, "e": 9918, "s": 9146, "text": "So is this the end? No. Sentiment analysis is actually a very tricky subject that needs proper consideration. First, sentiment can be subjective and interpretation depends on different people. For example, I may enjoy the peak of a particular article while someone else may view a different sentence as the peak and therefore introduce a lot of subjectivity. Second, we leveraged a pre-trained model but the model should be trained with your own data and particular use case. There are various models you can leverage, a popular one being BERT, but you can use several others again depending on your use case. Sentiment analysis again is a great way for you to analyze text if done right and can unlock a plethora of insights to help you better make data drive decisions." }, { "code": null, "e": 9996, "s": 9918, "text": "To see a video example of this please visit the following the link on youtube" }, { "code": null, "e": 10025, "s": 9996, "text": "https://youtu.be/sZOV5pD4ELg" }, { "code": null, "e": 10034, "s": 10025, "text": "Sources:" }, { "code": null, "e": 10123, "s": 10034, "text": "The Transformer architecture as present in the Attention is all you need paper by Google" } ]
turtle.reset() function in Python - GeeksforGeeks
28 Jul, 2020 The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. This function is used to delete the turtle’s drawings and restore its default values. It doesn’t require any argument. Syntax : turtle.reset() Below is the implementation of the above method with some examples : Example 1 : Python3 # import packageimport turtle # motionfor i in range(20): turtle.forward(2+2*i) turtle.left(45) # reset the workturtle.reset() Output : Example 2 : Python3 # import packageimport turtle # make turtle objects# and set positiont1 = turtle.Turtle()t2 = turtle.Turtle()t1.up()t1.setpos(-70, 0)t1.down()t2.up()t2.setpos(70, 0)t2.down() # loop for patternfor i in range(20): t1.forward(2+2*i) t1.left(45) t2.forward(2+2*i) t2.left(90) # reset first turtle# another remain as it ist1.reset() Output : Python-turtle 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 Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n28 Jul, 2020" }, { "code": null, "e": 24429, "s": 24212, "text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support." }, { "code": null, "e": 24548, "s": 24429, "text": "This function is used to delete the turtle’s drawings and restore its default values. It doesn’t require any argument." }, { "code": null, "e": 24557, "s": 24548, "text": "Syntax :" }, { "code": null, "e": 24573, "s": 24557, "text": "turtle.reset()\n" }, { "code": null, "e": 24642, "s": 24573, "text": "Below is the implementation of the above method with some examples :" }, { "code": null, "e": 24654, "s": 24642, "text": "Example 1 :" }, { "code": null, "e": 24662, "s": 24654, "text": "Python3" }, { "code": "# import packageimport turtle # motionfor i in range(20): turtle.forward(2+2*i) turtle.left(45) # reset the workturtle.reset()", "e": 24801, "s": 24662, "text": null }, { "code": null, "e": 24810, "s": 24801, "text": "Output :" }, { "code": null, "e": 24822, "s": 24810, "text": "Example 2 :" }, { "code": null, "e": 24830, "s": 24822, "text": "Python3" }, { "code": "# import packageimport turtle # make turtle objects# and set positiont1 = turtle.Turtle()t2 = turtle.Turtle()t1.up()t1.setpos(-70, 0)t1.down()t2.up()t2.setpos(70, 0)t2.down() # loop for patternfor i in range(20): t1.forward(2+2*i) t1.left(45) t2.forward(2+2*i) t2.left(90) # reset first turtle# another remain as it ist1.reset()", "e": 25174, "s": 24830, "text": null }, { "code": null, "e": 25183, "s": 25174, "text": "Output :" }, { "code": null, "e": 25197, "s": 25183, "text": "Python-turtle" }, { "code": null, "e": 25204, "s": 25197, "text": "Python" }, { "code": null, "e": 25302, "s": 25204, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25311, "s": 25302, "text": "Comments" }, { "code": null, "e": 25324, "s": 25311, "text": "Old Comments" }, { "code": null, "e": 25356, "s": 25324, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25412, "s": 25356, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25433, "s": 25412, "text": "Python OOPs Concepts" }, { "code": null, "e": 25472, "s": 25433, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25514, "s": 25472, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25541, "s": 25514, "text": "Python Classes and Objects" }, { "code": null, "e": 25572, "s": 25541, "text": "Python | os.path.join() method" }, { "code": null, "e": 25614, "s": 25572, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25650, "s": 25614, "text": "Python | Pandas dataframe.groupby()" } ]
Check whether the given node is in the path between the nodes U and V - GeeksforGeeks
01 Nov, 2021 Given three vertices U, V and R of a binary tree, the task is to check whether R lies in the path between U and V. If it is not present in the path then print No otherwise print Yes.Examples: Input: U = 4, V = 6, R = 2 Output: Yes Path 4 -> 2 -> 1 -> 3 -> 6 contains 2Input: U = 4, V = 6, R = 5 Output: No Path 4 -> 2 -> 1 -> 3 -> 6 does not contain 5 Approach: The idea is to use Lowest Common Ancestor of two nodes. There are following cases for R to exist in the path between U and V: R is the lowest common ancestor of U and V.R is in the left subtree of the lowest common ancestor of U and V and is above V.R is in the right subtree of the lowest common ancestor of U and V and is above U. R is the lowest common ancestor of U and V. R is in the left subtree of the lowest common ancestor of U and V and is above V. R is in the right subtree of the lowest common ancestor of U and V and is above U. To know more about the lowest common ancestor, read the post here.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP Program to implement the above approach#include <bits/stdc++.h>using namespace std; // Table for storing 2^ith parentvector<vector<int>> table; // Variable to store the height of the treeint height; // Graphvector<vector<int>> Graph; // Arrays to mark start and end time for a nodevector<int> timeIn, timeOut; // Timerint cnt_time; // constructor for initializing// the global variablesvoid initialise(int n){ // log(n) with base 2 height = (int)ceil(log2(n)); // Filling with -1 as initial table.resize(n + 1, vector<int>(height + 1, -1)); // Fill the graph with empty lists Graph.resize(n + 1); timeIn.resize(n + 1); timeOut.resize(n + 1); cnt_time = 0;} // Dfs for pre-processing sparse table and// calculating start and end timevoid dfs(int s, int p){ // Parent at 1 node distance is always // it's direct parent table[s][0] = p; // Start time noted timeIn[s] = ++cnt_time; // Filling sparse table recursively for (int i = 1; i <= height; i++) table[s][i] = table[table[s][i - 1]][i - 1]; // Traversing children of source for (int child : Graph[s]) { if (child == p) continue; dfs(child, s); } // End time noted timeOut[s] = ++cnt_time;} // Helper function to check lowest common Ancestorbool check(int u, int v){ return timeIn[u] <= timeIn[v] && timeOut[u] >= timeOut[v];} // Function to return Lowest Common Ancestor of U and Vint lowestCommonAncestor(int U, int V){ if (check(U, V)) return U; if (check(V, U)) return V; for (int i = height; i >= 0; i--) { if (!check(table[U][i], V)) U = table[U][i]; } return table[U][0];} // Function that return true if R// exists on the path between U// and V in the given treebool isPresent(int U, int V, int R){ // Dfs dfs(1, 1); // Calculating LCA between U and V int LCA = lowestCommonAncestor(U, V); // Calculating LCA between U and R int LCA_1 = lowestCommonAncestor(U, R); // Calculating LCA between U and V int LCA_2 = lowestCommonAncestor(V, R); if (LCA == R || (LCA_1 == LCA && LCA_2 == R) || (LCA_2 == LCA && LCA_1 == R)) { return true; } return false;} // Driver codeint main(int argc, char const *argv[]){ // Number of vertices int n = 6; initialise(n); // Create the graph Graph[1].push_back(2); Graph[2].push_back(1); Graph[1].push_back(3); Graph[3].push_back(1); Graph[2].push_back(4); Graph[4].push_back(2); Graph[2].push_back(5); Graph[5].push_back(2); Graph[3].push_back(6); Graph[6].push_back(3); int U = 4, V = 6, R = 2; if (isPresent(U, V, R)) cout << "Yes" << endl; else cout << "No" << endl;} // This code is contributed by sanjeev2552 // Java implementation of the approachimport java.util.*; class GfG { // Table for storing 2^ith parent private static int table[][]; // Variable to store the height of the tree private static int height; // Graph private static ArrayList<ArrayList<Integer> > Graph; // Arrays to mark start and end time for a node private static int timeIn[]; private static int timeOut[]; // Timer private static int time; // Private constructor for initializing // the global variables private GfG(int n) { // log(n) with base 2 height = (int)Math.ceil(Math.log10(n) / Math.log10(2)); table = new int[n + 1][height + 1]; // Fill the graph with empty lists Graph = new ArrayList<ArrayList<Integer> >(); for (int i = 0; i <= n; i++) Graph.add(new ArrayList<Integer>()); timeIn = new int[n + 1]; timeOut = new int[n + 1]; time = 0; } // Filling with -1 as initial private static void preprocessing(int n) { for (int i = 0; i < n + 1; i++) { Arrays.fill(table[i], -1); } } // Dfs for pre-processing sparse table and // calculating start and end time private static void dfs(int s, int p) { // Parent at 1 node distance is always // it's direct parent table[s][0] = p; // Start time noted timeIn[s] = ++time; // Filling sparse table recursively for (int i = 1; i <= height; i++) table[s][i] = table[table[s][i - 1]][i - 1]; // Traversing children of source for (int child : Graph.get(s)) { if (child == p) continue; dfs(child, s); } // End time noted timeOut[s] = ++time; } // Helper function to check lowest common Ancestor private static boolean check(int u, int v) { return timeIn[u] <= timeIn[v] && timeOut[u] >= timeOut[v]; } // Function to return Lowest Common Ancestor of U and V private static int lowestCommonAncestor(int U, int V) { if (check(U, V)) return U; if (check(V, U)) return V; for (int i = height; i >= 0; i--) { if (!check(table[U][i], V)) U = table[U][i]; } return table[U][0]; } // Function that return true if R // exists on the path between U // and V in the given tree private static boolean isPresent(int U, int V, int R) { // Dfs dfs(1, 1); // Calculating LCA between U and V int LCA = lowestCommonAncestor(U, V); // Calculating LCA between U and R int LCA_1 = lowestCommonAncestor(U, R); // Calculating LCA between U and V int LCA_2 = lowestCommonAncestor(V, R); if (LCA == R || (LCA_1 == LCA && LCA_2 == R) || (LCA_2 == LCA && LCA_1 == R)) { return true; } return false; } // Driver code public static void main(String args[]) { // Number of vertices int n = 6; GfG obj = new GfG(n); // Create the graph preprocessing(n); Graph.get(1).add(2); Graph.get(2).add(1); Graph.get(1).add(3); Graph.get(3).add(1); Graph.get(2).add(4); Graph.get(4).add(2); Graph.get(2).add(5); Graph.get(5).add(2); Graph.get(3).add(6); Graph.get(6).add(3); int U = 4, V = 6, R = 2; if (isPresent(U, V, R)) System.out.print("Yes"); else System.out.print("No"); }} # Python3 implementation of the approachimport math n = 6 # GraphGraph = [] # log(n) with base 2height = math.ceil(math.log10(n) / math.log10(2))table = [[-1 for i in range(n + 1)] for j in range(n + 1)] # Fill the graph with empty listsfor i in range(n + 1): Graph.append([])timeIn = [0]*(n + 1)timeOut = [0]*(n + 1)time = 0 # Filling with -1 as initialdef preprocessing(n): for i in range(n + 1): for j in range(height + 1): table[i][j] = -1 # Dfs for pre-processing sparse table and# calculating start and end timedef dfs(s, p): global time # Parent at 1 node distance is always # it's direct parent table[s][0] = p # Start time noted timeIn[s] = time+1 # Filling sparse table recursively for i in range(1, height + 1): table[s][i] = table[table[s][i - 1]][i - 1] # Traversing children of source for child in range(len(Graph[s])): if Graph[s][child] == p: continue dfs(Graph[s][child], s) # End time noted time+=1 timeOut[s] = time # Helper function to check lowest common Ancestordef check(u, v): return (timeIn[u] <= timeIn[v] and timeOut[u] >= timeOut[v]) # Function to return Lowest Common Ancestor of U and Vdef lowestCommonAncestor(U, V): if check(U, V): return U if check(V, U): return V for i in range(height, -1, -1): if not check(table[U][i], V): U = table[U][i] return table[U][0] # Function that return true if R# exists on the path between U# and V in the given treedef isPresent(U, V, R): # Dfs dfs(1, 1) # Calculating LCA between U and V LCA = lowestCommonAncestor(U, V) # Calculating LCA between U and R LCA_1 = lowestCommonAncestor(U, R) # Calculating LCA between U and V LCA_2 = lowestCommonAncestor(V, R) if LCA == R or (LCA_1 == LCA and LCA_2 == R) or (LCA_2 == LCA and LCA_1 == R): return True return False # Create the graphpreprocessing(n)Graph[1].append(2)Graph[2].append(1)Graph[1].append(3)Graph[3].append(1)Graph[2].append(4)Graph[4].append(2)Graph[2].append(5)Graph[5].append(2)Graph[3].append(6)Graph[6].append(3) U, V, R = 4, 6, 2if isPresent(U, V, R): print("Yes")else: print("No") # This code is contributed by suresh07. // C# implementation of the approachusing System;using System.Collections.Generic; class GfG{ // Table for storing 2^ith parent private static int [,]table; // Variable to store the height of the tree private static int height; // Graph private static List<List<int> > Graph; // Arrays to mark start and end time for a node private static int []timeIn; private static int []timeOut; // Timer private static int time; // Private constructor for initializing // the global variables private GfG(int n) { // log(n) with base 2 height = (int)Math.Ceiling(Math.Log10(n) / Math.Log10(2)); table = new int[n + 1, height + 1]; // Fill the graph with empty lists Graph = new List<List<int> >(); for (int i = 0; i <= n; i++) Graph.Add(new List<int>()); timeIn = new int[n + 1]; timeOut = new int[n + 1]; time = 0; } // Filling with -1 as initial private static void preprocessing(int n) { for (int i = 0; i < n + 1; i++) { for(int j = 0; j < height + 1; j++) table[i, j] = -1; } } // Dfs for pre-processing sparse table and // calculating start and end time private static void dfs(int s, int p) { // Parent at 1 node distance is always // it's direct parent table[s, 0] = p; // Start time noted timeIn[s] = ++time; // Filling sparse table recursively for (int i = 1; i <= height; i++) table[s, i] = table[table[s, i - 1], i - 1]; // Traversing children of source foreach (int child in Graph[s]) { if (child == p) continue; dfs(child, s); } // End time noted timeOut[s] = ++time; } // Helper function to check lowest common Ancestor private static bool check(int u, int v) { return timeIn[u] <= timeIn[v] && timeOut[u] >= timeOut[v]; } // Function to return Lowest Common Ancestor of U and V private static int lowestCommonAncestor(int U, int V) { if (check(U, V)) return U; if (check(V, U)) return V; for (int i = height; i >= 0; i--) { if (!check(table[U, i], V)) U = table[U, i]; } return table[U, 0]; } // Function that return true if R // exists on the path between U // and V in the given tree private static bool isPresent(int U, int V, int R) { // Dfs dfs(1, 1); // Calculating LCA between U and V int LCA = lowestCommonAncestor(U, V); // Calculating LCA between U and R int LCA_1 = lowestCommonAncestor(U, R); // Calculating LCA between U and V int LCA_2 = lowestCommonAncestor(V, R); if (LCA == R || (LCA_1 == LCA && LCA_2 == R) || (LCA_2 == LCA && LCA_1 == R)) { return true; } return false; } // Driver code public static void Main(String []args) { // Number of vertices int n = 6; GfG obj = new GfG(n); // Create the graph preprocessing(n); Graph[1].Add(2); Graph[2].Add(1); Graph[1].Add(3); Graph[3].Add(1); Graph[2].Add(4); Graph[4].Add(2); Graph[2].Add(5); Graph[5].Add(2); Graph[3].Add(6); Graph[6].Add(3); int U = 4, V = 6, R = 2; if (isPresent(U, V, R)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by PrinciRaj1992 <script> // JavaScript implementation of the approach let n = 6; // Table for storing 2^ith parent let table; // Variable to store the height of the tree let height; // Graph let Graph = []; // Arrays to mark start and end time for a node let timeIn; let timeOut; // Timer let time; // log(n) with base 2 height = Math.ceil(Math.log10(n) / Math.log10(2)); table = new Array(n + 1); // Fill the graph with empty lists for (let i = 0; i <= n; i++) Graph.push([]); timeIn = new Array(n + 1); timeOut = new Array(n + 1); time = 0; // Filling with -1 as initial function preprocessing(n) { for (let i = 0; i < n + 1; i++) { table[i] = new Array(height + 1); for(let j = 0; j < height + 1; j++) { table[i][j] = -1; } } } // Dfs for pre-processing sparse table and // calculating start and end time function dfs(s, p) { // Parent at 1 node distance is always // it's direct parent table[s][0] = p; // Start time noted timeIn[s] = ++time; // Filling sparse table recursively for (let i = 1; i <= height; i++) table[s][i] = table[table[s][i - 1]][i - 1]; // Traversing children of source for (let child = 0; child < Graph[s].length; child++) { if (Graph[s][child] == p) continue; dfs(Graph[s][child], s); } // End time noted timeOut[s] = ++time; } // Helper function to check lowest common Ancestor function check(u, v) { return timeIn[u] <= timeIn[v] && timeOut[u] >= timeOut[v]; } // Function to return Lowest Common Ancestor of U and V function lowestCommonAncestor(U, V) { if (check(U, V)) return U; if (check(V, U)) return V; for (let i = height; i >= 0; i--) { if (!check(table[U][i], V)) U = table[U][i]; } return table[U][0]; } // Function that return true if R // exists on the path between U // and V in the given tree function isPresent(U, V, R) { // Dfs dfs(1, 1); // Calculating LCA between U and V let LCA = lowestCommonAncestor(U, V); // Calculating LCA between U and R let LCA_1 = lowestCommonAncestor(U, R); // Calculating LCA between U and V let LCA_2 = lowestCommonAncestor(V, R); if (LCA == R || (LCA_1 == LCA && LCA_2 == R) || (LCA_2 == LCA && LCA_1 == R)) { return true; } return false; } // Create the graph preprocessing(n); Graph[1].push(2); Graph[2].push(1); Graph[1].push(3); Graph[3].push(1); Graph[2].push(4); Graph[4].push(2); Graph[2].push(5); Graph[5].push(2); Graph[3].push(6); Graph[6].push(3); let U = 4, V = 6, R = 2; if (isPresent(U, V, R)) document.write("Yes"); else document.write("No"); </script> Yes Time Complexity: O(NlogN) for pre-processing and logN for finding the lowest common ancestor.Auxiliary Space: O(NlogN). princiraj1992 sanjeev2552 rameshtravel07 sagar0719kumar pankajsharmagfg rajeev0719singh ashutoshsinghgeeksforgeeks suresh07 Binary Tree LCA Data Structures Dynamic Programming Recursion Tree Data Structures Dynamic Programming Recursion Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Tree Data Structure Program to implement Singly Linked List in C++ using class TCS NQT Coding Sheet Hash Functions and list/types of Hash functions Building an undirected graph and finding shortest path using Dictionaries in Python 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Largest Sum Contiguous Subarray Longest Common Subsequence | DP-4 Longest Increasing Subsequence | DP-3
[ { "code": null, "e": 24661, "s": 24633, "text": "\n01 Nov, 2021" }, { "code": null, "e": 24855, "s": 24661, "text": "Given three vertices U, V and R of a binary tree, the task is to check whether R lies in the path between U and V. If it is not present in the path then print No otherwise print Yes.Examples: " }, { "code": null, "e": 24884, "s": 24855, "text": "Input: U = 4, V = 6, R = 2 " }, { "code": null, "e": 24962, "s": 24884, "text": "Output: Yes Path 4 -> 2 -> 1 -> 3 -> 6 contains 2Input: U = 4, V = 6, R = 5 " }, { "code": null, "e": 25021, "s": 24962, "text": "Output: No Path 4 -> 2 -> 1 -> 3 -> 6 does not contain 5 " }, { "code": null, "e": 25161, "s": 25023, "text": "Approach: The idea is to use Lowest Common Ancestor of two nodes. There are following cases for R to exist in the path between U and V: " }, { "code": null, "e": 25368, "s": 25161, "text": "R is the lowest common ancestor of U and V.R is in the left subtree of the lowest common ancestor of U and V and is above V.R is in the right subtree of the lowest common ancestor of U and V and is above U." }, { "code": null, "e": 25412, "s": 25368, "text": "R is the lowest common ancestor of U and V." }, { "code": null, "e": 25494, "s": 25412, "text": "R is in the left subtree of the lowest common ancestor of U and V and is above V." }, { "code": null, "e": 25577, "s": 25494, "text": "R is in the right subtree of the lowest common ancestor of U and V and is above U." }, { "code": null, "e": 25696, "s": 25577, "text": "To know more about the lowest common ancestor, read the post here.Below is the implementation of the above approach: " }, { "code": null, "e": 25700, "s": 25696, "text": "C++" }, { "code": null, "e": 25705, "s": 25700, "text": "Java" }, { "code": null, "e": 25713, "s": 25705, "text": "Python3" }, { "code": null, "e": 25716, "s": 25713, "text": "C#" }, { "code": null, "e": 25727, "s": 25716, "text": "Javascript" }, { "code": "// CPP Program to implement the above approach#include <bits/stdc++.h>using namespace std; // Table for storing 2^ith parentvector<vector<int>> table; // Variable to store the height of the treeint height; // Graphvector<vector<int>> Graph; // Arrays to mark start and end time for a nodevector<int> timeIn, timeOut; // Timerint cnt_time; // constructor for initializing// the global variablesvoid initialise(int n){ // log(n) with base 2 height = (int)ceil(log2(n)); // Filling with -1 as initial table.resize(n + 1, vector<int>(height + 1, -1)); // Fill the graph with empty lists Graph.resize(n + 1); timeIn.resize(n + 1); timeOut.resize(n + 1); cnt_time = 0;} // Dfs for pre-processing sparse table and// calculating start and end timevoid dfs(int s, int p){ // Parent at 1 node distance is always // it's direct parent table[s][0] = p; // Start time noted timeIn[s] = ++cnt_time; // Filling sparse table recursively for (int i = 1; i <= height; i++) table[s][i] = table[table[s][i - 1]][i - 1]; // Traversing children of source for (int child : Graph[s]) { if (child == p) continue; dfs(child, s); } // End time noted timeOut[s] = ++cnt_time;} // Helper function to check lowest common Ancestorbool check(int u, int v){ return timeIn[u] <= timeIn[v] && timeOut[u] >= timeOut[v];} // Function to return Lowest Common Ancestor of U and Vint lowestCommonAncestor(int U, int V){ if (check(U, V)) return U; if (check(V, U)) return V; for (int i = height; i >= 0; i--) { if (!check(table[U][i], V)) U = table[U][i]; } return table[U][0];} // Function that return true if R// exists on the path between U// and V in the given treebool isPresent(int U, int V, int R){ // Dfs dfs(1, 1); // Calculating LCA between U and V int LCA = lowestCommonAncestor(U, V); // Calculating LCA between U and R int LCA_1 = lowestCommonAncestor(U, R); // Calculating LCA between U and V int LCA_2 = lowestCommonAncestor(V, R); if (LCA == R || (LCA_1 == LCA && LCA_2 == R) || (LCA_2 == LCA && LCA_1 == R)) { return true; } return false;} // Driver codeint main(int argc, char const *argv[]){ // Number of vertices int n = 6; initialise(n); // Create the graph Graph[1].push_back(2); Graph[2].push_back(1); Graph[1].push_back(3); Graph[3].push_back(1); Graph[2].push_back(4); Graph[4].push_back(2); Graph[2].push_back(5); Graph[5].push_back(2); Graph[3].push_back(6); Graph[6].push_back(3); int U = 4, V = 6, R = 2; if (isPresent(U, V, R)) cout << \"Yes\" << endl; else cout << \"No\" << endl;} // This code is contributed by sanjeev2552", "e": 28339, "s": 25727, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GfG { // Table for storing 2^ith parent private static int table[][]; // Variable to store the height of the tree private static int height; // Graph private static ArrayList<ArrayList<Integer> > Graph; // Arrays to mark start and end time for a node private static int timeIn[]; private static int timeOut[]; // Timer private static int time; // Private constructor for initializing // the global variables private GfG(int n) { // log(n) with base 2 height = (int)Math.ceil(Math.log10(n) / Math.log10(2)); table = new int[n + 1][height + 1]; // Fill the graph with empty lists Graph = new ArrayList<ArrayList<Integer> >(); for (int i = 0; i <= n; i++) Graph.add(new ArrayList<Integer>()); timeIn = new int[n + 1]; timeOut = new int[n + 1]; time = 0; } // Filling with -1 as initial private static void preprocessing(int n) { for (int i = 0; i < n + 1; i++) { Arrays.fill(table[i], -1); } } // Dfs for pre-processing sparse table and // calculating start and end time private static void dfs(int s, int p) { // Parent at 1 node distance is always // it's direct parent table[s][0] = p; // Start time noted timeIn[s] = ++time; // Filling sparse table recursively for (int i = 1; i <= height; i++) table[s][i] = table[table[s][i - 1]][i - 1]; // Traversing children of source for (int child : Graph.get(s)) { if (child == p) continue; dfs(child, s); } // End time noted timeOut[s] = ++time; } // Helper function to check lowest common Ancestor private static boolean check(int u, int v) { return timeIn[u] <= timeIn[v] && timeOut[u] >= timeOut[v]; } // Function to return Lowest Common Ancestor of U and V private static int lowestCommonAncestor(int U, int V) { if (check(U, V)) return U; if (check(V, U)) return V; for (int i = height; i >= 0; i--) { if (!check(table[U][i], V)) U = table[U][i]; } return table[U][0]; } // Function that return true if R // exists on the path between U // and V in the given tree private static boolean isPresent(int U, int V, int R) { // Dfs dfs(1, 1); // Calculating LCA between U and V int LCA = lowestCommonAncestor(U, V); // Calculating LCA between U and R int LCA_1 = lowestCommonAncestor(U, R); // Calculating LCA between U and V int LCA_2 = lowestCommonAncestor(V, R); if (LCA == R || (LCA_1 == LCA && LCA_2 == R) || (LCA_2 == LCA && LCA_1 == R)) { return true; } return false; } // Driver code public static void main(String args[]) { // Number of vertices int n = 6; GfG obj = new GfG(n); // Create the graph preprocessing(n); Graph.get(1).add(2); Graph.get(2).add(1); Graph.get(1).add(3); Graph.get(3).add(1); Graph.get(2).add(4); Graph.get(4).add(2); Graph.get(2).add(5); Graph.get(5).add(2); Graph.get(3).add(6); Graph.get(6).add(3); int U = 4, V = 6, R = 2; if (isPresent(U, V, R)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }}", "e": 31913, "s": 28339, "text": null }, { "code": "# Python3 implementation of the approachimport math n = 6 # GraphGraph = [] # log(n) with base 2height = math.ceil(math.log10(n) / math.log10(2))table = [[-1 for i in range(n + 1)] for j in range(n + 1)] # Fill the graph with empty listsfor i in range(n + 1): Graph.append([])timeIn = [0]*(n + 1)timeOut = [0]*(n + 1)time = 0 # Filling with -1 as initialdef preprocessing(n): for i in range(n + 1): for j in range(height + 1): table[i][j] = -1 # Dfs for pre-processing sparse table and# calculating start and end timedef dfs(s, p): global time # Parent at 1 node distance is always # it's direct parent table[s][0] = p # Start time noted timeIn[s] = time+1 # Filling sparse table recursively for i in range(1, height + 1): table[s][i] = table[table[s][i - 1]][i - 1] # Traversing children of source for child in range(len(Graph[s])): if Graph[s][child] == p: continue dfs(Graph[s][child], s) # End time noted time+=1 timeOut[s] = time # Helper function to check lowest common Ancestordef check(u, v): return (timeIn[u] <= timeIn[v] and timeOut[u] >= timeOut[v]) # Function to return Lowest Common Ancestor of U and Vdef lowestCommonAncestor(U, V): if check(U, V): return U if check(V, U): return V for i in range(height, -1, -1): if not check(table[U][i], V): U = table[U][i] return table[U][0] # Function that return true if R# exists on the path between U# and V in the given treedef isPresent(U, V, R): # Dfs dfs(1, 1) # Calculating LCA between U and V LCA = lowestCommonAncestor(U, V) # Calculating LCA between U and R LCA_1 = lowestCommonAncestor(U, R) # Calculating LCA between U and V LCA_2 = lowestCommonAncestor(V, R) if LCA == R or (LCA_1 == LCA and LCA_2 == R) or (LCA_2 == LCA and LCA_1 == R): return True return False # Create the graphpreprocessing(n)Graph[1].append(2)Graph[2].append(1)Graph[1].append(3)Graph[3].append(1)Graph[2].append(4)Graph[4].append(2)Graph[2].append(5)Graph[5].append(2)Graph[3].append(6)Graph[6].append(3) U, V, R = 4, 6, 2if isPresent(U, V, R): print(\"Yes\")else: print(\"No\") # This code is contributed by suresh07.", "e": 34167, "s": 31913, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GfG{ // Table for storing 2^ith parent private static int [,]table; // Variable to store the height of the tree private static int height; // Graph private static List<List<int> > Graph; // Arrays to mark start and end time for a node private static int []timeIn; private static int []timeOut; // Timer private static int time; // Private constructor for initializing // the global variables private GfG(int n) { // log(n) with base 2 height = (int)Math.Ceiling(Math.Log10(n) / Math.Log10(2)); table = new int[n + 1, height + 1]; // Fill the graph with empty lists Graph = new List<List<int> >(); for (int i = 0; i <= n; i++) Graph.Add(new List<int>()); timeIn = new int[n + 1]; timeOut = new int[n + 1]; time = 0; } // Filling with -1 as initial private static void preprocessing(int n) { for (int i = 0; i < n + 1; i++) { for(int j = 0; j < height + 1; j++) table[i, j] = -1; } } // Dfs for pre-processing sparse table and // calculating start and end time private static void dfs(int s, int p) { // Parent at 1 node distance is always // it's direct parent table[s, 0] = p; // Start time noted timeIn[s] = ++time; // Filling sparse table recursively for (int i = 1; i <= height; i++) table[s, i] = table[table[s, i - 1], i - 1]; // Traversing children of source foreach (int child in Graph[s]) { if (child == p) continue; dfs(child, s); } // End time noted timeOut[s] = ++time; } // Helper function to check lowest common Ancestor private static bool check(int u, int v) { return timeIn[u] <= timeIn[v] && timeOut[u] >= timeOut[v]; } // Function to return Lowest Common Ancestor of U and V private static int lowestCommonAncestor(int U, int V) { if (check(U, V)) return U; if (check(V, U)) return V; for (int i = height; i >= 0; i--) { if (!check(table[U, i], V)) U = table[U, i]; } return table[U, 0]; } // Function that return true if R // exists on the path between U // and V in the given tree private static bool isPresent(int U, int V, int R) { // Dfs dfs(1, 1); // Calculating LCA between U and V int LCA = lowestCommonAncestor(U, V); // Calculating LCA between U and R int LCA_1 = lowestCommonAncestor(U, R); // Calculating LCA between U and V int LCA_2 = lowestCommonAncestor(V, R); if (LCA == R || (LCA_1 == LCA && LCA_2 == R) || (LCA_2 == LCA && LCA_1 == R)) { return true; } return false; } // Driver code public static void Main(String []args) { // Number of vertices int n = 6; GfG obj = new GfG(n); // Create the graph preprocessing(n); Graph[1].Add(2); Graph[2].Add(1); Graph[1].Add(3); Graph[3].Add(1); Graph[2].Add(4); Graph[4].Add(2); Graph[2].Add(5); Graph[5].Add(2); Graph[3].Add(6); Graph[6].Add(3); int U = 4, V = 6, R = 2; if (isPresent(U, V, R)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by PrinciRaj1992", "e": 37794, "s": 34167, "text": null }, { "code": "<script> // JavaScript implementation of the approach let n = 6; // Table for storing 2^ith parent let table; // Variable to store the height of the tree let height; // Graph let Graph = []; // Arrays to mark start and end time for a node let timeIn; let timeOut; // Timer let time; // log(n) with base 2 height = Math.ceil(Math.log10(n) / Math.log10(2)); table = new Array(n + 1); // Fill the graph with empty lists for (let i = 0; i <= n; i++) Graph.push([]); timeIn = new Array(n + 1); timeOut = new Array(n + 1); time = 0; // Filling with -1 as initial function preprocessing(n) { for (let i = 0; i < n + 1; i++) { table[i] = new Array(height + 1); for(let j = 0; j < height + 1; j++) { table[i][j] = -1; } } } // Dfs for pre-processing sparse table and // calculating start and end time function dfs(s, p) { // Parent at 1 node distance is always // it's direct parent table[s][0] = p; // Start time noted timeIn[s] = ++time; // Filling sparse table recursively for (let i = 1; i <= height; i++) table[s][i] = table[table[s][i - 1]][i - 1]; // Traversing children of source for (let child = 0; child < Graph[s].length; child++) { if (Graph[s][child] == p) continue; dfs(Graph[s][child], s); } // End time noted timeOut[s] = ++time; } // Helper function to check lowest common Ancestor function check(u, v) { return timeIn[u] <= timeIn[v] && timeOut[u] >= timeOut[v]; } // Function to return Lowest Common Ancestor of U and V function lowestCommonAncestor(U, V) { if (check(U, V)) return U; if (check(V, U)) return V; for (let i = height; i >= 0; i--) { if (!check(table[U][i], V)) U = table[U][i]; } return table[U][0]; } // Function that return true if R // exists on the path between U // and V in the given tree function isPresent(U, V, R) { // Dfs dfs(1, 1); // Calculating LCA between U and V let LCA = lowestCommonAncestor(U, V); // Calculating LCA between U and R let LCA_1 = lowestCommonAncestor(U, R); // Calculating LCA between U and V let LCA_2 = lowestCommonAncestor(V, R); if (LCA == R || (LCA_1 == LCA && LCA_2 == R) || (LCA_2 == LCA && LCA_1 == R)) { return true; } return false; } // Create the graph preprocessing(n); Graph[1].push(2); Graph[2].push(1); Graph[1].push(3); Graph[3].push(1); Graph[2].push(4); Graph[4].push(2); Graph[2].push(5); Graph[5].push(2); Graph[3].push(6); Graph[6].push(3); let U = 4, V = 6, R = 2; if (isPresent(U, V, R)) document.write(\"Yes\"); else document.write(\"No\"); </script>", "e": 40869, "s": 37794, "text": null }, { "code": null, "e": 40876, "s": 40872, "text": "Yes" }, { "code": null, "e": 41002, "s": 40880, "text": "Time Complexity: O(NlogN) for pre-processing and logN for finding the lowest common ancestor.Auxiliary Space: O(NlogN). " }, { "code": null, "e": 41018, "s": 41004, "text": "princiraj1992" }, { "code": null, "e": 41030, "s": 41018, "text": "sanjeev2552" }, { "code": null, "e": 41045, "s": 41030, "text": "rameshtravel07" }, { "code": null, "e": 41060, "s": 41045, "text": "sagar0719kumar" }, { "code": null, "e": 41076, "s": 41060, "text": "pankajsharmagfg" }, { "code": null, "e": 41092, "s": 41076, "text": "rajeev0719singh" }, { "code": null, "e": 41119, "s": 41092, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 41128, "s": 41119, "text": "suresh07" }, { "code": null, "e": 41140, "s": 41128, "text": "Binary Tree" }, { "code": null, "e": 41144, "s": 41140, "text": "LCA" }, { "code": null, "e": 41160, "s": 41144, "text": "Data Structures" }, { "code": null, "e": 41180, "s": 41160, "text": "Dynamic Programming" }, { "code": null, "e": 41190, "s": 41180, "text": "Recursion" }, { "code": null, "e": 41195, "s": 41190, "text": "Tree" }, { "code": null, "e": 41211, "s": 41195, "text": "Data Structures" }, { "code": null, "e": 41231, "s": 41211, "text": "Dynamic Programming" }, { "code": null, "e": 41241, "s": 41231, "text": "Recursion" }, { "code": null, "e": 41246, "s": 41241, "text": "Tree" }, { "code": null, "e": 41344, "s": 41246, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41353, "s": 41344, "text": "Comments" }, { "code": null, "e": 41366, "s": 41353, "text": "Old Comments" }, { "code": null, "e": 41402, "s": 41366, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 41461, "s": 41402, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 41482, "s": 41461, "text": "TCS NQT Coding Sheet" }, { "code": null, "e": 41530, "s": 41482, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 41614, "s": 41530, "text": "Building an undirected graph and finding shortest path using Dictionaries in Python" }, { "code": null, "e": 41643, "s": 41614, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 41673, "s": 41643, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 41705, "s": 41673, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 41739, "s": 41705, "text": "Longest Common Subsequence | DP-4" } ]
CouchDB - Attaching Files
You can attach files to CouchDB just like email. The file contains metadata like name and includes its MIME type, and the number of bytes the attachment contains. To attach files to a document you have to send PUT request to the server. Following is the syntax to attach files to the document − $ curl -vX PUT http://127.0.0.1:5984/database_name/database_id /filename?rev=document rev_id --data-binary @filename -H "Content-Type: type of the content" The request has various options that are explained below. --data-binary@ − This option tells cURL to read a file’s contents into the HTTP request body. --data-binary@ − This option tells cURL to read a file’s contents into the HTTP request body. -H − This option is used to mention the content type of the file we are going to upload. -H − This option is used to mention the content type of the file we are going to upload. Let us attach a file named boy.jpg, to the document with id 001, in the database named my_database by sending PUT request to CouchDB. Before that, you have to fetch the data of the document with id 001 to get its current rev id as shown below. $ curl -X GET http://127.0.0.1:5984/my_database/001 { "_id": "001", "_rev": "1-967a00dff5e02add41819138abb3284d" } Now using the _rev value, send the PUT request to the CouchDB server as shown below. $ curl -vX PUT http://127.0.0.1:5984/my_database/001/boy.jpg?rev=1- 967a00dff5e02add41819138abb3284d --data-binary @boy.jpg -H "ContentType: image/jpg" To verify whether the attachment is uploaded, fetch the document content as shown below− $ curl -X GET http://127.0.0.1:5984/my_database/001 { "_id": "001", "_rev": "2-4705a219cdcca7c72aac4f623f5c46a8", "_attachments": { "boy.jpg": { "content_type": "image/jpg", "revpos": 2, "digest": "md5-9Swz8jvmga5mfBIsmCxCtQ==", "length": 91408, "stub": true } } } Using this option, you can upload a new attachment such as a file, image, or document, to the database. To do so, click on the Upload Attachment button. A dialog box will appear where you can choose the file to be uploaded. Select the file and click on the Upload button. The file uploaded will be displayed under _attachments field. Later you can see the file by clicking on it. Print Add Notes Bookmark this page
[ { "code": null, "e": 2133, "s": 1838, "text": "You can attach files to CouchDB just like email. The file contains metadata like name and includes its MIME type, and the number of bytes the attachment contains. To attach files to a document you have to send PUT request to the server. Following is the syntax to attach files to the document −" }, { "code": null, "e": 2289, "s": 2133, "text": "$ curl -vX PUT http://127.0.0.1:5984/database_name/database_id\n/filename?rev=document rev_id --data-binary @filename -H \"Content-Type:\ntype of the content\"" }, { "code": null, "e": 2347, "s": 2289, "text": "The request has various options that are explained below." }, { "code": null, "e": 2441, "s": 2347, "text": "--data-binary@ − This option tells cURL to read a file’s contents into the HTTP request body." }, { "code": null, "e": 2535, "s": 2441, "text": "--data-binary@ − This option tells cURL to read a file’s contents into the HTTP request body." }, { "code": null, "e": 2624, "s": 2535, "text": "-H − This option is used to mention the content type of the file we are going to upload." }, { "code": null, "e": 2713, "s": 2624, "text": "-H − This option is used to mention the content type of the file we are going to upload." }, { "code": null, "e": 2957, "s": 2713, "text": "Let us attach a file named boy.jpg, to the document with id 001, in the database named my_database by sending PUT request to CouchDB. Before that, you have to fetch the data of the document with id 001 to get its current rev id as shown below." }, { "code": null, "e": 3078, "s": 2957, "text": "$ curl -X GET http://127.0.0.1:5984/my_database/001\n{\n \"_id\": \"001\",\n \"_rev\": \"1-967a00dff5e02add41819138abb3284d\"\n}" }, { "code": null, "e": 3163, "s": 3078, "text": "Now using the _rev value, send the PUT request to the CouchDB server as shown below." }, { "code": null, "e": 3315, "s": 3163, "text": "$ curl -vX PUT http://127.0.0.1:5984/my_database/001/boy.jpg?rev=1-\n967a00dff5e02add41819138abb3284d --data-binary @boy.jpg -H \"ContentType:\nimage/jpg\"" }, { "code": null, "e": 3404, "s": 3315, "text": "To verify whether the attachment is uploaded, fetch the document content as shown below−" }, { "code": null, "e": 3739, "s": 3404, "text": "$ curl -X GET http://127.0.0.1:5984/my_database/001\n{\n \"_id\": \"001\",\n \"_rev\": \"2-4705a219cdcca7c72aac4f623f5c46a8\",\n \"_attachments\": {\n \"boy.jpg\": {\n \"content_type\": \"image/jpg\",\n \"revpos\": 2,\n \"digest\": \"md5-9Swz8jvmga5mfBIsmCxCtQ==\",\n \"length\": 91408,\n \"stub\": true\n }\n }\n}\n" }, { "code": null, "e": 4011, "s": 3739, "text": "Using this option, you can upload a new attachment such as a file, image, or document, to the database. To do so, click on the Upload Attachment button. A dialog box will appear where you can choose the file to be uploaded. Select the file and click on the Upload button." }, { "code": null, "e": 4119, "s": 4011, "text": "The file uploaded will be displayed under _attachments field. Later you can see the file by clicking on it." }, { "code": null, "e": 4126, "s": 4119, "text": " Print" }, { "code": null, "e": 4137, "s": 4126, "text": " Add Notes" } ]
How to get all children of a process using Process API in Java 9?
Process handling classes and related API have been introduced in Java 9. We can use the ProcessHandle interface and related methods to get pid and information about other related processes. We need to get all children of a process, then use java.lang.ProcessHandle.children() method. This method returns a stream, typically a process that has no children. In the below example, we can get the first process and retrieve its children's process information. import java.util.stream.Stream; import java.util.Optional; public class ChilderenProcessTest { public static void main(String args[]) throws InterruptedException { System.out.println("---------------------------"); System.out.println("Children Processes:"); Optional<ProcessHandle> processHandle = ProcessHandle.allProcesses().findFirst(); processHandle.ifPresent(proc -> proc.children().forEach(child -> System.out.println("PID: [ " + child.pid() + " ], Cmd: [ " + child.info().command() + " ]"))); } } --------------------------- Children Processes: PID: [ 0 ], Cmd: [ Optional.empty ] PID: [ 4 ], Cmd: [ Optional.empty ] PID: [ 424 ], Cmd: [ Optional.empty ] PID: [ 504 ], Cmd: [ Optional.empty ] PID: [ 560 ], Cmd: [ Optional.empty ] PID: [ 444 ], Cmd: [ Optional.empty ] PID: [ 1236 ], Cmd: [ Optional.empty ] PID: [ 1288 ], Cmd: [ Optional.empty ] PID: [ 1408 ], Cmd: [ Optional.empty ] PID: [ 1424 ], Cmd: [ Optional.empty ] PID: [ 1452 ], Cmd: [ Optional.empty ] PID: [ 1468 ], Cmd: [ Optional.empty ] PID: [ 5412 ], Cmd: [ Optional[C:\WINDOWS\System32\taskhostex.exe] ] PID: [ 3760 ], Cmd: [ Optional[C:\Program Files\Synaptics\SynTP\SynTPEnh.exe] ] PID: [ 5216 ], Cmd: [ Optional[C:\WINDOWS\explorer.exe] ] PID: [ 2460 ], Cmd: [ Optional[C:\Program Files (x86)\Dell Wireless\Bluetooth Suite\BtvStack.exe] ] PID: [ 6064 ], Cmd: [ Optional[C:\Program Files\Realtek\Audio\HDA\RtkNGUI64.exe] ] PID: [ 7172 ], Cmd: [ Optional[C:\Program Files (x86)\Google\Chrome\Application\chrome.exe] ] PID: [ 860 ], Cmd: [ Optional[C:\Program Files (x86)\Google\Chrome\Application\chrome.exe] ] PID: [ 9000 ], Cmd: [ Optional.empty ] PID: [ 4180 ], Cmd: [ Optional[C:\WINDOWS\System32\cmd.exe] ] PID: [ 3748 ], Cmd: [ Optional[C:\WINDOWS\System32\conhost.exe] ] PID: [ 3376 ], Cmd: [ Optional.empty ] PID: [ 2548 ], Cmd: [ Optional.empty ] PID: [ 1820 ], Cmd: [ Optional[C:\Program Files\Java\jdk-9.0.4\bin\java.exe] ]
[ { "code": null, "e": 1418, "s": 1062, "text": "Process handling classes and related API have been introduced in Java 9. We can use the ProcessHandle interface and related methods to get pid and information about other related processes. We need to get all children of a process, then use java.lang.ProcessHandle.children() method. This method returns a stream, typically a process that has no children." }, { "code": null, "e": 1518, "s": 1418, "text": "In the below example, we can get the first process and retrieve its children's process information." }, { "code": null, "e": 2053, "s": 1518, "text": "import java.util.stream.Stream;\nimport java.util.Optional;\n\npublic class ChilderenProcessTest {\n public static void main(String args[]) throws InterruptedException {\n System.out.println(\"---------------------------\");\n System.out.println(\"Children Processes:\");\n Optional<ProcessHandle> processHandle = ProcessHandle.allProcesses().findFirst();\n processHandle.ifPresent(proc -> proc.children().forEach(child -> System.out.println(\"PID: [ \" + child.pid() + \" ], Cmd: [ \" + child.info().command() + \" ]\")));\n }\n}" }, { "code": null, "e": 3460, "s": 2053, "text": "---------------------------\nChildren Processes:\nPID: [ 0 ], Cmd: [ Optional.empty ]\nPID: [ 4 ], Cmd: [ Optional.empty ]\nPID: [ 424 ], Cmd: [ Optional.empty ]\nPID: [ 504 ], Cmd: [ Optional.empty ]\nPID: [ 560 ], Cmd: [ Optional.empty ]\nPID: [ 444 ], Cmd: [ Optional.empty ]\nPID: [ 1236 ], Cmd: [ Optional.empty ]\nPID: [ 1288 ], Cmd: [ Optional.empty ]\nPID: [ 1408 ], Cmd: [ Optional.empty ]\nPID: [ 1424 ], Cmd: [ Optional.empty ]\nPID: [ 1452 ], Cmd: [ Optional.empty ]\nPID: [ 1468 ], Cmd: [ Optional.empty ]\nPID: [ 5412 ], Cmd: [ Optional[C:\\WINDOWS\\System32\\taskhostex.exe] ]\nPID: [ 3760 ], Cmd: [ Optional[C:\\Program Files\\Synaptics\\SynTP\\SynTPEnh.exe] ]\nPID: [ 5216 ], Cmd: [ Optional[C:\\WINDOWS\\explorer.exe] ]\nPID: [ 2460 ], Cmd: [ Optional[C:\\Program Files (x86)\\Dell Wireless\\Bluetooth Suite\\BtvStack.exe] ]\nPID: [ 6064 ], Cmd: [ Optional[C:\\Program Files\\Realtek\\Audio\\HDA\\RtkNGUI64.exe] ]\nPID: [ 7172 ], Cmd: [ Optional[C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe] ]\nPID: [ 860 ], Cmd: [ Optional[C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe] ]\nPID: [ 9000 ], Cmd: [ Optional.empty ]\nPID: [ 4180 ], Cmd: [ Optional[C:\\WINDOWS\\System32\\cmd.exe] ]\nPID: [ 3748 ], Cmd: [ Optional[C:\\WINDOWS\\System32\\conhost.exe] ]\nPID: [ 3376 ], Cmd: [ Optional.empty ]\nPID: [ 2548 ], Cmd: [ Optional.empty ]\nPID: [ 1820 ], Cmd: [ Optional[C:\\Program Files\\Java\\jdk-9.0.4\\bin\\java.exe] ]" } ]
Decision Trees — A Bird’s eye view and an Implementation | by Vishal R | Towards Data Science
This article is being moved to my Substack Publication. You can read the article for free here. This post will be deleted on 18th May 2022. The following are achieved in this dataset Understanding the definition of Decision Trees Implementation Loading the data Visualizing the data using a correlation matrix and a pair plot Building a Decision Tree Classifier Determining the accuracy of the model using a confusion matrix Visualizing the Decision tree as a flow chart A decision tree is a flowchart-like structure in which each internal node represents a “test” on an attribute (e.g. whether a coin flip comes up heads or tails), each branch represents the outcome of the test, and each leaf node represents a class label (decision taken after computing all attributes). (Source: Wikipedia) In simpler terms, a decision tree checks if an attribute or a set of attributes satisfy a condition and based on the result of the check, the subsequent checks are performed. The tree splits the data into different parts based these checks. import pandas as pdimport numpy as npfrom sklearn.preprocessing import StandardScalerimport tflearn.data_utils as dufrom sklearn.tree import DecisionTreeClassifierfrom sklearn.model_selection import train_test_splitimport seaborn as snsfrom sklearn.metrics import confusion_matrixfrom sklearn.externals.six import StringIO from IPython.display import Image from sklearn.tree import export_graphvizimport pydotplus data = pd.read_csv('../input/column_3C_weka.csv') The dataset used here is the Biomechanical features of orthopedic patients Correlation is a statistical term which in common usage refers to how close two variables are to having a linear relationship with each other. For example, two variable which are linearly dependent (say, x and y which depend on each other as x = 2y) will have a higher correlation than two variables which are non-linearly dependent (say, u and v which depend on each other as u = sqr(v)) # Calculating the correlation matrixcorr = data.corr()# Generating a heatmapsns.heatmap(corr,xticklabels=corr.columns, yticklabels=corr.columns) sns.pairplot(data) In the above two plots you can clearly see that the pairs of independent variables with a higher correlation have a more linear scatter plot than the independent variables having a relatively lesser correlation x = data.iloc[:,:6].valuesy = data.iloc[:,6].values The train data to train the model and the test data to validate the model’s performance x_train , x_test, y_train, y_test = train_test_split(x, y, test_size = 0.25, random_state = 0) This question on stackoverflow has responses which gives a brief explanation on why scaling is necessary and how it can affect the model sc = StandardScaler()x_train = sc.fit_transform(x_train)x_test = sc.transform(x_test) The criterion here is entropy. The criterion parameter determines the function to measure the quality of a split. When the entropy is used as a criterion, each split tries to reduce the randomness in that part of the data. There are lot of parameters in the Decision Tree Class that you can tweak to improve your results. There we take a peak into the max_depth parameter. The max_dept the determines how deep a tree can go. The affect of this parameter on the model will be discusses later in this article classifier = DecisionTreeClassifier(criterion = 'entropy', max_depth = 4)classifier.fit(x_train, y_train) y_pred = classifier.predict(x_test) A confusion matrix is a technique for summarizing the performance of a classification algorithm. Classification accuracy alone can be misleading if you have an unequal number of observations in each class or if you have more than two classes in your dataset. Calculating a confusion matrix can give you a better idea of what your classification model is getting right and what types of errors it is making. Source cm = confusion_matrix(y_test, y_pred)accuracy = sum(cm[i][i] for i in range(3)) / y_test.shape[0]print("accuracy = " + str(accuracy)) dot_data = StringIO()export_graphviz(classifier, out_file=dot_data, filled=True, rounded=True, special_characters=True)graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) Image(graph.create_png()) classifier2 = DecisionTreeClassifier(criterion = 'entropy')classifier2.fit(x_train, y_train)y_pred2 = classifier2.predict(x_test)cm2 = confusion_matrix(y_test, y_pred2)accuracy2 = sum(cm2[i][i] for i in range(3)) / y_test.shape[0]print("accuracy = " + str(accuracy2)) dot_data = StringIO()export_graphviz(classifier2, out_file=dot_data, filled=True, rounded=True, special_characters=True)graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) Image(graph.create_png()) Now, consider the leaf nodes (terminal nodes) of the tree with and without the max_depth parameter. You will notice that the entropy all the terminal nodes are zero in the tree without the max_depth parameter and non zero in three with that parameter. This is because when the parameter is not mentioned, the split recursively takes place till the terminal node has an entropy of zero. To know more about the different parameters of the sklearn.tree.DecisionTreeClassifier, click here To get this article as a iPython Notebook, click here
[ { "code": null, "e": 312, "s": 172, "text": "This article is being moved to my Substack Publication. You can read the article for free here. This post will be deleted on 18th May 2022." }, { "code": null, "e": 355, "s": 312, "text": "The following are achieved in this dataset" }, { "code": null, "e": 402, "s": 355, "text": "Understanding the definition of Decision Trees" }, { "code": null, "e": 417, "s": 402, "text": "Implementation" }, { "code": null, "e": 434, "s": 417, "text": "Loading the data" }, { "code": null, "e": 498, "s": 434, "text": "Visualizing the data using a correlation matrix and a pair plot" }, { "code": null, "e": 534, "s": 498, "text": "Building a Decision Tree Classifier" }, { "code": null, "e": 597, "s": 534, "text": "Determining the accuracy of the model using a confusion matrix" }, { "code": null, "e": 643, "s": 597, "text": "Visualizing the Decision tree as a flow chart" }, { "code": null, "e": 946, "s": 643, "text": "A decision tree is a flowchart-like structure in which each internal node represents a “test” on an attribute (e.g. whether a coin flip comes up heads or tails), each branch represents the outcome of the test, and each leaf node represents a class label (decision taken after computing all attributes)." }, { "code": null, "e": 966, "s": 946, "text": "(Source: Wikipedia)" }, { "code": null, "e": 1207, "s": 966, "text": "In simpler terms, a decision tree checks if an attribute or a set of attributes satisfy a condition and based on the result of the check, the subsequent checks are performed. The tree splits the data into different parts based these checks." }, { "code": null, "e": 1623, "s": 1207, "text": "import pandas as pdimport numpy as npfrom sklearn.preprocessing import StandardScalerimport tflearn.data_utils as dufrom sklearn.tree import DecisionTreeClassifierfrom sklearn.model_selection import train_test_splitimport seaborn as snsfrom sklearn.metrics import confusion_matrixfrom sklearn.externals.six import StringIO from IPython.display import Image from sklearn.tree import export_graphvizimport pydotplus" }, { "code": null, "e": 1673, "s": 1623, "text": "data = pd.read_csv('../input/column_3C_weka.csv')" }, { "code": null, "e": 1748, "s": 1673, "text": "The dataset used here is the Biomechanical features of orthopedic patients" }, { "code": null, "e": 1891, "s": 1748, "text": "Correlation is a statistical term which in common usage refers to how close two variables are to having a linear relationship with each other." }, { "code": null, "e": 2137, "s": 1891, "text": "For example, two variable which are linearly dependent (say, x and y which depend on each other as x = 2y) will have a higher correlation than two variables which are non-linearly dependent (say, u and v which depend on each other as u = sqr(v))" }, { "code": null, "e": 2282, "s": 2137, "text": "# Calculating the correlation matrixcorr = data.corr()# Generating a heatmapsns.heatmap(corr,xticklabels=corr.columns, yticklabels=corr.columns)" }, { "code": null, "e": 2301, "s": 2282, "text": "sns.pairplot(data)" }, { "code": null, "e": 2512, "s": 2301, "text": "In the above two plots you can clearly see that the pairs of independent variables with a higher correlation have a more linear scatter plot than the independent variables having a relatively lesser correlation" }, { "code": null, "e": 2564, "s": 2512, "text": "x = data.iloc[:,:6].valuesy = data.iloc[:,6].values" }, { "code": null, "e": 2652, "s": 2564, "text": "The train data to train the model and the test data to validate the model’s performance" }, { "code": null, "e": 2747, "s": 2652, "text": "x_train , x_test, y_train, y_test = train_test_split(x, y, test_size = 0.25, random_state = 0)" }, { "code": null, "e": 2884, "s": 2747, "text": "This question on stackoverflow has responses which gives a brief explanation on why scaling is necessary and how it can affect the model" }, { "code": null, "e": 2970, "s": 2884, "text": "sc = StandardScaler()x_train = sc.fit_transform(x_train)x_test = sc.transform(x_test)" }, { "code": null, "e": 3193, "s": 2970, "text": "The criterion here is entropy. The criterion parameter determines the function to measure the quality of a split. When the entropy is used as a criterion, each split tries to reduce the randomness in that part of the data." }, { "code": null, "e": 3343, "s": 3193, "text": "There are lot of parameters in the Decision Tree Class that you can tweak to improve your results. There we take a peak into the max_depth parameter." }, { "code": null, "e": 3477, "s": 3343, "text": "The max_dept the determines how deep a tree can go. The affect of this parameter on the model will be discusses later in this article" }, { "code": null, "e": 3583, "s": 3477, "text": "classifier = DecisionTreeClassifier(criterion = 'entropy', max_depth = 4)classifier.fit(x_train, y_train)" }, { "code": null, "e": 3619, "s": 3583, "text": "y_pred = classifier.predict(x_test)" }, { "code": null, "e": 4026, "s": 3619, "text": "A confusion matrix is a technique for summarizing the performance of a classification algorithm. Classification accuracy alone can be misleading if you have an unequal number of observations in each class or if you have more than two classes in your dataset. Calculating a confusion matrix can give you a better idea of what your classification model is getting right and what types of errors it is making." }, { "code": null, "e": 4033, "s": 4026, "text": "Source" }, { "code": null, "e": 4167, "s": 4033, "text": "cm = confusion_matrix(y_test, y_pred)accuracy = sum(cm[i][i] for i in range(3)) / y_test.shape[0]print(\"accuracy = \" + str(accuracy))" }, { "code": null, "e": 4404, "s": 4167, "text": "dot_data = StringIO()export_graphviz(classifier, out_file=dot_data, filled=True, rounded=True, special_characters=True)graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) Image(graph.create_png())" }, { "code": null, "e": 4672, "s": 4404, "text": "classifier2 = DecisionTreeClassifier(criterion = 'entropy')classifier2.fit(x_train, y_train)y_pred2 = classifier2.predict(x_test)cm2 = confusion_matrix(y_test, y_pred2)accuracy2 = sum(cm2[i][i] for i in range(3)) / y_test.shape[0]print(\"accuracy = \" + str(accuracy2))" }, { "code": null, "e": 4910, "s": 4672, "text": "dot_data = StringIO()export_graphviz(classifier2, out_file=dot_data, filled=True, rounded=True, special_characters=True)graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) Image(graph.create_png())" }, { "code": null, "e": 5296, "s": 4910, "text": "Now, consider the leaf nodes (terminal nodes) of the tree with and without the max_depth parameter. You will notice that the entropy all the terminal nodes are zero in the tree without the max_depth parameter and non zero in three with that parameter. This is because when the parameter is not mentioned, the split recursively takes place till the terminal node has an entropy of zero." }, { "code": null, "e": 5395, "s": 5296, "text": "To know more about the different parameters of the sklearn.tree.DecisionTreeClassifier, click here" } ]
How to get the ip address in C#?
IP (Internet Protocol) Address is an address of your network hardware. It helps in connecting your computer to other devices on your network and all over the world. An IP Address is made up of numbers or characters. All devices that are connected to an internet connection have a unique IP address which means there’s a need of billions of IP addresses. This requirement is fulfilled by the new IP version IPv6. Private IP Address A private IP address is the address of your device connected on the home or business network. If you have a few different devices connected to one ISP (Internet Service Provider), then all your devices will have a unique private IP address. This IP address cannot be accessed from devices outside your home or business network. For example: 192.168.1.1 class Program{ static void Main(string[] args){ string IPAddress = GetIPAddress(); System.Console.WriteLine(IPAddress); Console.ReadLine(); } public static string GetIPAddress(){ string IPAddress = string.Empty; IPHostEntry Host = default(IPHostEntry); string Hostname = null; Hostname = System.Environment.MachineName; Host = Dns.GetHostEntry(Hostname); foreach (IPAddress IP in Host.AddressList){ if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork){ IPAddress = Convert.ToString(IP); } } return IPAddress; } } 192.168.1.1
[ { "code": null, "e": 1278, "s": 1062, "text": "IP (Internet Protocol) Address is an address of your network hardware.\nIt helps in connecting your computer to other devices on your network and all over the world. An IP Address is made up of numbers or characters." }, { "code": null, "e": 1474, "s": 1278, "text": "All devices that are connected to an internet connection have a unique IP address which means there’s a need of billions of IP addresses.\nThis requirement is fulfilled by the new IP version IPv6." }, { "code": null, "e": 1493, "s": 1474, "text": "Private IP Address" }, { "code": null, "e": 1821, "s": 1493, "text": "A private IP address is the address of your device connected on the home or business network. If you have a few different devices connected to one ISP (Internet Service Provider), then all your devices will have a unique private IP address. This IP address cannot be accessed from devices outside your home or business network." }, { "code": null, "e": 1846, "s": 1821, "text": "For example: 192.168.1.1" }, { "code": null, "e": 2485, "s": 1846, "text": "class Program{\n static void Main(string[] args){\n string IPAddress = GetIPAddress();\n System.Console.WriteLine(IPAddress);\n Console.ReadLine();\n }\n public static string GetIPAddress(){\n string IPAddress = string.Empty;\n IPHostEntry Host = default(IPHostEntry);\n string Hostname = null;\n Hostname = System.Environment.MachineName;\n Host = Dns.GetHostEntry(Hostname);\n foreach (IPAddress IP in Host.AddressList){\n if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork){\n IPAddress = Convert.ToString(IP);\n }\n }\n return IPAddress;\n }\n}" }, { "code": null, "e": 2497, "s": 2485, "text": "192.168.1.1" } ]
Ionic - Javascript Keyboard
Keyboard is one of the automated features in Ionic. This means that Ionic can recognize when there is a need to open the keyboard. There are some functionalities, which the developers can adjust while working with the Ionic keyboard. When you want to hide some elements while the keyboard is open, you can use the hide-on-keyboard-open class. To show you how this works we created input and button that needs to be hidden when the keyboard is open. <label class = "item item-input"> <input type = "text" placeholder = "Input 1"> </label> <button class = "button button-block hide-on-keyboard-open"> button </button> The above code will produce the following screen − Now, when we tap on the input field, the keyboard will open automatically and the button will become hidden. A nice feature of Ionic is that it will adjust elements on screen, so the focused element is always visible when the keyboard is open. The following image below shows ten Input forms and the last one is blue. When we tap the blue form, Ionic will adjust our screen, so the blue form is always visible. Note − This will work only if the screen is within a directive that has a Scroll View. If you start with one of the Ionic templates, you will notice that all templates use ion-content directive as a container to other screen elements, so the Scroll View is always applied. 16 Lectures 2.5 hours Frahaan Hussain 185 Lectures 46.5 hours Nikhil Agarwal Print Add Notes Bookmark this page
[ { "code": null, "e": 2594, "s": 2463, "text": "Keyboard is one of the automated features in Ionic. This means that Ionic can recognize when there is a need to open the keyboard." }, { "code": null, "e": 2912, "s": 2594, "text": "There are some functionalities, which the developers can adjust while working with the Ionic keyboard. When you want to hide some elements while the keyboard is open, you can use the hide-on-keyboard-open class. To show you how this works we created input and button that needs to be hidden when the keyboard is open." }, { "code": null, "e": 3086, "s": 2912, "text": "<label class = \"item item-input\">\n <input type = \"text\" placeholder = \"Input 1\">\n</label>\n\n<button class = \"button button-block hide-on-keyboard-open\">\n button\n</button>" }, { "code": null, "e": 3137, "s": 3086, "text": "The above code will produce the following screen −" }, { "code": null, "e": 3246, "s": 3137, "text": "Now, when we tap on the input field, the keyboard will open automatically and the button will become hidden." }, { "code": null, "e": 3455, "s": 3246, "text": "A nice feature of Ionic is that it will adjust elements on screen, so the focused element is always visible when the keyboard is open. The following image below shows ten Input forms and the last one is blue." }, { "code": null, "e": 3548, "s": 3455, "text": "When we tap the blue form, Ionic will adjust our screen, so the blue form is always visible." }, { "code": null, "e": 3821, "s": 3548, "text": "Note − This will work only if the screen is within a directive that has a Scroll View. If you start with one of the Ionic templates, you will notice that all templates use ion-content directive as a container to other screen elements, so the Scroll View is always applied." }, { "code": null, "e": 3856, "s": 3821, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3873, "s": 3856, "text": " Frahaan Hussain" }, { "code": null, "e": 3910, "s": 3873, "text": "\n 185 Lectures \n 46.5 hours \n" }, { "code": null, "e": 3926, "s": 3910, "text": " Nikhil Agarwal" }, { "code": null, "e": 3933, "s": 3926, "text": " Print" }, { "code": null, "e": 3944, "s": 3933, "text": " Add Notes" } ]
Tryit Editor v3.6 - Show C++
using namespace std; ​ int main() { int x, y; int sum; cout << "Type a number: "; cin >> x; cout << "Type another number: "; cin >> y; sum = x + y;
[ { "code": null, "e": 41, "s": 20, "text": "using namespace std;" }, { "code": null, "e": 43, "s": 41, "text": "​" }, { "code": null, "e": 56, "s": 43, "text": "int main() {" }, { "code": null, "e": 68, "s": 56, "text": " int x, y;" }, { "code": null, "e": 79, "s": 68, "text": " int sum;" }, { "code": null, "e": 108, "s": 79, "text": " cout << \"Type a number: \";" }, { "code": null, "e": 120, "s": 108, "text": " cin >> x;" }, { "code": null, "e": 155, "s": 120, "text": " cout << \"Type another number: \";" }, { "code": null, "e": 167, "s": 155, "text": " cin >> y;" } ]
Evaluate Postfix Expression
For solving a mathematical expression, we need prefix or postfix form. After converting infix to postfix, we need postfix evaluation algorithm to find the correct answer. Here also we have to use the stack data structure to solve the postfix expressions. From the postfix expression, when some operands are found, pushed them in the stack. When some operator is found, two items are popped from the stack and the operation is performed in correct sequence. After that, the result is also pushed in the stack for future use. After completing the whole expression, the final result is also stored in the stack top. Input: Postfix expression: 53+62/*35*+ Output: The result is: 39 postfixEvaluation(postfix) Input: Postfix expression to evaluate. Output: Answer after evaluating postfix form. Begin for each character ch in the postfix expression, do if ch is an operator ⨀ , then a := pop first element from stack b := pop second element from the stack res := b ⨀ a push res into the stack else if ch is an operand, then add ch into the stack done return element of stack top End #include<iostream> #include<cmath> #include<stack> using namespace std; float scanNum(char ch) { int value; value = ch; return float(value-'0'); //return float from character } int isOperator(char ch) { if(ch == '+'|| ch == '-'|| ch == '*'|| ch == '/' || ch == '^') return 1; //character is an operator return -1; //not an operator } int isOperand(char ch) { if(ch >= '0' && ch <= '9') return 1; //character is an operand return -1; //not an operand } float operation(int a, int b, char op) { //Perform operation if(op == '+') return b+a; else if(op == '-') return b-a; else if(op == '*') return b*a; else if(op == '/') return b/a; else if(op == '^') return pow(b,a); //find b^a else return INT_MIN; //return negative infinity } float postfixEval(string postfix) { int a, b; stack<float> stk; string::iterator it; for(it=postfix.begin(); it!=postfix.end(); it++) { //read elements and perform postfix evaluation if(isOperator(*it) != -1) { a = stk.top(); stk.pop(); b = stk.top(); stk.pop(); stk.push(operation(a, b, *it)); }else if(isOperand(*it) > 0) { stk.push(scanNum(*it)); } } return stk.top(); } main() { string post = "53+62/*35*+"; cout << "The result is: "<<postfixEval(post); } The result is: 39
[ { "code": null, "e": 1233, "s": 1062, "text": "For solving a mathematical expression, we need prefix or postfix form. After converting infix to postfix, we need postfix evaluation algorithm to find the correct answer." }, { "code": null, "e": 1317, "s": 1233, "text": "Here also we have to use the stack data structure to solve the postfix expressions." }, { "code": null, "e": 1675, "s": 1317, "text": "From the postfix expression, when some operands are found, pushed them in the stack. When some operator is found, two items are popped from the stack and the operation is performed in correct sequence. After that, the result is also pushed in the stack for future use. After completing the whole expression, the final result is also stored in the stack top." }, { "code": null, "e": 1740, "s": 1675, "text": "Input:\nPostfix expression: 53+62/*35*+\nOutput:\nThe result is: 39" }, { "code": null, "e": 1767, "s": 1740, "text": "postfixEvaluation(postfix)" }, { "code": null, "e": 1806, "s": 1767, "text": "Input: Postfix expression to evaluate." }, { "code": null, "e": 1852, "s": 1806, "text": "Output: Answer after evaluating postfix form." }, { "code": null, "e": 2206, "s": 1852, "text": "Begin\n for each character ch in the postfix expression, do\n if ch is an operator ⨀ , then\n a := pop first element from stack\n b := pop second element from the stack\n res := b ⨀ a\n push res into the stack\n else if ch is an operand, then\n add ch into the stack\n done\n return element of stack top\nEnd" }, { "code": null, "e": 3612, "s": 2206, "text": "#include<iostream>\n#include<cmath>\n#include<stack>\nusing namespace std;\n\nfloat scanNum(char ch) {\n int value;\n value = ch;\n return float(value-'0'); //return float from character\n}\n\nint isOperator(char ch) {\n if(ch == '+'|| ch == '-'|| ch == '*'|| ch == '/' || ch == '^')\n return 1; //character is an operator\n return -1; //not an operator\n}\n\nint isOperand(char ch) {\n if(ch >= '0' && ch <= '9')\n return 1; //character is an operand\n return -1; //not an operand\n}\n\nfloat operation(int a, int b, char op) {\n //Perform operation\n if(op == '+')\n return b+a;\n else if(op == '-')\n return b-a;\n else if(op == '*')\n return b*a;\n else if(op == '/')\n return b/a;\n else if(op == '^')\n return pow(b,a); //find b^a\n else\n return INT_MIN; //return negative infinity\n}\n\nfloat postfixEval(string postfix) {\n int a, b;\n stack<float> stk;\n string::iterator it;\n\n for(it=postfix.begin(); it!=postfix.end(); it++) {\n //read elements and perform postfix evaluation\n if(isOperator(*it) != -1) {\n a = stk.top();\n stk.pop();\n b = stk.top();\n stk.pop();\n stk.push(operation(a, b, *it));\n }else if(isOperand(*it) > 0) {\n stk.push(scanNum(*it));\n }\n }\n return stk.top();\n}\n\nmain() {\n string post = \"53+62/*35*+\";\n cout << \"The result is: \"<<postfixEval(post);\n}" }, { "code": null, "e": 3630, "s": 3612, "text": "The result is: 39" } ]
Difference Between XML and HTML
In this post, we will understand the difference between HTML and XML. It refers to Hyper Text Markup Language. It refers to Hyper Text Markup Language. It helps create web pages and applications. It helps create web pages and applications. It is a markup language. It is a markup language. It helps create static pages as well. It helps create static pages as well. It helps display data. It helps display data. It doesn’t transport data. It doesn’t transport data. HyperText helps define link between multiple web pages. HyperText helps define link between multiple web pages. Markup Language helps define text document using tags, which gives a structure to the web page. Markup Language helps define text document using tags, which gives a structure to the web page. It helps annotate the text so that a system can understand it and use it. It helps annotate the text so that a system can understand it and use it. It ignores minor errors. It ignores minor errors. It is not case sensitive. It is not case sensitive. There are specific number of tags in HTML. There are specific number of tags in HTML. These tags are predefined. These tags are predefined. It doesn’t preserve white spaces. It doesn’t preserve white spaces. Closing tags are not a necessity. Closing tags are not a necessity. An example of HTML − <!DOCTYPE html> <html> <head> <title>My title</title> </head> <body> <h1>title</h1> <p>A sample</p> </body> </html> XML stands for ‘eXtensible Markup Language’. XML stands for ‘eXtensible Markup Language’. It is case sensitive. It is case sensitive. It doesn’t allow errors. It doesn’t allow errors. It helps provide a framework that would define markup languages. It helps provide a framework that would define markup languages. The tags are user defined. The tags are user defined. These tags are extensible. These tags are extensible. The white space can be preserved. The white space can be preserved. The tags help describe data. The tags help describe data. These tags aren’t used to display data. These tags aren’t used to display data. The closing tags are required. The closing tags are required. It helps create web pages and applications. It helps create web pages and applications. It is dynamic since it helps transport data. It is dynamic since it helps transport data. The design goals focus on simplicity, usability across internet. The design goals focus on simplicity, usability across internet. It supports Unicode. It supports Unicode. It can also be used to represent arbitrary data structures required for web services. It can also be used to represent arbitrary data structures required for web services. An example of XML − <?xml version = "1.0"?> <contactinfo> <address category = "type"> <name>Mark</name> <College>MIT</College> <mobile>6787878</mobile> </address> </contactinfo> Mark MIT 6787878
[ { "code": null, "e": 1132, "s": 1062, "text": "In this post, we will understand the difference between HTML and XML." }, { "code": null, "e": 1173, "s": 1132, "text": "It refers to Hyper Text Markup Language." }, { "code": null, "e": 1214, "s": 1173, "text": "It refers to Hyper Text Markup Language." }, { "code": null, "e": 1258, "s": 1214, "text": "It helps create web pages and applications." }, { "code": null, "e": 1302, "s": 1258, "text": "It helps create web pages and applications." }, { "code": null, "e": 1327, "s": 1302, "text": "It is a markup language." }, { "code": null, "e": 1352, "s": 1327, "text": "It is a markup language." }, { "code": null, "e": 1390, "s": 1352, "text": "It helps create static pages as well." }, { "code": null, "e": 1428, "s": 1390, "text": "It helps create static pages as well." }, { "code": null, "e": 1451, "s": 1428, "text": "It helps display data." }, { "code": null, "e": 1474, "s": 1451, "text": "It helps display data." }, { "code": null, "e": 1501, "s": 1474, "text": "It doesn’t transport data." }, { "code": null, "e": 1528, "s": 1501, "text": "It doesn’t transport data." }, { "code": null, "e": 1584, "s": 1528, "text": "HyperText helps define link between multiple web pages." }, { "code": null, "e": 1640, "s": 1584, "text": "HyperText helps define link between multiple web pages." }, { "code": null, "e": 1736, "s": 1640, "text": "Markup Language helps define text document using tags, which gives a structure to the web page." }, { "code": null, "e": 1832, "s": 1736, "text": "Markup Language helps define text document using tags, which gives a structure to the web page." }, { "code": null, "e": 1906, "s": 1832, "text": "It helps annotate the text so that a system can understand it and use it." }, { "code": null, "e": 1980, "s": 1906, "text": "It helps annotate the text so that a system can understand it and use it." }, { "code": null, "e": 2005, "s": 1980, "text": "It ignores minor errors." }, { "code": null, "e": 2030, "s": 2005, "text": "It ignores minor errors." }, { "code": null, "e": 2056, "s": 2030, "text": "It is not case sensitive." }, { "code": null, "e": 2082, "s": 2056, "text": "It is not case sensitive." }, { "code": null, "e": 2125, "s": 2082, "text": "There are specific number of tags in HTML." }, { "code": null, "e": 2168, "s": 2125, "text": "There are specific number of tags in HTML." }, { "code": null, "e": 2195, "s": 2168, "text": "These tags are predefined." }, { "code": null, "e": 2222, "s": 2195, "text": "These tags are predefined." }, { "code": null, "e": 2256, "s": 2222, "text": "It doesn’t preserve white spaces." }, { "code": null, "e": 2290, "s": 2256, "text": "It doesn’t preserve white spaces." }, { "code": null, "e": 2324, "s": 2290, "text": "Closing tags are not a necessity." }, { "code": null, "e": 2358, "s": 2324, "text": "Closing tags are not a necessity." }, { "code": null, "e": 2379, "s": 2358, "text": "An example of HTML −" }, { "code": null, "e": 2504, "s": 2379, "text": "<!DOCTYPE html>\n<html>\n<head>\n <title>My title</title>\n</head>\n<body>\n <h1>title</h1>\n <p>A sample</p>\n</body>\n</html>" }, { "code": null, "e": 2549, "s": 2504, "text": "XML stands for ‘eXtensible Markup Language’." }, { "code": null, "e": 2594, "s": 2549, "text": "XML stands for ‘eXtensible Markup Language’." }, { "code": null, "e": 2616, "s": 2594, "text": "It is case sensitive." }, { "code": null, "e": 2638, "s": 2616, "text": "It is case sensitive." }, { "code": null, "e": 2663, "s": 2638, "text": "It doesn’t allow errors." }, { "code": null, "e": 2688, "s": 2663, "text": "It doesn’t allow errors." }, { "code": null, "e": 2753, "s": 2688, "text": "It helps provide a framework that would define markup languages." }, { "code": null, "e": 2818, "s": 2753, "text": "It helps provide a framework that would define markup languages." }, { "code": null, "e": 2845, "s": 2818, "text": "The tags are user defined." }, { "code": null, "e": 2872, "s": 2845, "text": "The tags are user defined." }, { "code": null, "e": 2899, "s": 2872, "text": "These tags are extensible." }, { "code": null, "e": 2926, "s": 2899, "text": "These tags are extensible." }, { "code": null, "e": 2960, "s": 2926, "text": "The white space can be preserved." }, { "code": null, "e": 2994, "s": 2960, "text": "The white space can be preserved." }, { "code": null, "e": 3023, "s": 2994, "text": "The tags help describe data." }, { "code": null, "e": 3052, "s": 3023, "text": "The tags help describe data." }, { "code": null, "e": 3092, "s": 3052, "text": "These tags aren’t used to display data." }, { "code": null, "e": 3132, "s": 3092, "text": "These tags aren’t used to display data." }, { "code": null, "e": 3163, "s": 3132, "text": "The closing tags are required." }, { "code": null, "e": 3194, "s": 3163, "text": "The closing tags are required." }, { "code": null, "e": 3238, "s": 3194, "text": "It helps create web pages and applications." }, { "code": null, "e": 3282, "s": 3238, "text": "It helps create web pages and applications." }, { "code": null, "e": 3327, "s": 3282, "text": "It is dynamic since it helps transport data." }, { "code": null, "e": 3372, "s": 3327, "text": "It is dynamic since it helps transport data." }, { "code": null, "e": 3437, "s": 3372, "text": "The design goals focus on simplicity, usability across internet." }, { "code": null, "e": 3502, "s": 3437, "text": "The design goals focus on simplicity, usability across internet." }, { "code": null, "e": 3523, "s": 3502, "text": "It supports Unicode." }, { "code": null, "e": 3544, "s": 3523, "text": "It supports Unicode." }, { "code": null, "e": 3630, "s": 3544, "text": "It can also be used to represent arbitrary data structures required for web services." }, { "code": null, "e": 3716, "s": 3630, "text": "It can also be used to represent arbitrary data structures required for web services." }, { "code": null, "e": 3736, "s": 3716, "text": "An example of XML −" }, { "code": null, "e": 3918, "s": 3736, "text": "<?xml version = \"1.0\"?>\n<contactinfo>\n <address category = \"type\">\n <name>Mark</name>\n <College>MIT</College>\n <mobile>6787878</mobile>\n </address>\n</contactinfo>" }, { "code": null, "e": 3935, "s": 3918, "text": "Mark\nMIT\n6787878" } ]
Java program to verify whether a given element exists in an array.
You can find whether a particular exists in a given array using any of the search algorithms. Here, we will see examples for linear search and binary search. Iterate through the array. Compare each element with the required element. import java.util.Scanner; public class ArraySearch { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array that is to be created: "); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Enter the elements of the array: "); for(int i=0; i<size; i++){ myArray[i] = sc.nextInt(); } System.out.println("Enter the value tobe searched: "); int searchVal = sc.nextInt(); for (int i =0 ; i<myArray.length; i++) { if (myArray[i] == searchVal) { System.out.println("The index of element "+searchVal+" is : " + i); } } } } Enter the size of the array that is to be created: 5 Enter the elements of the array: 30 20 5 12 55 Enter the value to be searched: 12 The index of element 12 is : 3 The Arrays class of the java.util package provides a method with name binarySearch(), this method accepts a sorted array and a value to search and returns the index of the given element in the array. import java.util.Arrays; import java.util.Scanner; public class ArraySearch { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array that is to be created: "); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Enter the elements of the array: "); for(int i=0; i>size; i++){ myArray[i] = sc.nextInt(); } //Sorting the array Arrays.sort(myArray); System.out.println("The sorted int array is:"); for (int number : myArray) { System.out.print(number+" "); } System.out.println(" "); System.out.println("Enter the value to be searched: "); int searchVal = sc.nextInt(); int retVal = Arrays.binarySearch(myArray,searchVal); System.out.println("Element found"); System.out.println("The index of element in the sorted array: " + retVal); } } Enter the size of the array that is to be created: 5 Enter the elements of the array: 30 20 5 12 55 The sorted int array is: 5 12 20 30 55 Enter the value to be searched: 12 Element found The index of element in the sorted array: 1
[ { "code": null, "e": 1220, "s": 1062, "text": "You can find whether a particular exists in a given array using any of the search algorithms. Here, we will see examples for linear search and binary search." }, { "code": null, "e": 1247, "s": 1220, "text": "Iterate through the array." }, { "code": null, "e": 1295, "s": 1247, "text": "Compare each element with the required element." }, { "code": null, "e": 2014, "s": 1295, "text": "import java.util.Scanner;\npublic class ArraySearch {\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the size of the array that is to be created: \");\n int size = sc.nextInt();\n int[] myArray = new int[size];\n System.out.println(\"Enter the elements of the array: \");\n for(int i=0; i<size; i++){\n myArray[i] = sc.nextInt();\n }\n System.out.println(\"Enter the value tobe searched: \");\n int searchVal = sc.nextInt();\n for (int i =0 ; i<myArray.length; i++) {\n if (myArray[i] == searchVal) {\n System.out.println(\"The index of element \"+searchVal+\" is : \" + i);\n }\n }\n }\n}" }, { "code": null, "e": 2180, "s": 2014, "text": "Enter the size of the array that is to be created:\n5\nEnter the elements of the array:\n30\n20\n5\n12\n55\nEnter the value to be searched:\n12\nThe index of element 12 is : 3" }, { "code": null, "e": 2380, "s": 2180, "text": "The Arrays class of the java.util package provides a method with name binarySearch(), this method accepts a sorted array and a value to search and returns the index of the given element in the array." }, { "code": null, "e": 3343, "s": 2380, "text": "import java.util.Arrays;\nimport java.util.Scanner;\npublic class ArraySearch {\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the size of the array that is to be created: \");\n int size = sc.nextInt();\n int[] myArray = new int[size];\n System.out.println(\"Enter the elements of the array: \");\n for(int i=0; i>size; i++){\n myArray[i] = sc.nextInt();\n }\n //Sorting the array\n Arrays.sort(myArray);\n System.out.println(\"The sorted int array is:\");\n for (int number : myArray) {\n System.out.print(number+\" \");\n }\n System.out.println(\" \");\n System.out.println(\"Enter the value to be searched: \");\n int searchVal = sc.nextInt();\n int retVal = Arrays.binarySearch(myArray,searchVal);\n System.out.println(\"Element found\");\n System.out.println(\"The index of element in the sorted array: \" + retVal);\n }\n}" }, { "code": null, "e": 3575, "s": 3343, "text": "Enter the size of the array that is to be created:\n5\nEnter the elements of the array:\n30\n20\n5\n12\n55\nThe sorted int array is:\n5 12 20 30 55\nEnter the value to be searched:\n12\nElement found\nThe index of element in the sorted array: 1" } ]
Circle of strings | Practice | GeeksforGeeks
Given an array of lowercase strings A[] of size N, determine if the strings can be chained together to form a circle. A string X can be chained together with another string Y if the last character of X is same as first character of Y. If every string of the array can be chained, it will form a circle. For example, for the array arr[] = {"for", "geek", "rig", "kaf"} the answer will be Yes as the given strings can be chained as "for", "rig", "geek" and "kaf" Example 1: Input: N = 3 A[] = { "abc", "bcd", "cdf" } Output: 0 Explaination: These strings can't form a circle because no string has 'd'at the starting index. Example 2: Input: N = 4 A[] = { "ab" , "bc", "cd", "da" } Output: 1 Explaination: These strings can form a circle of strings. Your Task: You don't need to read input or print output. Your task is to complete the function isCircle() which takes the length of the array N and the array A as input parameters and returns 1 if we can form a circle or 0 if we cannot. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1 ≤ N ≤ 104 1 ≤ Length of strings ≤ 20 0 himanshujain4572 months ago Why The Output For The TestCase: 3ceee eeece ddbc is 0? can't be it: ddbc→ceee→eeece +2 kronizerdeltac2 months ago JAVA SOLUTION: class Solution { static boolean dfs(HashMap<Character, ArrayList<Character>> map, HashSet<Character> vis, char ch) { if(vis.contains(ch)) return vis.size() == map.size(); vis.add(ch); for(char c : map.get(ch)) { if(dfs(map, vis, c)) return true; } return false; } static int isCircle(int N, String A[]) { int[] indegree = new int[26], outdegree = new int[26]; HashMap<Character, ArrayList<Character>> map = new HashMap<>(); for(String str : A) { char first = str.charAt(0), last = str.charAt(str.length() - 1); if(!map.containsKey(first)) map.put(first, new ArrayList<>()); map.get(first).add(last); outdegree[first - 'a']++; indegree[last - 'a']++; } for(int i = 0; i < 26; i++) if(indegree[i] != outdegree[i]) return 0; HashSet<Character> vis = new HashSet<>(); return dfs(map, vis, A[0].charAt(0)) ? 1 : 0; } } 0 rajatgarg212cd0162 months ago // TIME 0.1 USING HASHING ONLY class Solution{public:int isCircle(int N, vector<string> A){ unordered_map<char,int> m;unordered_map<char,int> m1;//m1 for finding the words which have same letters at the start and endunordered_map<char,int> m2;int n = A.size();for(int i = 0 ; i < n ;i++){m[A[i][0]]++; if(A[i][0] == A[i][A[i].size()-1]){m1[A[i][0]]++;}m2[A[i][A[i].size()-1]]++; }for(int i = 0 ; i < n ;i++){if(m[A[i][0]] != m2[A[i][0]]){ return 0;}if(m[A[i][0]] == m1[A[i][0]]){ // IF THIS EXIST MEANS ALL STRINGS THERE SHOULD HAVE SAME FIRST AND LAST DIGITS if(n != m[A[i][0]])return 0;return 1;}}return 1;}}; 0 taiphanvan24033 months ago int deg_in[256];class Solution{ public: void input(set<char>&s,vector<char>adj[],vector<string>A,int N) { for(int i=0;i<N;i++){ s.insert(A[i][0]); s.insert(A[i].back()); adj[A[i][0]].push_back(A[i].back()); deg_in[A[i].back()]++; } } void dfs(vector<char>adj[],bool visited[],char u){ visited[u]=1; for(auto i:adj[u]) if(!visited[i]) dfs(adj,visited,i); } bool isConnected(vector<char>adj[],bool visited[],set<char>s){ char c; for(auto i:s) if(s.size()>0){ c=i; break; } dfs(adj,visited,c); for(auto i:s) if(adj[i].size()>0 && !visited[i]) return false; return true; } bool checkEuler(vector<char>adj[],bool visited[],set<char>s) { if(!isConnected(adj,visited,s)) return false; for(auto i:s) if(deg_in[i]!=adj[i].size()) return false; return true; } int isCircle(int N, vector<string> A) { bool visited[256]; memset(visited,0,sizeof(visited)); vector<char>adj[256]; set<char>s; memset(deg_in,0,sizeof(deg_in)); input(s,adj,A,N); return checkEuler(adj,visited,s); }}; +1 shivambhadani1236 months ago int isCircle(int N, vector<string> A) { vector<int> adj[26]; vector<int> in(26, 0); vector<int> out(26, 0); for(int i=0; i<N; i++) { int ch1 = A[i][0]-'a'; int ch2 = A[i].back()-'a'; adj[ch1].push_back(ch2); out[ch1]++; in[ch2]++; } for(int i=0; i<26; i++) { if(in[i]!=out[i]) return 0; } int src; for(int i=0; i<26; i++) { if(out[i]) { src = i; break; } } vector<int> vis(26, 0); dfs(adj, vis, src); for(int i=0; i<26; i++) { if(out[i] && !vis[i]) return 0; } return 1; } void dfs(vector<int> adj[], vector<int>& vis, int s) { vis[s] = 1; for(auto& it: adj[s]) { if(!vis[it]) { dfs(adj, vis, it); } } } +2 Abhijit roy7 months ago Abhijit roy "HEY, PEOPLE" , this question just tests your knowledge of Euler Concepts of PATHS and CIRCUITS, and the strongly Connected components(KOSARAJU'S or TARJAN'S)...So be sure to check these two concepts before proceeding.. Steps: 1) Making a class graph having member function (addEdge, isConnected, DFS, isEulerian, canBeChained) will be really helpful..It makes tracking through the code easier and if you happen to come and see after a few weeks, the code will be very much understandable. 2) Keep track on inBound Dependency of a node, you can make this in the constructor. Basically this will keep track on the inbound dependencies of a node,Inshort it'll keep track of nodes pointing to it. 3) Use Kosaraju's Algo or Tarjan's algo to find SCC(Strongly Connected Components). If you find some disconnected components return false. Reverse the graph and do the same stuff so we can be sure that the graph has all components connected and all the nodes can be traversed, then return true; 4) Construct the graph using the class and the string of words. Then check if isConnected is false, return false cuz there will be no Eulerian Circuit . Otherwise, return false if the dependency of a node is equal to its list size, which means its not pointing to anyone but itself getting pointed. Its a Euler Concept so be sure to read that first. Now if all shit goes well, we can safely return our bad boy as true class Graph{private: int V; list<int>*adj; int*in;public: Graph(int V){ this->V=V; adj=new list<int>[V]; in=new int[V]; for(int i=0;i<v;i++){ in[i]="0;" }="" }="" void="" addedge(int="" u,int="" v){="" adj[u].push_back(v);="" in[v]++;="" this="" node="" has="" some="" dependecy="" }="" graph="" transpose(){="" graph="" g(v);="" for(int="" i="0;i&lt;V;i++){" for(auto="" it:="" adj[i]){="" g.addedge(it,i);="" }="" }="" return="" g;="" }="" void="" dfs(int="" node,vector<bool=""> &vis){ vis[node]=true; for(auto it: adj[node]){ if(vis[it]==false){ DFS(it,vis); } } } bool isConnected(){ vector<bool> vis(V,false); int i; for(i=0;i<v;i++){ if(adj[i].size()!="0){" break;="" }="" }="" dfs(i,vis);="" for(int="" i="0;i&lt;V;i++){" if(vis[i]="=false" &&="" adj[i].size()="">0){ //Disconnected Component return false; } } if(i==V){ //All disconnected components return false; } Graph g=Transpose(); for(int i=0;i<v;i++){ vis[i]="false;" }="" g.dfs(i,vis);="" for(int="" i="0;i&lt;V;i++){" if(vis[i]="=false" &&="" g.adj[i].size()="">0){ //Disconnected Component return false; } } return true; } bool isEulerianCycle(){ if (isConnected() == false){ return false; } for (int i = 0; i < V; i++){ if (adj[i].size() != in[i]){ return false; } } return true; }};class Solution{public: int isCircle(int n, vector<string> arr) { Graph g(26); for (int i = 0; i < n; i++){ string s = arr[i]; g.addEdge(s[0]-'a', s[s.length()-1]-'a'); } return g.isEulerianCycle(); }}; Link to Google Docs Code: https://docs.google.com/doc... P.S. GFG please stop messing with code posting...Its a part of learning +2 hishikeshphukan1237 months ago class Solution { int graph[26][26]; void dfs(int v, vector<bool> &visited) { visited[v] = true; for(int i=0 ; i<26 ; i++) if(graph[v][i] && !visited[i]) dfs(i,visited); } public: int isCircle(int N, vector<string> A) { memset(graph,0,sizeof(graph)); vector<int> in(26,0); vector<int> out(26,0); for(int i=0 ; i<N ; i++) { int a = A[i][0] - 'a'; int b = A[i].back() - 'a'; in[a]++; out[b]++; graph[a][b] = 1; } for(int i=0 ; i<26 ; i++) if(in[i] != out[i]) return 0; vector<bool> visited(26,false); int i; for(i=0 ; i<26 ; i++) if(in[i]) break; dfs(i,visited); for(int i=0 ; i<26 ; i++) if(in[i] && visited[i] == false) return 0; return 1; } }; 0 Kumar Sahab9 months ago Kumar Sahab class Solution{ int graph[26][26]; void dfs(int v, bool visited[]) { visited[v] = true; for(int i=0; i<26; i++) if(graph[v][i] && !visited[i]) dfs(i, visited); } public: int isCircle(int N, vector<string> A) { memset(graph, 0, sizeof(graph)); int in[26]={0}, ou[26] = {0}; for(int i=0; i<n; i++)="" {="" int="" a="A[i][0]-'a';" int="" b="A[i].back()-'a';" in[a]++;="" ou[b]++;="" graph[a][b]="1;" }="" for(int="" i="0;" i<26;="" i++)="" if(in[i]!="ou[i])" return="" 0;="" bool="" visited[26]="{false};" int="" i="0;" for(;="" i<26;="" i++)="" if(in[i])="" break;="" dfs(i,="" visited);="" for(int="" i="0;" i<26;="" i++)="" if(in[i]="" &&="" !visited[i])="" return="" 0;="" return="" 1;="" }="" };="" <="" code=""> 0 Aviral Ahuja9 months ago Aviral Ahuja Test case is failing woth 10000 Strings. can anyone help. Its correct output is 1 and my o/p is 0 static int isCircle(int N, String A[]) { Map<character,list<character>> map =new HashMap<>(); Map<character,integer> in = new HashMap<>(); Map<character,integer> out = new HashMap<>(); Character start=A[0].charAt(0); for(String el:A){ Character s=el.charAt(0); Character e=el.charAt(el.length()-1); map.putIfAbsent(s,new ArrayList<>()); map.get(s).add(e); in.merge(s,1,(o,n)->o+n); out.merge(e,1,(o,n)->o+n); } for(Character key : in.keySet()){ if(in.get(key) !=out.get(key)) return 0; } Set<character> visited = new HashSet<>(); dfs(map,visited,start); return (visited.size()==map.size())?1:0; } private static void dfs(Map<character,list<character>> map, Set<character> visited, Character start){ visited.add(start); for(Character ch:map.get(start)){ if(!visited.contains(ch)){ dfs(map,visited,ch); } } } 0 T9 months ago T class Solution{ public: int isCircle(int n, vector<string> v) { for (int i=0; i<=n-1; i++) { int x=v[i].length(); int y=v[i+1].length(); if (v[i][x-1]==v[i+1][0]) { continue; } else { return 0; } } if (v[0][0]==v[n-1][v[n-1].length()-1]) { return 1; } return 0; }}; what is wrong with this code? 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": 541, "s": 238, "text": "Given an array of lowercase strings A[] of size N, determine if the strings can be chained together to form a circle.\nA string X can be chained together with another string Y if the last character of X is same as first\ncharacter of Y. If every string of the array can be chained, it will form a circle." }, { "code": null, "e": 699, "s": 541, "text": "For example, for the array arr[] = {\"for\", \"geek\", \"rig\", \"kaf\"} the answer will be Yes as the given strings can be chained as \"for\", \"rig\", \"geek\" and \"kaf\"" }, { "code": null, "e": 711, "s": 699, "text": "\nExample 1:" }, { "code": null, "e": 861, "s": 711, "text": "Input:\nN = 3\nA[] = { \"abc\", \"bcd\", \"cdf\" }\nOutput:\n0\nExplaination:\nThese strings can't form a circle \nbecause no string has 'd'at the starting index." }, { "code": null, "e": 872, "s": 861, "text": "Example 2:" }, { "code": null, "e": 988, "s": 872, "text": "Input:\nN = 4\nA[] = { \"ab\" , \"bc\", \"cd\", \"da\" }\nOutput:\n1\nExplaination:\nThese strings can form a circle \nof strings." }, { "code": null, "e": 1226, "s": 988, "text": "\nYour Task:\nYou don't need to read input or print output. Your task is to complete the function isCircle() which takes the length of the array N and the array A as input parameters and returns 1 if we can form a circle or 0 if we cannot." }, { "code": null, "e": 1289, "s": 1226, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1343, "s": 1289, "text": "\nConstraints: \n1 ≤ N ≤ 104\n1 ≤ Length of strings ≤ 20" }, { "code": null, "e": 1345, "s": 1343, "text": "0" }, { "code": null, "e": 1373, "s": 1345, "text": "himanshujain4572 months ago" }, { "code": null, "e": 1406, "s": 1373, "text": "Why The Output For The TestCase:" }, { "code": null, "e": 1423, "s": 1406, "text": "3ceee eeece ddbc" }, { "code": null, "e": 1429, "s": 1423, "text": "is 0?" }, { "code": null, "e": 1458, "s": 1429, "text": "can't be it: ddbc→ceee→eeece" }, { "code": null, "e": 1461, "s": 1458, "text": "+2" }, { "code": null, "e": 1488, "s": 1461, "text": "kronizerdeltac2 months ago" }, { "code": null, "e": 1504, "s": 1488, "text": "JAVA SOLUTION: " }, { "code": null, "e": 2656, "s": 1504, "text": "class Solution\n{\n static boolean dfs(HashMap<Character, ArrayList<Character>> map, HashSet<Character> vis, char ch) {\n if(vis.contains(ch))\n return vis.size() == map.size();\n \n vis.add(ch);\n \n for(char c : map.get(ch)) {\n if(dfs(map, vis, c))\n return true;\n }\n return false;\n }\n static int isCircle(int N, String A[])\n {\n int[] indegree = new int[26], outdegree = new int[26];\n HashMap<Character, ArrayList<Character>> map = new HashMap<>();\n for(String str : A) {\n char first = str.charAt(0), last = str.charAt(str.length() - 1);\n if(!map.containsKey(first))\n map.put(first, new ArrayList<>());\n \n map.get(first).add(last);\n outdegree[first - 'a']++;\n indegree[last - 'a']++;\n \n }\n \n for(int i = 0; i < 26; i++)\n if(indegree[i] != outdegree[i])\n return 0;\n \n HashSet<Character> vis = new HashSet<>();\n return dfs(map, vis, A[0].charAt(0)) ? 1 : 0;\n }\n}" }, { "code": null, "e": 2658, "s": 2656, "text": "0" }, { "code": null, "e": 2688, "s": 2658, "text": "rajatgarg212cd0162 months ago" }, { "code": null, "e": 2719, "s": 2688, "text": "// TIME 0.1 USING HASHING ONLY" }, { "code": null, "e": 2780, "s": 2719, "text": "class Solution{public:int isCircle(int N, vector<string> A){" }, { "code": null, "e": 3249, "s": 2780, "text": "unordered_map<char,int> m;unordered_map<char,int> m1;//m1 for finding the words which have same letters at the start and endunordered_map<char,int> m2;int n = A.size();for(int i = 0 ; i < n ;i++){m[A[i][0]]++; if(A[i][0] == A[i][A[i].size()-1]){m1[A[i][0]]++;}m2[A[i][A[i].size()-1]]++; }for(int i = 0 ; i < n ;i++){if(m[A[i][0]] != m2[A[i][0]]){ return 0;}if(m[A[i][0]] == m1[A[i][0]]){ // IF THIS EXIST MEANS ALL STRINGS THERE SHOULD HAVE SAME FIRST AND LAST DIGITS" }, { "code": null, "e": 3301, "s": 3249, "text": "if(n != m[A[i][0]])return 0;return 1;}}return 1;}};" }, { "code": null, "e": 3303, "s": 3301, "text": "0" }, { "code": null, "e": 3330, "s": 3303, "text": "taiphanvan24033 months ago" }, { "code": null, "e": 4563, "s": 3330, "text": "int deg_in[256];class Solution{ public: void input(set<char>&s,vector<char>adj[],vector<string>A,int N) { for(int i=0;i<N;i++){ s.insert(A[i][0]); s.insert(A[i].back()); adj[A[i][0]].push_back(A[i].back()); deg_in[A[i].back()]++; } } void dfs(vector<char>adj[],bool visited[],char u){ visited[u]=1; for(auto i:adj[u]) if(!visited[i]) dfs(adj,visited,i); } bool isConnected(vector<char>adj[],bool visited[],set<char>s){ char c; for(auto i:s) if(s.size()>0){ c=i; break; } dfs(adj,visited,c); for(auto i:s) if(adj[i].size()>0 && !visited[i]) return false; return true; } bool checkEuler(vector<char>adj[],bool visited[],set<char>s) { if(!isConnected(adj,visited,s)) return false; for(auto i:s) if(deg_in[i]!=adj[i].size()) return false; return true; } int isCircle(int N, vector<string> A) { bool visited[256]; memset(visited,0,sizeof(visited)); vector<char>adj[256]; set<char>s; memset(deg_in,0,sizeof(deg_in)); input(s,adj,A,N); return checkEuler(adj,visited,s); }};" }, { "code": null, "e": 4566, "s": 4563, "text": "+1" }, { "code": null, "e": 4595, "s": 4566, "text": "shivambhadani1236 months ago" }, { "code": null, "e": 5556, "s": 4595, "text": "int isCircle(int N, vector<string> A)\n {\n vector<int> adj[26];\n vector<int> in(26, 0);\n vector<int> out(26, 0);\n for(int i=0; i<N; i++) {\n int ch1 = A[i][0]-'a';\n int ch2 = A[i].back()-'a';\n adj[ch1].push_back(ch2);\n out[ch1]++;\n in[ch2]++;\n }\n for(int i=0; i<26; i++) {\n if(in[i]!=out[i]) return 0;\n }\n int src;\n for(int i=0; i<26; i++) {\n if(out[i]) {\n src = i;\n break;\n }\n }\n vector<int> vis(26, 0);\n dfs(adj, vis, src);\n for(int i=0; i<26; i++) {\n if(out[i] && !vis[i]) \n return 0;\n }\n return 1;\n }\n void dfs(vector<int> adj[], vector<int>& vis, int s) {\n vis[s] = 1;\n for(auto& it: adj[s]) {\n if(!vis[it]) {\n dfs(adj, vis, it);\n }\n }\n }" }, { "code": null, "e": 5559, "s": 5556, "text": "+2" }, { "code": null, "e": 5583, "s": 5559, "text": "Abhijit roy7 months ago" }, { "code": null, "e": 5595, "s": 5583, "text": "Abhijit roy" }, { "code": null, "e": 5815, "s": 5595, "text": "\"HEY, PEOPLE\" , this question just tests your knowledge of Euler Concepts of PATHS and CIRCUITS, and the strongly Connected components(KOSARAJU'S or TARJAN'S)...So be sure to check these two concepts before proceeding.." }, { "code": null, "e": 6085, "s": 5815, "text": "Steps: 1) Making a class graph having member function (addEdge, isConnected, DFS, isEulerian, canBeChained) will be really helpful..It makes tracking through the code easier and if you happen to come and see after a few weeks, the code will be very much understandable." }, { "code": null, "e": 6289, "s": 6085, "text": "2) Keep track on inBound Dependency of a node, you can make this in the constructor. Basically this will keep track on the inbound dependencies of a node,Inshort it'll keep track of nodes pointing to it." }, { "code": null, "e": 6584, "s": 6289, "text": "3) Use Kosaraju's Algo or Tarjan's algo to find SCC(Strongly Connected Components). If you find some disconnected components return false. Reverse the graph and do the same stuff so we can be sure that the graph has all components connected and all the nodes can be traversed, then return true;" }, { "code": null, "e": 7002, "s": 6584, "text": "4) Construct the graph using the class and the string of words. Then check if isConnected is false, return false cuz there will be no Eulerian Circuit . Otherwise, return false if the dependency of a node is equal to its list size, which means its not pointing to anyone but itself getting pointed. Its a Euler Concept so be sure to read that first. Now if all shit goes well, we can safely return our bad boy as true" }, { "code": null, "e": 8796, "s": 7002, "text": "class Graph{private: int V; list<int>*adj; int*in;public: Graph(int V){ this->V=V; adj=new list<int>[V]; in=new int[V]; for(int i=0;i<v;i++){ in[i]=\"0;\" }=\"\" }=\"\" void=\"\" addedge(int=\"\" u,int=\"\" v){=\"\" adj[u].push_back(v);=\"\" in[v]++;=\"\" this=\"\" node=\"\" has=\"\" some=\"\" dependecy=\"\" }=\"\" graph=\"\" transpose(){=\"\" graph=\"\" g(v);=\"\" for(int=\"\" i=\"0;i&lt;V;i++){\" for(auto=\"\" it:=\"\" adj[i]){=\"\" g.addedge(it,i);=\"\" }=\"\" }=\"\" return=\"\" g;=\"\" }=\"\" void=\"\" dfs(int=\"\" node,vector<bool=\"\"> &vis){ vis[node]=true; for(auto it: adj[node]){ if(vis[it]==false){ DFS(it,vis); } } } bool isConnected(){ vector<bool> vis(V,false); int i; for(i=0;i<v;i++){ if(adj[i].size()!=\"0){\" break;=\"\" }=\"\" }=\"\" dfs(i,vis);=\"\" for(int=\"\" i=\"0;i&lt;V;i++){\" if(vis[i]=\"=false\" &&=\"\" adj[i].size()=\"\">0){ //Disconnected Component return false; } } if(i==V){ //All disconnected components return false; } Graph g=Transpose(); for(int i=0;i<v;i++){ vis[i]=\"false;\" }=\"\" g.dfs(i,vis);=\"\" for(int=\"\" i=\"0;i&lt;V;i++){\" if(vis[i]=\"=false\" &&=\"\" g.adj[i].size()=\"\">0){ //Disconnected Component return false; } } return true; } bool isEulerianCycle(){ if (isConnected() == false){ return false; } for (int i = 0; i < V; i++){ if (adj[i].size() != in[i]){ return false; } } return true; }};class Solution{public: int isCircle(int n, vector<string> arr) { Graph g(26); for (int i = 0; i < n; i++){ string s = arr[i]; g.addEdge(s[0]-'a', s[s.length()-1]-'a'); } return g.isEulerianCycle(); }};" }, { "code": null, "e": 8853, "s": 8796, "text": "Link to Google Docs Code: https://docs.google.com/doc..." }, { "code": null, "e": 8925, "s": 8853, "text": "P.S. GFG please stop messing with code posting...Its a part of learning" }, { "code": null, "e": 8928, "s": 8925, "text": "+2" }, { "code": null, "e": 8959, "s": 8928, "text": "hishikeshphukan1237 months ago" }, { "code": null, "e": 9927, "s": 8959, "text": "class Solution\n{\n int graph[26][26];\n void dfs(int v, vector<bool> &visited)\n {\n visited[v] = true;\n for(int i=0 ; i<26 ; i++)\n if(graph[v][i] && !visited[i])\n dfs(i,visited);\n }\n public:\n int isCircle(int N, vector<string> A)\n {\n memset(graph,0,sizeof(graph));\n vector<int> in(26,0);\n vector<int> out(26,0);\n for(int i=0 ; i<N ; i++)\n {\n int a = A[i][0] - 'a';\n int b = A[i].back() - 'a';\n in[a]++;\n out[b]++;\n graph[a][b] = 1;\n }\n for(int i=0 ; i<26 ; i++)\n if(in[i] != out[i])\n return 0;\n vector<bool> visited(26,false);\n int i;\n for(i=0 ; i<26 ; i++)\n if(in[i])\n break;\n dfs(i,visited);\n for(int i=0 ; i<26 ; i++)\n if(in[i] && visited[i] == false)\n return 0;\n return 1;\n }\n};" }, { "code": null, "e": 9929, "s": 9927, "text": "0" }, { "code": null, "e": 9953, "s": 9929, "text": "Kumar Sahab9 months ago" }, { "code": null, "e": 9965, "s": 9953, "text": "Kumar Sahab" }, { "code": null, "e": 10762, "s": 9965, "text": "class Solution{ int graph[26][26]; void dfs(int v, bool visited[]) { visited[v] = true; for(int i=0; i<26; i++) if(graph[v][i] && !visited[i]) dfs(i, visited); } public: int isCircle(int N, vector<string> A) { memset(graph, 0, sizeof(graph)); int in[26]={0}, ou[26] = {0}; for(int i=0; i<n; i++)=\"\" {=\"\" int=\"\" a=\"A[i][0]-'a';\" int=\"\" b=\"A[i].back()-'a';\" in[a]++;=\"\" ou[b]++;=\"\" graph[a][b]=\"1;\" }=\"\" for(int=\"\" i=\"0;\" i<26;=\"\" i++)=\"\" if(in[i]!=\"ou[i])\" return=\"\" 0;=\"\" bool=\"\" visited[26]=\"{false};\" int=\"\" i=\"0;\" for(;=\"\" i<26;=\"\" i++)=\"\" if(in[i])=\"\" break;=\"\" dfs(i,=\"\" visited);=\"\" for(int=\"\" i=\"0;\" i<26;=\"\" i++)=\"\" if(in[i]=\"\" &&=\"\" !visited[i])=\"\" return=\"\" 0;=\"\" return=\"\" 1;=\"\" }=\"\" };=\"\" <=\"\" code=\"\">" }, { "code": null, "e": 10764, "s": 10762, "text": "0" }, { "code": null, "e": 10789, "s": 10764, "text": "Aviral Ahuja9 months ago" }, { "code": null, "e": 10802, "s": 10789, "text": "Aviral Ahuja" }, { "code": null, "e": 10900, "s": 10802, "text": "Test case is failing woth 10000 Strings. can anyone help. Its correct output is 1 and my o/p is 0" }, { "code": null, "e": 11931, "s": 10900, "text": "static int isCircle(int N, String A[]) { Map<character,list<character>> map =new HashMap<>(); Map<character,integer> in = new HashMap<>(); Map<character,integer> out = new HashMap<>(); Character start=A[0].charAt(0); for(String el:A){ Character s=el.charAt(0); Character e=el.charAt(el.length()-1); map.putIfAbsent(s,new ArrayList<>()); map.get(s).add(e); in.merge(s,1,(o,n)->o+n); out.merge(e,1,(o,n)->o+n); } for(Character key : in.keySet()){ if(in.get(key) !=out.get(key)) return 0; } Set<character> visited = new HashSet<>(); dfs(map,visited,start); return (visited.size()==map.size())?1:0; } private static void dfs(Map<character,list<character>> map, Set<character> visited, Character start){ visited.add(start); for(Character ch:map.get(start)){ if(!visited.contains(ch)){ dfs(map,visited,ch); } } }" }, { "code": null, "e": 11933, "s": 11931, "text": "0" }, { "code": null, "e": 11947, "s": 11933, "text": "T9 months ago" }, { "code": null, "e": 11949, "s": 11947, "text": "T" }, { "code": null, "e": 12404, "s": 11949, "text": "class Solution{ public: int isCircle(int n, vector<string> v) { for (int i=0; i<=n-1; i++) { int x=v[i].length(); int y=v[i+1].length(); if (v[i][x-1]==v[i+1][0]) { continue; } else { return 0; } } if (v[0][0]==v[n-1][v[n-1].length()-1]) { return 1; } return 0; }};" }, { "code": null, "e": 12434, "s": 12404, "text": "what is wrong with this code?" }, { "code": null, "e": 12580, "s": 12434, "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": 12616, "s": 12580, "text": " Login to access your submissions. " }, { "code": null, "e": 12626, "s": 12616, "text": "\nProblem\n" }, { "code": null, "e": 12636, "s": 12626, "text": "\nContest\n" }, { "code": null, "e": 12699, "s": 12636, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 12847, "s": 12699, "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": 13055, "s": 12847, "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": 13161, "s": 13055, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Jython - Modules
A module is a Jython script in which one or more related functions, classes or variables are defined. This allows a logical organization of the Jython code. The Program elements defined in a module can be used in another Jython script by importing either the module or the specific element (function/class) from it. In the following code (hello.py) a function SayHello() is defined. #definition of function defSayHello(str): print "Hello ", str return To use the SayHello() function from another script, import the hello.py module in it. import hello hello.SayHello("TutorialsPoint") However, this will import all functions defined in the module. In order to import specific function from module use following syntax. from modname import name1[, name2[,... nameN] For example, to import only the SayHello() function, change the above script as follows. from hello import SayHello SayHello("TutorialsPoint") There is no need to prefix the name of the module while calling the function. Print Add Notes Bookmark this page
[ { "code": null, "e": 2397, "s": 2081, "text": "A module is a Jython script in which one or more related functions, classes or variables are defined. This allows a logical organization of the Jython code. The Program elements defined in a module can be used in another Jython script by importing either the module or the specific element (function/class) from it." }, { "code": null, "e": 2464, "s": 2397, "text": "In the following code (hello.py) a function SayHello() is defined." }, { "code": null, "e": 2539, "s": 2464, "text": "#definition of function\ndefSayHello(str):\n print \"Hello \", str\n return" }, { "code": null, "e": 2625, "s": 2539, "text": "To use the SayHello() function from another script, import the hello.py module in it." }, { "code": null, "e": 2672, "s": 2625, "text": "import hello\nhello.SayHello(\"TutorialsPoint\")\n" }, { "code": null, "e": 2806, "s": 2672, "text": "However, this will import all functions defined in the module. In order to import specific function from module use following syntax." }, { "code": null, "e": 2853, "s": 2806, "text": "from modname import name1[, name2[,... nameN]\n" }, { "code": null, "e": 2942, "s": 2853, "text": "For example, to import only the SayHello() function, change the above script as follows." }, { "code": null, "e": 2996, "s": 2942, "text": "from hello import SayHello\nSayHello(\"TutorialsPoint\")" }, { "code": null, "e": 3074, "s": 2996, "text": "There is no need to prefix the name of the module while calling the function." }, { "code": null, "e": 3081, "s": 3074, "text": " Print" }, { "code": null, "e": 3092, "s": 3081, "text": " Add Notes" } ]
Adding a unique id for each entry in JSON object in JavaScript
Suppose, we have an array described as follows − const arr = [ { "Arts": [ { "Performing arts": [ { "Music": [ { "title": "Accompanying" }, { "title": "Chamber music" }, { "title": "Church music" }, { "Conducting": [ { "title": "Choral conducting" }, { "title": "Orchestral conducting" }, { "title": "Wind ensemble conducting" } ] }, { "title": "Early music" }, { "title": "Jazz studies" }, { "title": "Musical composition" }, { "title": "Music education" }, { "title": "Music history" }, { "Musicology": [ { "title": "Historical musicology" }, { "title": "Systematic musicology" } ] }, { "title": "Ethnomusicology" }, { "title": "Music theory" }, { "title": "Orchestral studies" }, { "Organology": [ { "title": "Organ and historical keyboards" }, { "title": "Piano" }, { "title": "Strings, harp, oud, and guitar" }, { "title": "Singing" }, { "title": "Strings, harp, oud, and guitar" } ] }, { "title": "Recording" } ] }, { "Dance": [ { "title": "Choreography" }, { "title": "Dance notation" }, { "title": "Ethnochoreology" }, { "title": "History of dance" } ] }, { "Television": [ { "title": "Television studies" } ] }, { "Theatre": [ { "title": "Acting" }, { "title": "Directing" }, { "title": "Dramaturgy" }, { "title": "History" }, { "title": "Musical theatre" }, { "title": "Playwrighting" }, { "title": "Puppetry" } ] } ] }] }]; We are required to write a JavaScript function that takes in one such array. Then the function should add an "id" field in all those objects that have a "title" field. The value of "id" property is not of much importance (it can be any unique value), what’s more important is that all those objects with "title" property must have an "id" property. We have to do this without creating a copy of the actual array. The code for this will be − const arr = [ { "Arts": [ { "Performing arts": [ { "Music": [ { "title": "Accompanying" }, { "title": "Chamber music" }, { "title": "Church music" }, { "Conducting": [ { "title": "Choral conducting" }, { "title": "Orchestral conducting" }, { "title": "Wind ensemble conducting" } ] }, { "title": "Early music" }, { "title": "Jazz studies" }, { "title": "Musical composition" }, { "title": "Music education" }, { "title": "Music history" }, { "Musicology": [ { "title": "Historical musicology" }, { "title": "Systematic musicology" } ] }, { "title": "Ethnomusicology" }, { "title": "Music theory" }, { "title": "Orchestral studies" }, { "Organology": [ { "title": "Organ and historical keyboards" }, { "title": "Piano" }, { "title": "Strings, harp, oud, and guitar" }, { "title": "Singing" }, { "title": "Strings, harp, oud, and guitar" } ] }, { "title": "Recording" } ] }, { "Dance": [ { "title": "Choreography" }, { "title": "Dance notation" }, { "title": "Ethnochoreology" }, { "title": "History of dance" } ] }, { "Television": [ { "title": "Television studies" } ] }, { "Theatre": [ { "title": "Acting" }, { "title": "Directing" }, { "title": "Dramaturgy" }, { "title": "History" }, { "title": "Musical theatre" }, { "title": "Playwrighting" }, { "title": "Puppetry" } ] } ] }] }]; const addId = (id = 1) => { return function recur(obj) { if ('title' in obj) { obj.id = id++; }; Object.keys(obj).forEach(el => { Array.isArray(obj[el]) && obj[el].forEach(recur); }); }; } const mapId = arr => { arr.forEach(addId); } mapId(arr); console.log(JSON.stringify(arr, undefined, 4)); And the output in the console will be − [ { "Arts": [ { "Performing arts": [ { "Music": [ { "title": "Accompanying" }, { "title": "Chamber music" }, { "title": "Church music" }, { "Conducting": [ { "title": "Choral conducting" }, { "title": "Orchestral conducting" }, { "title": "Wind ensemble conducting" } ] }, { "title": "Early music" }, { "title": "Jazz studies" }, { "title": "Musical composition" }, { "title": "Music education" }, { "title": "Music history" }, { "Musicology": [ { "title": "Historical musicology" }, { "title": "Systematic musicology" } ] }, { "title": "Ethnomusicology" }, { "title": "Music theory" }, { "title": "Orchestral studies" }, { "Organology": [ { "title": "Organ and historical keyboards" }, { "title": "Piano" }, { "title": "Strings, harp, oud, and guitar" }, { "title": "Singing" }, { "title": "Strings, harp, oud, and guitar" } ] }, { "title": "Recording" } ] }, { "Dance": [ { "title": "Choreography" }, { "title": "Dance notation" }, { "title": "Ethnochoreology" }, { "title": "History of dance" } ] }, { "Television": [ { "title": "Television studies" } ] }, { "Theatre": [ { "title": "Acting" }, { "title": "Directing" }, { "title": "Dramaturgy" }, { "title": "History" }, { "title": "Musical theatre" }, { "title": "Playwrighting" }, { "title": "Puppetry" } ] } ] } ] } ]
[ { "code": null, "e": 1111, "s": 1062, "text": "Suppose, we have an array described as follows −" }, { "code": null, "e": 3318, "s": 1111, "text": "const arr = [\n {\n \"Arts\": [\n {\n \"Performing arts\": [\n {\n \"Music\": [\n { \"title\": \"Accompanying\" },\n { \"title\": \"Chamber music\" },\n { \"title\": \"Church music\" },\n { \"Conducting\": [\n { \"title\": \"Choral conducting\" },\n { \"title\": \"Orchestral conducting\" },\n { \"title\": \"Wind ensemble conducting\" }\n ] },\n { \"title\": \"Early music\" },\n { \"title\": \"Jazz studies\" },\n { \"title\": \"Musical composition\" },\n { \"title\": \"Music education\" },\n { \"title\": \"Music history\" },\n { \"Musicology\": [\n { \"title\": \"Historical musicology\" },\n { \"title\": \"Systematic musicology\" }\n ] },\n { \"title\": \"Ethnomusicology\" },\n { \"title\": \"Music theory\" },\n { \"title\": \"Orchestral studies\" },\n { \"Organology\": [\n { \"title\": \"Organ and historical keyboards\" },\n { \"title\": \"Piano\" },\n { \"title\": \"Strings, harp, oud, and guitar\" },\n { \"title\": \"Singing\" },\n { \"title\": \"Strings, harp, oud, and guitar\" }\n ] },\n { \"title\": \"Recording\" }\n ] },\n { \"Dance\": [\n { \"title\": \"Choreography\" },\n { \"title\": \"Dance notation\" },\n { \"title\": \"Ethnochoreology\" },\n { \"title\": \"History of dance\" }\n ] },\n { \"Television\": [\n { \"title\": \"Television studies\" }\n ] },\n { \"Theatre\": [\n { \"title\": \"Acting\" },\n { \"title\": \"Directing\" },\n { \"title\": \"Dramaturgy\" },\n { \"title\": \"History\" },\n { \"title\": \"Musical theatre\" },\n { \"title\": \"Playwrighting\" },\n { \"title\": \"Puppetry\" }\n ] }\n ]\n }]\n}];" }, { "code": null, "e": 3486, "s": 3318, "text": "We are required to write a JavaScript function that takes in one such array. Then the function should add an \"id\" field in all those objects that have a \"title\" field." }, { "code": null, "e": 3667, "s": 3486, "text": "The value of \"id\" property is not of much importance (it can be any unique value), what’s more important is that all those objects with \"title\" property must have an \"id\" property." }, { "code": null, "e": 3731, "s": 3667, "text": "We have to do this without creating a copy of the actual array." }, { "code": null, "e": 3759, "s": 3731, "text": "The code for this will be −" }, { "code": null, "e": 5990, "s": 3759, "text": "const arr = [\n { \"Arts\": [\n { \"Performing arts\": [\n { \"Music\": [\n { \"title\": \"Accompanying\" },\n { \"title\": \"Chamber music\" },\n { \"title\": \"Church music\" },\n { \"Conducting\": [\n { \"title\": \"Choral conducting\" },\n { \"title\": \"Orchestral conducting\" },\n { \"title\": \"Wind ensemble conducting\" }\n ] },\n { \"title\": \"Early music\" },\n { \"title\": \"Jazz studies\" },\n { \"title\": \"Musical composition\" },\n { \"title\": \"Music education\" },\n { \"title\": \"Music history\" },\n { \"Musicology\": [\n { \"title\": \"Historical musicology\" },\n { \"title\": \"Systematic musicology\" }\n ] },\n { \"title\": \"Ethnomusicology\" },\n { \"title\": \"Music theory\" },\n { \"title\": \"Orchestral studies\" },\n { \"Organology\": [\n { \"title\": \"Organ and historical keyboards\" },\n { \"title\": \"Piano\" },\n { \"title\": \"Strings, harp, oud, and guitar\" },\n { \"title\": \"Singing\" },\n { \"title\": \"Strings, harp, oud, and guitar\" }\n ] },\n { \"title\": \"Recording\" }\n ] },\n { \"Dance\": [\n { \"title\": \"Choreography\" },\n { \"title\": \"Dance notation\" },\n { \"title\": \"Ethnochoreology\" },\n { \"title\": \"History of dance\" }\n ] },\n { \"Television\": [\n { \"title\": \"Television studies\" }\n ] },\n { \"Theatre\": [\n { \"title\": \"Acting\" },\n { \"title\": \"Directing\" },\n { \"title\": \"Dramaturgy\" },\n { \"title\": \"History\" },\n { \"title\": \"Musical theatre\" },\n { \"title\": \"Playwrighting\" },\n { \"title\": \"Puppetry\" }\n ] }\n ]\n }]\n}];\nconst addId = (id = 1) => {\n return function recur(obj) {\n if ('title' in obj) {\n obj.id = id++;\n };\n Object.keys(obj).forEach(el => {\n Array.isArray(obj[el]) && obj[el].forEach(recur);\n });\n };\n}\nconst mapId = arr => {\n arr.forEach(addId);\n}\nmapId(arr);\nconsole.log(JSON.stringify(arr, undefined, 4));" }, { "code": null, "e": 6030, "s": 5990, "text": "And the output in the console will be −" }, { "code": null, "e": 10326, "s": 6030, "text": "[\n {\n \"Arts\": [\n {\n \"Performing arts\": [\n {\n \"Music\": [\n {\n \"title\": \"Accompanying\"\n },\n {\n \"title\": \"Chamber music\"\n },\n {\n \"title\": \"Church music\"\n },\n {\n \"Conducting\": [\n {\n \"title\": \"Choral conducting\"\n },\n {\n \"title\": \"Orchestral conducting\"\n },\n {\n \"title\": \"Wind ensemble conducting\"\n }\n ]\n },\n {\n \"title\": \"Early music\"\n },\n {\n \"title\": \"Jazz studies\"\n },\n {\n \"title\": \"Musical composition\"\n },\n {\n \"title\": \"Music education\"\n },\n {\n \"title\": \"Music history\"\n },\n {\n \"Musicology\": [\n {\n \"title\": \"Historical musicology\"\n },\n {\n \"title\": \"Systematic musicology\"\n }\n ]\n },\n {\n \"title\": \"Ethnomusicology\"\n },\n {\n \"title\": \"Music theory\"\n },\n {\n \"title\": \"Orchestral studies\"\n },\n {\n \"Organology\": [\n {\n \"title\": \"Organ and historical keyboards\"\n },\n {\n \"title\": \"Piano\"\n },\n {\n \"title\": \"Strings, harp, oud, and guitar\"\n },\n {\n \"title\": \"Singing\"\n },\n {\n \"title\": \"Strings, harp, oud, and guitar\"\n }\n ]\n },\n {\n \"title\": \"Recording\"\n }\n ]\n },\n {\n \"Dance\": [\n {\n \"title\": \"Choreography\"\n },\n {\n \"title\": \"Dance notation\"\n },\n {\n \"title\": \"Ethnochoreology\"\n },\n {\n \"title\": \"History of dance\"\n }\n ]\n },\n {\n \"Television\": [\n {\n \"title\": \"Television studies\"\n }\n ]\n },\n {\n \"Theatre\": [\n {\n \"title\": \"Acting\"\n },\n {\n \"title\": \"Directing\"\n },\n {\n \"title\": \"Dramaturgy\"\n },\n {\n \"title\": \"History\"\n },\n {\n \"title\": \"Musical theatre\"\n },\n {\n \"title\": \"Playwrighting\"\n },\n {\n \"title\": \"Puppetry\"\n }\n ]\n }\n ]\n }\n ]\n }\n]" } ]
Fetch the first letter of a column value and insert it in another column with MySQL
For this, use the concept of LEFT() function. Let us first create a table − mysql> create table DemoTable2036 -> ( -> FirstLetter varchar(20), -> Title varchar(20) -> ); Query OK, 0 rows affected (1.01 sec) Insert some records in the table using insert command − mysql> insert into DemoTable2036(Title) values('Chris'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable2036(Title) values('John'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable2036(Title) values('Adam'); Query OK, 1 row affected (0.15 sec) Display all records from the table using select statement − mysql> select *from DemoTable2036; This will produce the following output − +-------------+-------+ | FirstLetter | Title | +-------------+-------+ | NULL | Chris | | NULL | John | | NULL | Adam | +-------------+-------+ 3 rows in set (0.00 sec) Following is the query to fetch the first letter of a column value and place it to another column − mysql> update DemoTable2036 -> set FirstLetter=left(Title,1); Query OK, 3 rows affected (0.23 sec) Rows matched: 3 Changed: 3 Warnings: 0 Let us check the table records once again − mysql> select *from DemoTable2036; This will produce the following output − +-------------+-------+ | FirstLetter | Title | +-------------+-------+ | C | Chris | | J | John | | A | Adam | +-------------+-------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1138, "s": 1062, "text": "For this, use the concept of LEFT() function. Let us first create a table −" }, { "code": null, "e": 1281, "s": 1138, "text": "mysql> create table DemoTable2036\n -> (\n -> FirstLetter varchar(20),\n -> Title varchar(20)\n -> );\nQuery OK, 0 rows affected (1.01 sec)" }, { "code": null, "e": 1337, "s": 1281, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1616, "s": 1337, "text": "mysql> insert into DemoTable2036(Title) values('Chris');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable2036(Title) values('John');\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into DemoTable2036(Title) values('Adam');\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 1676, "s": 1616, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1711, "s": 1676, "text": "mysql> select *from DemoTable2036;" }, { "code": null, "e": 1752, "s": 1711, "text": "This will produce the following output −" }, { "code": null, "e": 1945, "s": 1752, "text": "+-------------+-------+\n| FirstLetter | Title |\n+-------------+-------+\n| NULL | Chris |\n| NULL | John |\n| NULL | Adam |\n+-------------+-------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2045, "s": 1945, "text": "Following is the query to fetch the first letter of a column value and place it to another column −" }, { "code": null, "e": 2186, "s": 2045, "text": "mysql> update DemoTable2036\n -> set FirstLetter=left(Title,1);\nQuery OK, 3 rows affected (0.23 sec)\nRows matched: 3 Changed: 3 Warnings: 0" }, { "code": null, "e": 2230, "s": 2186, "text": "Let us check the table records once again −" }, { "code": null, "e": 2265, "s": 2230, "text": "mysql> select *from DemoTable2036;" }, { "code": null, "e": 2306, "s": 2265, "text": "This will produce the following output −" }, { "code": null, "e": 2499, "s": 2306, "text": "+-------------+-------+\n| FirstLetter | Title |\n+-------------+-------+\n| C | Chris |\n| J | John |\n| A | Adam |\n+-------------+-------+\n3 rows in set (0.00 sec)" } ]
C++ Hello World | Practice | GeeksforGeeks
Let's begin your journey towards coding with the very first question of coding world. Your task is to write code which prints Hello World. Example 1: Input: No Input Output: Hello World Your Task: In the function helloWorld(), output a line "Hello World" (without quotes). -1 heartlucy14322 hours ago cout << “Hello World”; 0 2002skr222 days ago #include<iostream> using namespace std; int main(){ cout<<"Hello World"; return 0; } 0 vedantchourasiya142 days ago #include <iostream>using namespace std;int main() { cout << "Hello, world!"; return 0;} 0 gocode3 days ago #include<iostream> using namespace std; int main() { cout<<"Hello World"<<endl; return 0; } 0 honeydancer253 days ago #include<iostream>using namespace std;main(){ cout <<"Hello World"; return 0;} 0 dikshasharmaug216 days ago #include<iostrem.h> std; int main(){ cout<<"hello world"; } 0 pshiv27041 week ago Include<iostream.h> using namespace std; int main () { cout<<"Hello world": return 0; } 0 annuchhikara20011 week ago #include<iostream> using namespace std; int main(){ cout<<"Hello World"; return 0; } 0 sk31951132 weeks ago #include<iostream> using namespace std; int main () { cout<<"HELLO WOLD!"; return 0; } 0 sudhanshuranjan0292 weeks ago #include<iostream> Using namespace std; Int main(){ Cout<<"HELLOW WORLD"<<endl; Returns;} 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": 418, "s": 278, "text": "Let's begin your journey towards coding with the very first question of coding world. Your task is to write code which prints Hello World. " }, { "code": null, "e": 429, "s": 418, "text": "Example 1:" }, { "code": null, "e": 465, "s": 429, "text": "Input:\nNo Input\nOutput:\nHello World" }, { "code": null, "e": 476, "s": 465, "text": "Your Task:" }, { "code": null, "e": 552, "s": 476, "text": "In the function helloWorld(), output a line \"Hello World\" (without quotes)." }, { "code": null, "e": 555, "s": 552, "text": "-1" }, { "code": null, "e": 580, "s": 555, "text": "heartlucy14322 hours ago" }, { "code": null, "e": 603, "s": 580, "text": "cout << “Hello World”;" }, { "code": null, "e": 605, "s": 603, "text": "0" }, { "code": null, "e": 625, "s": 605, "text": "2002skr222 days ago" }, { "code": null, "e": 644, "s": 625, "text": "#include<iostream>" }, { "code": null, "e": 665, "s": 644, "text": "using namespace std;" }, { "code": null, "e": 677, "s": 665, "text": "int main(){" }, { "code": null, "e": 698, "s": 677, "text": "cout<<\"Hello World\";" }, { "code": null, "e": 708, "s": 698, "text": "return 0;" }, { "code": null, "e": 710, "s": 708, "text": "}" }, { "code": null, "e": 712, "s": 710, "text": "0" }, { "code": null, "e": 741, "s": 712, "text": "vedantchourasiya142 days ago" }, { "code": null, "e": 833, "s": 741, "text": "#include <iostream>using namespace std;int main() { cout << \"Hello, world!\"; return 0;}" }, { "code": null, "e": 835, "s": 833, "text": "0" }, { "code": null, "e": 852, "s": 835, "text": "gocode3 days ago" }, { "code": null, "e": 871, "s": 852, "text": "#include<iostream>" }, { "code": null, "e": 892, "s": 871, "text": "using namespace std;" }, { "code": null, "e": 905, "s": 894, "text": "int main()" }, { "code": null, "e": 907, "s": 905, "text": "{" }, { "code": null, "e": 938, "s": 907, "text": " cout<<\"Hello World\"<<endl;" }, { "code": null, "e": 952, "s": 938, "text": " return 0;" }, { "code": null, "e": 956, "s": 954, "text": "}" }, { "code": null, "e": 958, "s": 956, "text": "0" }, { "code": null, "e": 982, "s": 958, "text": "honeydancer253 days ago" }, { "code": null, "e": 1065, "s": 982, "text": "#include<iostream>using namespace std;main(){ cout <<\"Hello World\"; return 0;}" }, { "code": null, "e": 1067, "s": 1065, "text": "0" }, { "code": null, "e": 1094, "s": 1067, "text": "dikshasharmaug216 days ago" }, { "code": null, "e": 1154, "s": 1094, "text": "#include<iostrem.h>\nstd;\nint main(){\ncout<<\"hello world\";\n}" }, { "code": null, "e": 1156, "s": 1154, "text": "0" }, { "code": null, "e": 1176, "s": 1156, "text": "pshiv27041 week ago" }, { "code": null, "e": 1196, "s": 1176, "text": "Include<iostream.h>" }, { "code": null, "e": 1217, "s": 1196, "text": "using namespace std;" }, { "code": null, "e": 1231, "s": 1217, "text": "int main () {" }, { "code": null, "e": 1252, "s": 1231, "text": "cout<<\"Hello world\":" }, { "code": null, "e": 1262, "s": 1252, "text": "return 0;" }, { "code": null, "e": 1264, "s": 1262, "text": "}" }, { "code": null, "e": 1266, "s": 1264, "text": "0" }, { "code": null, "e": 1293, "s": 1266, "text": "annuchhikara20011 week ago" }, { "code": null, "e": 1312, "s": 1293, "text": "#include<iostream>" }, { "code": null, "e": 1333, "s": 1312, "text": "using namespace std;" }, { "code": null, "e": 1345, "s": 1333, "text": "int main(){" }, { "code": null, "e": 1366, "s": 1345, "text": "cout<<\"Hello World\";" }, { "code": null, "e": 1376, "s": 1366, "text": "return 0;" }, { "code": null, "e": 1378, "s": 1376, "text": "}" }, { "code": null, "e": 1380, "s": 1378, "text": "0" }, { "code": null, "e": 1401, "s": 1380, "text": "sk31951132 weeks ago" }, { "code": null, "e": 1420, "s": 1401, "text": "#include<iostream>" }, { "code": null, "e": 1441, "s": 1420, "text": "using namespace std;" }, { "code": null, "e": 1453, "s": 1441, "text": "int main ()" }, { "code": null, "e": 1455, "s": 1453, "text": "{" }, { "code": null, "e": 1476, "s": 1455, "text": "cout<<\"HELLO WOLD!\";" }, { "code": null, "e": 1486, "s": 1476, "text": "return 0;" }, { "code": null, "e": 1488, "s": 1486, "text": "}" }, { "code": null, "e": 1490, "s": 1488, "text": "0" }, { "code": null, "e": 1520, "s": 1490, "text": "sudhanshuranjan0292 weeks ago" }, { "code": null, "e": 1539, "s": 1520, "text": "#include<iostream>" }, { "code": null, "e": 1560, "s": 1539, "text": "Using namespace std;" }, { "code": null, "e": 1572, "s": 1560, "text": "Int main(){" }, { "code": null, "e": 1600, "s": 1572, "text": "Cout<<\"HELLOW WORLD\"<<endl;" }, { "code": null, "e": 1610, "s": 1600, "text": "Returns;}" }, { "code": null, "e": 1756, "s": 1610, "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": 1792, "s": 1756, "text": " Login to access your submissions. " }, { "code": null, "e": 1802, "s": 1792, "text": "\nProblem\n" }, { "code": null, "e": 1812, "s": 1802, "text": "\nContest\n" }, { "code": null, "e": 1875, "s": 1812, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2023, "s": 1875, "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": 2231, "s": 2023, "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": 2337, "s": 2231, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Minimum element in a max heap in C++.
Find the element with the least value in max heap. Let us consider below max heap. In max heap value of the root node is always greater than its childer. Because of this property, we can conclude that value will be present in one of the leaf nodes. If heap contains n nodes then there will be ceil(n/2) leaves. Max heap is a complete binary tree hence it can be represented in an array. In such heap the first leaf will be present after floor(n/2) index. So in our example, the first leave will be present at index 5. We can use the below algorithm to find min value in a max heap − 1. Find first leaf in a heap and consider its value as min 2. Iterate all remaining leaves and update min value if leaf with smaller value is found #include <iostream> #define SIZE(arr) (sizeof(arr) / sizeof(arr[0])) using namespace std; int getMinElement(int *heap, int n){ int minElement = heap[n / 2]; for (int i = n / 2 + 1; i < n; ++i) { minElement = min(minElement, heap[i]); } return minElement; } int main(){ int heap[] = {120, 90, 100, 70, 75, 80, 60, 25, 40, 35}; cout << "Min value: " << getMinElement(heap, SIZE(heap)) << "\n"; return 0; } When you compile and execute the above program. It generates the following output − Min value: 25
[ { "code": null, "e": 1113, "s": 1062, "text": "Find the element with the least value in max heap." }, { "code": null, "e": 1145, "s": 1113, "text": "Let us consider below max heap." }, { "code": null, "e": 1373, "s": 1145, "text": "In max heap value of the root node is always greater than its childer. Because of this property, we can conclude that value will be present in one of the leaf nodes. If heap contains n nodes then there will be ceil(n/2) leaves." }, { "code": null, "e": 1580, "s": 1373, "text": "Max heap is a complete binary tree hence it can be represented in an array. In such heap the first leaf will be present after floor(n/2) index. So in our example, the first leave will be present at index 5." }, { "code": null, "e": 1645, "s": 1580, "text": "We can use the below algorithm to find min value in a max heap −" }, { "code": null, "e": 1793, "s": 1645, "text": "1. Find first leaf in a heap and consider its value as min\n2. Iterate all remaining leaves and update min value if leaf with smaller value is found" }, { "code": null, "e": 2224, "s": 1793, "text": "#include <iostream>\n#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))\nusing namespace std;\nint getMinElement(int *heap, int n){\n int minElement = heap[n / 2];\n for (int i = n / 2 + 1; i < n; ++i) {\n minElement = min(minElement, heap[i]);\n }\n return minElement;\n}\nint main(){\n int heap[] = {120, 90, 100, 70, 75, 80, 60, 25, 40, 35};\n cout << \"Min value: \" << getMinElement(heap, SIZE(heap)) << \"\\n\";\n return 0;\n}" }, { "code": null, "e": 2308, "s": 2224, "text": "When you compile and execute the above program. It generates the following output −" }, { "code": null, "e": 2322, "s": 2308, "text": "Min value: 25" } ]
How to Make Countplot or barplot with Seaborn Catplot? - GeeksforGeeks
25 Nov, 2020 In Python, we can normally plot barcharts for numerical variables. But when it comes to the case of categorical variables then we cannot normally plot the count for each category. Here comes Seaborn Catplot in the picture. It allows you to plot the count of each category for non-numerical/categorical variables. Countplot gives a graphical visual for the count of observations in each category using bars. This cannot be used for quantitative variables. It can be created by passing the count value to the kind parameter. Example: Let’s take an example of a titanic dataset. Python3 # import librariesimport matplotlib.pyplot as pltimport seaborn as sns # setting background stylesns.set_style('darkgrid') # import datasetdata = sns.load_dataset('titanic')data.head() Output: Example 1: Creating the countplot Python3 # plot for count of passengers belonging# to each gendersns.catplot(x='sex', kind='count', data=data)plt.xlabel("Gender")plt.ylabel("Count") Output: Example 2: Creating the grouped countplot Python3 # Grouped Countplot/Barplot# Count of passengers who survived# or didn't of each gendersns.catplot(x='sex', hue='survived', kind='count', data=data) plt.xlabel("Gender")plt.ylabel("Count") Output: Example 3: Creating the horizontal countplot Python3 # Plotting horizontallysns.catplot(y='sex', hue='survived', kind='count', data=data) plt.xlabel("Count")plt.ylabel("Gender") Output: Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 26736, "s": 26708, "text": "\n25 Nov, 2020" }, { "code": null, "e": 27049, "s": 26736, "text": "In Python, we can normally plot barcharts for numerical variables. But when it comes to the case of categorical variables then we cannot normally plot the count for each category. Here comes Seaborn Catplot in the picture. It allows you to plot the count of each category for non-numerical/categorical variables." }, { "code": null, "e": 27259, "s": 27049, "text": "Countplot gives a graphical visual for the count of observations in each category using bars. This cannot be used for quantitative variables. It can be created by passing the count value to the kind parameter." }, { "code": null, "e": 27312, "s": 27259, "text": "Example: Let’s take an example of a titanic dataset." }, { "code": null, "e": 27320, "s": 27312, "text": "Python3" }, { "code": "# import librariesimport matplotlib.pyplot as pltimport seaborn as sns # setting background stylesns.set_style('darkgrid') # import datasetdata = sns.load_dataset('titanic')data.head()", "e": 27507, "s": 27320, "text": null }, { "code": null, "e": 27515, "s": 27507, "text": "Output:" }, { "code": null, "e": 27549, "s": 27515, "text": "Example 1: Creating the countplot" }, { "code": null, "e": 27557, "s": 27549, "text": "Python3" }, { "code": "# plot for count of passengers belonging# to each gendersns.catplot(x='sex', kind='count', data=data)plt.xlabel(\"Gender\")plt.ylabel(\"Count\")", "e": 27698, "s": 27557, "text": null }, { "code": null, "e": 27706, "s": 27698, "text": "Output:" }, { "code": null, "e": 27748, "s": 27706, "text": "Example 2: Creating the grouped countplot" }, { "code": null, "e": 27756, "s": 27748, "text": "Python3" }, { "code": "# Grouped Countplot/Barplot# Count of passengers who survived# or didn't of each gendersns.catplot(x='sex', hue='survived', kind='count', data=data) plt.xlabel(\"Gender\")plt.ylabel(\"Count\")", "e": 27957, "s": 27756, "text": null }, { "code": null, "e": 27965, "s": 27957, "text": "Output:" }, { "code": null, "e": 28010, "s": 27965, "text": "Example 3: Creating the horizontal countplot" }, { "code": null, "e": 28018, "s": 28010, "text": "Python3" }, { "code": "# Plotting horizontallysns.catplot(y='sex', hue='survived', kind='count', data=data) plt.xlabel(\"Count\")plt.ylabel(\"Gender\")", "e": 28156, "s": 28018, "text": null }, { "code": null, "e": 28164, "s": 28156, "text": "Output:" }, { "code": null, "e": 28179, "s": 28164, "text": "Python-Seaborn" }, { "code": null, "e": 28186, "s": 28179, "text": "Python" }, { "code": null, "e": 28284, "s": 28186, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28312, "s": 28284, "text": "Read JSON file using Python" }, { "code": null, "e": 28362, "s": 28312, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28384, "s": 28362, "text": "Python map() function" }, { "code": null, "e": 28428, "s": 28384, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 28446, "s": 28428, "text": "Python Dictionary" }, { "code": null, "e": 28469, "s": 28446, "text": "Taking input in Python" }, { "code": null, "e": 28504, "s": 28469, "text": "Read a file line by line in Python" }, { "code": null, "e": 28526, "s": 28504, "text": "Enumerate() in Python" }, { "code": null, "e": 28558, "s": 28526, "text": "How to Install PIP on Windows ?" } ]
Count number of substrings | Practice | GeeksforGeeks
Given a string of lowercase alphabets, count all possible substrings (not necessarily distinct) that have exactly k distinct characters. Example 1: Input: S = "aba", K = 2 Output: 3 Explanation: The substrings are: "ab", "ba" and "aba". Example 2: Input: S = "abaaca", K = 1 Output: 7 Explanation: The substrings are: "a", "b", "a", "aa", "a", "c", "a". Your Task: You don't need to read input or print anything. Your task is to complete the function substrCount() which takes the string S and an integer K as inputs and returns the number of substrings having exactly K distinct characters. Expected Time Complexity: O(|S|). Expected Auxiliary Space: O(1). Constraints: 1 ≤ |S| ≤ 105 1 ≤ K ≤ 26 -1 tejasbhagat543 months ago Java class Solution{ public static boolean isValid(String s,int k) { if(s.length()<k)return false; HashMap<Character ,Integer>map=new HashMap<>(); for(int i=0;i<s.length();i++) { char c=s.charAt(i); if(!(map.containsKey(c))) { map.put(c,i); } //return false; } if(map.size()==k)return true; return false; } long substrCount (String s, int k) { long ans=0; for(int i=0;i<s.length();i++) { for(int j=i+k;j<=s.length();j++) { if(isValid(s.substring(i,j),k)) { ans++; // System.out.println(s.substring(i,j)); } } } return ans; }} 0 Sourabh Shah9 months ago Sourabh Shah long long int atmost (string s, int k) { //code here. if(s.size()==0 || k==0) return 0; long long int c=0,ans=0,i=0,j=0,n=s.size(); int f[26]={0}; while(j<n){ f[s[j]-'a']++;="" if(f[s[j]-'a']="=1)c++;" while(i<="j" &&="" c="">k){ f[s[i]-'a']--; if(f[s[i]-'a']==0)c--; i++; } ans+=(j-i+1); j++; } return ans; } long long int substrCount (string s, int k) { //code here. return atmost(s,k)-atmost(s,k-1); } 0 Yuvraj Bedi This comment was deleted. 0 sudarshan maskare10 months ago sudarshan maskare Think->window concept->constant space->easy long long int atMostK(string& A, int K) { long long int i = 0, res = 0; int count[26]={0}; for (long long int j = 0; j < A.size(); ++j) { if (!count[A[j]-97]++) K--; while (K < 0) { if (!--count[A[i]-97]) K++; i++; } res += j - i + 1; } return res; } public: long long int substrCount (string s, int k) { return atMostK(s,k)-atMostK(s,k-1); } -1 Debjyoti Chattopadhyay10 months ago Debjyoti Chattopadhyay class Sol{ long substrCount (String str, int k) { long ans=0; int smap[]=new int[26]; int lmap[]=new int[26]; int e=-1; int ptrs=0; int ptrl=0; char prevs='@'; char prevl='@'; for(int i=0;i<str.length();i++){ while(ptrs<str.length()="" &&="" count(smap)<="k-1){" smap[str.charat(ptrs)-97]++;="" ptrs++;="" }="" if(count(smap)="=k)" smap[str.charat(--ptrs)-97]--;="" while(ptrl<str.length()="" &&="" count(lmap)<="k){" lmap[str.charat(ptrl)-97]++;="" ptrl++;="" }="" if(count(lmap)="=k+1)" lmap[str.charat(--ptrl)-97]--;="" ans+="diff(lmap,smap);" smap[str.charat(i)-97]--;="" lmap[str.charat(i)-97]--;="" }="" return(ans);="" }="" substrcount="" public="" int="" count(int="" arr[]){="" int="" c="0;" for(int="" i="0;i&lt;26;i++){" if(arr[i]="">0) c++; } return(c); }//count public int diff(int arr1[],int arr2[]){ int c=0; for(int i=0;i<26;i++) c+=(arr1[i]-arr2[i]); return(c); }//diff}//SolJAVA Soln +1 Aiiyan Sinha11 months ago Aiiyan Sinha Can anyone tell me why this solution is showing TLE https://ide.geeksforgeeks.o... 0 Soumya Jha11 months ago Soumya Jha @sandeep1103:disqus Unable to figure out a test case where input String is "hq" and k=1output should be 1, whereas the test case expects it to be 2 attaching the screenshot. https://uploads.disquscdn.c... 0 aadi1551 year ago aadi155 don't use unordered_map if getting tle make it(map) manully :) 0 Debarshi Maitra1 year ago Debarshi Maitra O(N) Solution : https://ide.geeksforgeeks.o... 0 Anup1 year ago Anup JAVA 0.75s https://ide.geeksforgeeks.o... 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": 364, "s": 226, "text": "Given a string of lowercase alphabets, count all possible substrings (not necessarily distinct) that have exactly k distinct characters. " }, { "code": null, "e": 376, "s": 364, "text": "\nExample 1:" }, { "code": null, "e": 466, "s": 376, "text": "Input:\nS = \"aba\", K = 2\nOutput:\n3\nExplanation:\nThe substrings are:\n\"ab\", \"ba\" and \"aba\".\n" }, { "code": null, "e": 477, "s": 466, "text": "Example 2:" }, { "code": null, "e": 586, "s": 477, "text": "Input: \nS = \"abaaca\", K = 1\nOutput:\n7\nExplanation:\nThe substrings are:\n\"a\", \"b\", \"a\", \"aa\", \"a\", \"c\", \"a\". \n" }, { "code": null, "e": 825, "s": 586, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function substrCount() which takes the string S and an integer K as inputs and returns the number of substrings having exactly K distinct characters." }, { "code": null, "e": 892, "s": 825, "text": "\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 931, "s": 892, "text": "\nConstraints:\n1 ≤ |S| ≤ 105\n1 ≤ K ≤ 26" }, { "code": null, "e": 934, "s": 931, "text": "-1" }, { "code": null, "e": 960, "s": 934, "text": "tejasbhagat543 months ago" }, { "code": null, "e": 965, "s": 960, "text": "Java" }, { "code": null, "e": 1745, "s": 965, "text": "class Solution{ public static boolean isValid(String s,int k) { if(s.length()<k)return false; HashMap<Character ,Integer>map=new HashMap<>(); for(int i=0;i<s.length();i++) { char c=s.charAt(i); if(!(map.containsKey(c))) { map.put(c,i); } //return false; } if(map.size()==k)return true; return false; } long substrCount (String s, int k) { long ans=0; for(int i=0;i<s.length();i++) { for(int j=i+k;j<=s.length();j++) { if(isValid(s.substring(i,j),k)) { ans++; // System.out.println(s.substring(i,j)); } } } return ans; }}" }, { "code": null, "e": 1747, "s": 1745, "text": "0" }, { "code": null, "e": 1772, "s": 1747, "text": "Sourabh Shah9 months ago" }, { "code": null, "e": 1785, "s": 1772, "text": "Sourabh Shah" }, { "code": null, "e": 2277, "s": 1785, "text": "long long int atmost (string s, int k) { //code here. if(s.size()==0 || k==0) return 0; long long int c=0,ans=0,i=0,j=0,n=s.size(); int f[26]={0}; while(j<n){ f[s[j]-'a']++;=\"\" if(f[s[j]-'a']=\"=1)c++;\" while(i<=\"j\" &&=\"\" c=\"\">k){ f[s[i]-'a']--; if(f[s[i]-'a']==0)c--; i++; } ans+=(j-i+1); j++; } return ans; } long long int substrCount (string s, int k) { //code here. return atmost(s,k)-atmost(s,k-1); }" }, { "code": null, "e": 2279, "s": 2277, "text": "0" }, { "code": null, "e": 2291, "s": 2279, "text": "Yuvraj Bedi" }, { "code": null, "e": 2317, "s": 2291, "text": "This comment was deleted." }, { "code": null, "e": 2319, "s": 2317, "text": "0" }, { "code": null, "e": 2350, "s": 2319, "text": "sudarshan maskare10 months ago" }, { "code": null, "e": 2368, "s": 2350, "text": "sudarshan maskare" }, { "code": null, "e": 2899, "s": 2368, "text": "Think->window concept->constant space->easy long long int atMostK(string& A, int K) { long long int i = 0, res = 0; int count[26]={0}; for (long long int j = 0; j < A.size(); ++j) { if (!count[A[j]-97]++) K--; while (K < 0) { if (!--count[A[i]-97]) K++; i++; } res += j - i + 1; } return res; } public: long long int substrCount (string s, int k) { return atMostK(s,k)-atMostK(s,k-1); }" }, { "code": null, "e": 2902, "s": 2899, "text": "-1" }, { "code": null, "e": 2938, "s": 2902, "text": "Debjyoti Chattopadhyay10 months ago" }, { "code": null, "e": 2961, "s": 2938, "text": "Debjyoti Chattopadhyay" }, { "code": null, "e": 4002, "s": 2961, "text": "class Sol{ long substrCount (String str, int k) { long ans=0; int smap[]=new int[26]; int lmap[]=new int[26]; int e=-1; int ptrs=0; int ptrl=0; char prevs='@'; char prevl='@'; for(int i=0;i<str.length();i++){ while(ptrs<str.length()=\"\" &&=\"\" count(smap)<=\"k-1){\" smap[str.charat(ptrs)-97]++;=\"\" ptrs++;=\"\" }=\"\" if(count(smap)=\"=k)\" smap[str.charat(--ptrs)-97]--;=\"\" while(ptrl<str.length()=\"\" &&=\"\" count(lmap)<=\"k){\" lmap[str.charat(ptrl)-97]++;=\"\" ptrl++;=\"\" }=\"\" if(count(lmap)=\"=k+1)\" lmap[str.charat(--ptrl)-97]--;=\"\" ans+=\"diff(lmap,smap);\" smap[str.charat(i)-97]--;=\"\" lmap[str.charat(i)-97]--;=\"\" }=\"\" return(ans);=\"\" }=\"\" substrcount=\"\" public=\"\" int=\"\" count(int=\"\" arr[]){=\"\" int=\"\" c=\"0;\" for(int=\"\" i=\"0;i&lt;26;i++){\" if(arr[i]=\"\">0) c++; } return(c); }//count public int diff(int arr1[],int arr2[]){ int c=0; for(int i=0;i<26;i++) c+=(arr1[i]-arr2[i]); return(c); }//diff}//SolJAVA Soln" }, { "code": null, "e": 4005, "s": 4002, "text": "+1" }, { "code": null, "e": 4031, "s": 4005, "text": "Aiiyan Sinha11 months ago" }, { "code": null, "e": 4044, "s": 4031, "text": "Aiiyan Sinha" }, { "code": null, "e": 4096, "s": 4044, "text": "Can anyone tell me why this solution is showing TLE" }, { "code": null, "e": 4127, "s": 4096, "text": "https://ide.geeksforgeeks.o..." }, { "code": null, "e": 4129, "s": 4127, "text": "0" }, { "code": null, "e": 4153, "s": 4129, "text": "Soumya Jha11 months ago" }, { "code": null, "e": 4164, "s": 4153, "text": "Soumya Jha" }, { "code": null, "e": 4184, "s": 4164, "text": "@sandeep1103:disqus" }, { "code": null, "e": 4312, "s": 4184, "text": "Unable to figure out a test case where input String is \"hq\" and k=1output should be 1, whereas the test case expects it to be 2" }, { "code": null, "e": 4338, "s": 4312, "text": "attaching the screenshot." }, { "code": null, "e": 4369, "s": 4338, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 4371, "s": 4369, "text": "0" }, { "code": null, "e": 4389, "s": 4371, "text": "aadi1551 year ago" }, { "code": null, "e": 4397, "s": 4389, "text": "aadi155" }, { "code": null, "e": 4436, "s": 4397, "text": "don't use unordered_map if getting tle" }, { "code": null, "e": 4460, "s": 4436, "text": "make it(map) manully :)" }, { "code": null, "e": 4462, "s": 4460, "text": "0" }, { "code": null, "e": 4488, "s": 4462, "text": "Debarshi Maitra1 year ago" }, { "code": null, "e": 4504, "s": 4488, "text": "Debarshi Maitra" }, { "code": null, "e": 4551, "s": 4504, "text": "O(N) Solution : https://ide.geeksforgeeks.o..." }, { "code": null, "e": 4553, "s": 4551, "text": "0" }, { "code": null, "e": 4568, "s": 4553, "text": "Anup1 year ago" }, { "code": null, "e": 4573, "s": 4568, "text": "Anup" }, { "code": null, "e": 4615, "s": 4573, "text": "JAVA 0.75s https://ide.geeksforgeeks.o..." }, { "code": null, "e": 4761, "s": 4615, "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": 4797, "s": 4761, "text": " Login to access your submissions. " }, { "code": null, "e": 4807, "s": 4797, "text": "\nProblem\n" }, { "code": null, "e": 4817, "s": 4807, "text": "\nContest\n" }, { "code": null, "e": 4880, "s": 4817, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5028, "s": 4880, "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": 5236, "s": 5028, "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": 5342, "s": 5236, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Feature Scaling — Effect Of Different Scikit-Learn Scalers: Deep Dive | by Kaushik Choudhury | Towards Data Science
In supervised machine learning, we calculate the value of the output variable by supplying input variable values to an algorithm. Machine learning algorithm relates the input and output variable with a mathematical function. Output variable value = (2.4* Input Variable 1 )+ (6*Input Variable 2) + 3.5 There are a few specific assumptions behind each of the machine learning algorithms. To build an accurate model, we need to ensure that the input data meets those assumptions. In case, the data fed to machine learning algorithms do not satisfy the assumptions then prediction accuracy of the model is compromised. Most of the supervised algorithms in sklearn require standard normally distributed input data centred around zero and have variance in the same order. If the value range from 1 to 10 for an input variable and 4000 to 700,000 for the other variable then the second input variable values will dominate and the algorithm will not be able to learn from other features correctly as expected. In this article, I will illustrate the effect of scaling the input variables with different scalers in scikit-learn and three different regression algorithms. In the below code, we import the packages we will be using for the analysis. We will create the test data with the help of make_regression from sklearn.datasets import make_regressionimport numpy as npfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import *from sklearn.linear_model import* We will use the sample size of 100 records with three independent (input) variables. Further, we will inject three outliers using the method “np.random.normal” X, y, coef = make_regression(n_samples=100, n_features=3,noise=2,tail_strength=0.5,coef=True, random_state=0)X[:3] = 1 + 0.9 * np.random.normal(size=(3,3))y[:3] = 1 + 2 * np.random.normal(size=3) We will print the real coefficients of the sample datasets as a reference and compare with predicted coefficients. print("The real coefficients are ". coef) We will train the algorithm with 80 records and reserve the remaining 20 samples unseen by the algorithm earlier for testing the accuracy of the model. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20,random_state=42) We will study the scaling effect with the scikit-learn StandardScaler, MinMaxScaler, power transformers, RobustScaler and, MaxAbsScaler. regressors=[StandardScaler(),MinMaxScaler(),PowerTransformer(method='yeo-johnson'),RobustScaler(quantile_range=(25,75)),MaxAbsScaler()] All the regression model we will be using is mentioned in a list object. models=[Ridge(alpha=1.0),HuberRegressor(),LinearRegression()] In the code below, we scale the training and test sample input variable by calling each scaler in succession from the regressor list defined earlier. We will draw a scatter plot of the original first input variable and scaled the first input variable to get an insight on various scaling. We see each of these plots little later in this article. Further, we fit each of the models with scaled input variables from different scalers and predict the values of dependent variables for test sample dataset. for regressor in regressors: X_train_scaled=regressor.fit_transform(X_train) X_test_scaled=regressor.transform(X_test) Scaled =plt.scatter(X_train_scaled[:,0],y_train, marker='^', alpha=0.8) Original=plt.scatter(X_train[:,0],y_train) plt.legend((Scaled, Original),('Scaled', 'Original'),loc='best',fontsize=13) plt.xlabel("Feature 1") plt.ylabel("Train Target") plt.show() for model in models: reg_lin=model.fit(X_train_scaled, y_train) y_pred=reg_lin.predict(X_test_scaled) print("The calculated coeffiects with ", model , "and", regressor, reg_lin.coef_) Finally, the predicted coefficients from the model fit are printed for the comparison with real coefficients. On first glance itself, we can deduce that same regression estimator predicts different values of the coefficients based on the scalers.Predicted coefficients with MaxAbsScaler and MinMax scaler is quite far from true coefficient values.We can see the importance of appropriate scalers in the prediction accuracy of the model from this example. As a self-exploration and learning exercise, I will encourage you all to calculate the R2 score and Root Mean Square Error (RMSE) for each of the training and testing set combination and compare it with each other. Now that we understand the importance of scaling and selecting suitable scalers, we will get into the inner working of each scaler. Standard Scaler: It is one of the popular scalers used in various real-life machine learning projects. The mean value and standard deviation of each input variable sample set are determined separately. It then subtracts the mean from each data point and divides by the standard deviation to transforms the variables to zero mean and standard deviation of one. It does not bound the values to a specific range, and it can be an issue for a few algorithms. MinMax Scaler: All the numeric values scaled between 0 and 1 with a MinMax Scaler Xscaled= (X-Xmin)/(Xmax-Xmin) MinMax scaling is quite affected by the outliers. If we have one or more extreme outlier in our data set, then the min-max scaler will place the normal values quite closely to accommodate the outliers within the 0 and 1 range. We saw earlier that the predicted coefficients with MinMax scaler are approximately three times the real coefficient. I will recommend not to use MinMax Scaler with outlier dataset. Robust Scaler- Robust scaler is one of the best-suited scalers for outlier data sets. It scales the data according to the interquartile range. The interquartile range is the middle range where most of the data points exist. Power Transformer Scaler: Power transformer tries to scale the data like Gaussian. It attempts optimal scaling to stabilize variance and minimize skewness through maximum likelihood estimation. Sometimes, Power transformer fails to scale Gaussian-like results hence it is important to check the plot the scaled data MaxAbs Scaler: MaxAbsScaler is best suited to scale the sparse data. It scales each feature by dividing it with the largest maximum value in each feature. For example, if an input variable has the original value [2,-1,0,1] then MaxAbs will scale it as [1,-0.5,0,0.5]. It divided each value with the highest value i.e. 2. It is not advised to use with large outlier dataset. We have learnt that scaling the input variables with suitable scaler is as vital as selecting the right machine learning algorithm. Few of the scalers are quite sensitive to outlier dataset, and others are robust. Each of the scalers in Scikit-Learn has its strengths and limitations, and we need to be mindful of it while using it. It also highlights the importance of performing the exploratory data analysis (EDA) initially to identify the presence or absence of outliers and other idiosyncrasies which will guide the selection of appropriate scaler. In my article, 5 Advanced Visualisation for Exploratory data analysis (EDA) you can learn more about this area. In case, you would like to learn a structured approach to identify the appropriate independent variables to make accurate predictions then read my article “How to identify the right independent variables for Machine Learning Supervised. """Full Code"""from sklearn.datasets import make_regressionimport numpy as npfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import *from sklearn.linear_model import*import matplotlib.pyplot as pltimport seaborn as snsX, y, coef = make_regression(n_samples=100, n_features=3,noise=2,tail_strength=0.5,coef=True, random_state=0)print("The real coefficients are ", coef)X[:3] = 1 + 0.9 * np.random.normal(size=(3,3))y[:3] = 1 + 2 * np.random.normal(size=3)X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.20,random_state=42)regressors=[StandardScaler(),MinMaxScaler(),PowerTransformer(method='yeo-johnson'),RobustScaler(quantile_range=(25, 75)),MaxAbsScaler()]models=[Ridge(alpha=1.0),HuberRegressor(),LinearRegression()]for regressor in regressors: X_train_scaled=regressor.fit_transform(X_train) X_test_scaled=regressor.transform(X_test) Scaled =plt.scatter(X_train_scaled[:,0],y_train, marker='^', alpha=0.8) Original=plt.scatter(X_train[:,0],y_train) plt.legend((Scaled, Original),('Scaled', 'Original'),loc='best',fontsize=13) plt.xlabel("Feature 1") plt.ylabel("Train Target") plt.show() for model in models: reg_lin=model.fit(X_train_scaled, y_train) y_pred=reg_lin.predict(X_test_scaled) print("The calculated coeffiects with ", model , "and", regressor, reg_lin.coef_)
[ { "code": null, "e": 397, "s": 172, "text": "In supervised machine learning, we calculate the value of the output variable by supplying input variable values to an algorithm. Machine learning algorithm relates the input and output variable with a mathematical function." }, { "code": null, "e": 474, "s": 397, "text": "Output variable value = (2.4* Input Variable 1 )+ (6*Input Variable 2) + 3.5" }, { "code": null, "e": 788, "s": 474, "text": "There are a few specific assumptions behind each of the machine learning algorithms. To build an accurate model, we need to ensure that the input data meets those assumptions. In case, the data fed to machine learning algorithms do not satisfy the assumptions then prediction accuracy of the model is compromised." }, { "code": null, "e": 1175, "s": 788, "text": "Most of the supervised algorithms in sklearn require standard normally distributed input data centred around zero and have variance in the same order. If the value range from 1 to 10 for an input variable and 4000 to 700,000 for the other variable then the second input variable values will dominate and the algorithm will not be able to learn from other features correctly as expected." }, { "code": null, "e": 1334, "s": 1175, "text": "In this article, I will illustrate the effect of scaling the input variables with different scalers in scikit-learn and three different regression algorithms." }, { "code": null, "e": 1473, "s": 1334, "text": "In the below code, we import the packages we will be using for the analysis. We will create the test data with the help of make_regression" }, { "code": null, "e": 1657, "s": 1473, "text": "from sklearn.datasets import make_regressionimport numpy as npfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import *from sklearn.linear_model import*" }, { "code": null, "e": 1817, "s": 1657, "text": "We will use the sample size of 100 records with three independent (input) variables. Further, we will inject three outliers using the method “np.random.normal”" }, { "code": null, "e": 2013, "s": 1817, "text": "X, y, coef = make_regression(n_samples=100, n_features=3,noise=2,tail_strength=0.5,coef=True, random_state=0)X[:3] = 1 + 0.9 * np.random.normal(size=(3,3))y[:3] = 1 + 2 * np.random.normal(size=3)" }, { "code": null, "e": 2128, "s": 2013, "text": "We will print the real coefficients of the sample datasets as a reference and compare with predicted coefficients." }, { "code": null, "e": 2170, "s": 2128, "text": "print(\"The real coefficients are \". coef)" }, { "code": null, "e": 2322, "s": 2170, "text": "We will train the algorithm with 80 records and reserve the remaining 20 samples unseen by the algorithm earlier for testing the accuracy of the model." }, { "code": null, "e": 2422, "s": 2322, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20,random_state=42)" }, { "code": null, "e": 2559, "s": 2422, "text": "We will study the scaling effect with the scikit-learn StandardScaler, MinMaxScaler, power transformers, RobustScaler and, MaxAbsScaler." }, { "code": null, "e": 2695, "s": 2559, "text": "regressors=[StandardScaler(),MinMaxScaler(),PowerTransformer(method='yeo-johnson'),RobustScaler(quantile_range=(25,75)),MaxAbsScaler()]" }, { "code": null, "e": 2768, "s": 2695, "text": "All the regression model we will be using is mentioned in a list object." }, { "code": null, "e": 2830, "s": 2768, "text": "models=[Ridge(alpha=1.0),HuberRegressor(),LinearRegression()]" }, { "code": null, "e": 3176, "s": 2830, "text": "In the code below, we scale the training and test sample input variable by calling each scaler in succession from the regressor list defined earlier. We will draw a scatter plot of the original first input variable and scaled the first input variable to get an insight on various scaling. We see each of these plots little later in this article." }, { "code": null, "e": 3333, "s": 3176, "text": "Further, we fit each of the models with scaled input variables from different scalers and predict the values of dependent variables for test sample dataset." }, { "code": null, "e": 3950, "s": 3333, "text": "for regressor in regressors: X_train_scaled=regressor.fit_transform(X_train) X_test_scaled=regressor.transform(X_test) Scaled =plt.scatter(X_train_scaled[:,0],y_train, marker='^', alpha=0.8) Original=plt.scatter(X_train[:,0],y_train) plt.legend((Scaled, Original),('Scaled', 'Original'),loc='best',fontsize=13) plt.xlabel(\"Feature 1\") plt.ylabel(\"Train Target\") plt.show() for model in models: reg_lin=model.fit(X_train_scaled, y_train) y_pred=reg_lin.predict(X_test_scaled) print(\"The calculated coeffiects with \", model , \"and\", regressor, reg_lin.coef_)" }, { "code": null, "e": 4060, "s": 3950, "text": "Finally, the predicted coefficients from the model fit are printed for the comparison with real coefficients." }, { "code": null, "e": 4405, "s": 4060, "text": "On first glance itself, we can deduce that same regression estimator predicts different values of the coefficients based on the scalers.Predicted coefficients with MaxAbsScaler and MinMax scaler is quite far from true coefficient values.We can see the importance of appropriate scalers in the prediction accuracy of the model from this example." }, { "code": null, "e": 4620, "s": 4405, "text": "As a self-exploration and learning exercise, I will encourage you all to calculate the R2 score and Root Mean Square Error (RMSE) for each of the training and testing set combination and compare it with each other." }, { "code": null, "e": 4752, "s": 4620, "text": "Now that we understand the importance of scaling and selecting suitable scalers, we will get into the inner working of each scaler." }, { "code": null, "e": 5207, "s": 4752, "text": "Standard Scaler: It is one of the popular scalers used in various real-life machine learning projects. The mean value and standard deviation of each input variable sample set are determined separately. It then subtracts the mean from each data point and divides by the standard deviation to transforms the variables to zero mean and standard deviation of one. It does not bound the values to a specific range, and it can be an issue for a few algorithms." }, { "code": null, "e": 5289, "s": 5207, "text": "MinMax Scaler: All the numeric values scaled between 0 and 1 with a MinMax Scaler" }, { "code": null, "e": 5319, "s": 5289, "text": "Xscaled= (X-Xmin)/(Xmax-Xmin)" }, { "code": null, "e": 5728, "s": 5319, "text": "MinMax scaling is quite affected by the outliers. If we have one or more extreme outlier in our data set, then the min-max scaler will place the normal values quite closely to accommodate the outliers within the 0 and 1 range. We saw earlier that the predicted coefficients with MinMax scaler are approximately three times the real coefficient. I will recommend not to use MinMax Scaler with outlier dataset." }, { "code": null, "e": 5952, "s": 5728, "text": "Robust Scaler- Robust scaler is one of the best-suited scalers for outlier data sets. It scales the data according to the interquartile range. The interquartile range is the middle range where most of the data points exist." }, { "code": null, "e": 6268, "s": 5952, "text": "Power Transformer Scaler: Power transformer tries to scale the data like Gaussian. It attempts optimal scaling to stabilize variance and minimize skewness through maximum likelihood estimation. Sometimes, Power transformer fails to scale Gaussian-like results hence it is important to check the plot the scaled data" }, { "code": null, "e": 6423, "s": 6268, "text": "MaxAbs Scaler: MaxAbsScaler is best suited to scale the sparse data. It scales each feature by dividing it with the largest maximum value in each feature." }, { "code": null, "e": 6642, "s": 6423, "text": "For example, if an input variable has the original value [2,-1,0,1] then MaxAbs will scale it as [1,-0.5,0,0.5]. It divided each value with the highest value i.e. 2. It is not advised to use with large outlier dataset." }, { "code": null, "e": 6975, "s": 6642, "text": "We have learnt that scaling the input variables with suitable scaler is as vital as selecting the right machine learning algorithm. Few of the scalers are quite sensitive to outlier dataset, and others are robust. Each of the scalers in Scikit-Learn has its strengths and limitations, and we need to be mindful of it while using it." }, { "code": null, "e": 7196, "s": 6975, "text": "It also highlights the importance of performing the exploratory data analysis (EDA) initially to identify the presence or absence of outliers and other idiosyncrasies which will guide the selection of appropriate scaler." }, { "code": null, "e": 7308, "s": 7196, "text": "In my article, 5 Advanced Visualisation for Exploratory data analysis (EDA) you can learn more about this area." }, { "code": null, "e": 7545, "s": 7308, "text": "In case, you would like to learn a structured approach to identify the appropriate independent variables to make accurate predictions then read my article “How to identify the right independent variables for Machine Learning Supervised." } ]
Real-time Twitter Sentiment Analysis for Brand Improvement and Topic Tracking (Chapter 2/3) | by Chulong Li | Towards Data Science
The tutorial will teach you how to step-by-step apply 1) Nature Language Processing and Sentiment Analysis on Twitter data, and 2) utilize Plotly to build an interactive data visualization. This a standalone component to perform sentiment analysis & topic tracking and build the analytical dashboard on Jupiter Notebook, although it’s the second part of my comprehensive real-time Twitter monitoring system tutorial. Streaming Twitter data collection is explained and implemented in previous chapter. Chapter 1: Collecting Twitter Data using Streaming Twitter API with Tweepy, MySQL, & Python Chapter 2 (You’re here!): Twitter Sentiment Analysis and Interactive Data Visualization using RE, TextBlob, NLTK, and Plotly Chapter 3: Deploy a Real-time Twitter Analytical Web App on Heroku using Dash & Plotly in Python Chapter 4 (Optional): Parallelize Streaming Twitter Sentiment Analysis using Scala, Kafka and Spark Streaming The analytical dashboard (with full code) above is what we’ll do today, which lays the foundation of the Real-time Twitter Monitoring Web App below in next chapter, as Dash (python framework for analytical web apps) is written on top of Plotly. Check my GitHub Repo for more details. Tech Stack of Chapter: RE, NLTK, TextBlob, Plotly, MySQL, Python (time, datetime, math, itertools) RE: Regular expression operations to identify whether a pattern exists in a given sequence of characters or not NLTK: Natural Language Toolkit, a leading platform for building Python programs to work with human language data TextBlob: Natural Language Processing library for processing textual data, providing a simple API for diving into common NLP. Plotly: An interactive, open-source, and browser-based graphing library for Python First, we need to extract the Twitter data from data source. You can directly read from sample_data.csv for simplicity. df = pd.read_csv("sample_data.csv") Or in a more formal way, extract data from our MySQL database, which has been set up and filled with real-time Twitter data in the Chapter 1. db_connection = mysql.connector.connect( host="localhost", user="root", passwd="password", database="TwitterDB", charset = 'utf8' )time_now = datetime.datetime.utcnow()time_10mins_before = datetime.timedelta(hours=0,minutes=10)) \ .strftime('%Y-%m-%d %H:%M:%S'time_interval = time_now - time_10mins_before And read data released in last 30 minutes and load it into Pandas DataFrame via SQL query. query = "SELECT id_str, text, created_at, polarity, \ user_location FROM {} WHERE created_at >= '{}'" \ .format(settings.TABLE_NAME, time_interval)df = pd.read_sql(query, con=db_connection) Then convert DATETIME (MySQL data type) into Datetime (Pandas data type). # UTC for date time at defaultdf['created_at'] = pd.to_datetime(df['created_at']) The core of sentiment analysis is to use TextBlob in order to extract the polarity & subjectivity from tweet texts, which is actually done by the data preprocessing for better data storage in the previous chapter. Negative tweets represent as -1, positive tweets represent as +1, and neutral tweets represent as 0 . from textblob import TextBlobsentiment = TextBlob(tweet_text).sentimentpolarity = sentiment.polaritysubjectivity = sentiment.subjectivity Convert the entire time serises into groups of 2 seconds, and count the number of sentiment for each kind of polarities (e.g. -1, 0, and 1) in each time-interval group. Apply unstack-stack technology to make sure all categories in each group are displayed even if one of categories doesn't have any value. As we only display real-time tweets posted in last 30 minutes, groups of 2-second interval could best display on the screen in practice. After that, rename the columns to allow them self explanatory. # Clean and transform data to enable time seriesresult = df.groupby( \ [pd.Grouper(key='created_at', freq='2s'), 'polarity'] \ ).count().unstack(fill_value=0).stack().reset_index()result = result.rename(columns= \ { "id_str": "Num of '{}' mentions".format(TRACK_WORD), \ "created_at":"Time in UTC" }) Record the time series with 2-second interval for further index usage. time_series = result["Time in UTC"][result['polarity']==0] \ .reset_index(drop=True) Use simple Plotly Express to quick visualize the line chart. Note: Plotly Express is a terse, consistent, high-level wrapper of plotly.graph_objects for rapid data exploration and figure generation. import plotly.express as pxfig = px.line(result, x='Time in UTC', \ y="Num of '{}' mentions".format(TRACK_WORD), \ color='polarity')fig.show() In order to tracking the hottest words or the most frequency tokens in the tweets, we join all tweet texts, remove the urls, clean the ‘RT’ and ‘&’ (a.k.a. ‘&amp;’ )symbols, and convert all characters into lowercases. content = ' '.join(df["text"])content = re.sub(r"http\S+", "", content)content = content.replace('RT ', ' ').replace('&amp;', 'and')content = re.sub('[^A-Za-z0-9]+', ' ', content)content = content.lower() Use python script to download these 2 files from NLTK at the first time. Punkt Sentence Tokenizer is used to divide a text into a list of sentences by using an unsupervised algorithm. import nltknltk.download('punkt')nltk.download('stopwords') Then tokenize the entire text from all tweets, use Stop Words to remove commonly used words, and extract 10 most common words in the Frequency Distribution of all words. from nltk.probability import FreqDistfrom nltk.tokenize import word_tokenizefrom nltk.corpus import stopwordstokenized_word = word_tokenize(content)stop_words=set(stopwords.words("english"))filtered_sent=[]for w in tokenized_word: if w not in stop_words: filtered_sent.append(w)fdist = FreqDist(filtered_sent)fd = pd.DataFrame(fdist.most_common(10), \ columns = ["Word","Frequency"]).drop([0]).reindex() Use simple Plotly Express again to quick visualize the bar chart. import plotly.express as pxfig = px.bar(fd, x="Word", y="Frequency")fig.update_traces(marker_color='rgb(240,128,128)', \ marker_line_color='rgb(8,48,107)', \ marker_line_width=1.5, opacity=0.8)fig.show() To explore users’ geographic distributions, we need to identify their locations through their user profile rather than the locations attached with tweets, since less than 1% people will attach their tweet locations. However, according to locations in users’ profile, they may include one or more of counties, cities, states, countries, or planets. Thus, filtering these data into US state-level locations is the core of geographic segmentation recognization. Set up all state names and their abbreviations as constants for further abbreviation-name transformation. STATES = ['Alabama', 'AL', 'Alaska', 'AK', \ ...... # Text hided for readability \ 'WV', 'Wisconsin', 'WI', 'Wyoming', 'WY']STATE_DICT = dict(itertools.zip_longest(*[iter(STATES)] * 2, fillvalue=""))INV_STATE_DICT = dict((v,k) for k,v in STATE_DICT.items()) Extract the state information from their locations by iterating the list of state names and the list of user locations. is_in_US=[]geo = df[['user_location']]df = df.fillna(" ")for x in df['user_location']: check = False for s in STATES: if s in x: is_in_US.append(STATE_DICT[s] if s in STATE_DICT else s) check = True break if not check: is_in_US.append(None)geo_dist = pd.DataFrame(is_in_US, columns['State']) \ .dropna().reset_index() Count the number of tweets posted in each state of US, and use logarithmic number to avoid the extreme values (e.g. 500+ in California and 3 in North Dakota) for better visualization. geo_dist = geo_dist.groupby('State').count(). \ rename(columns={"index": "Number"}).sort_values( \ by=['Number'], ascending=False).reset_index()geo_dist["Log Num"] = geo_dist["Number"] \ .apply(lambda x: math.log(x, 2)) Add explanatory text information for the hover text on later dashboard. geo_dist['Full State Name'] = geo_dist['State'] \ .apply(lambda x: INV_STATE_DICT[x])geo_dist['text'] = geo_dist['Full State Name'] + '<br>' + \ 'Num: ' + geo_dist['Number'].astype(str) This time, we use Plotly (not Plotly Express) to visualize the USA map. Note: plotly.graph_objects is the core of Plotly Library containing more generic functions for more complex usage.locationmode is the set of locations match entries in “locations”. text is the hover text. marker_line_color is the color of line markers between states. Set geo_scope to limit map scope to USA. import plotly.graph_objects as gofig = go.Figure(data=go.Choropleth( locations=geo_dist['State'], # Spatial coordinates z = geo_dist['Log Num'].astype(float), # Data to be color-coded locationmode = 'USA-states', colorscale = "Reds", text=geo_dist['text'], marker_line_color='white', # line markers between states colorbar_title = "Numbers in Log2"))fig.update_layout( geo_scope='usa', )fig.show() Now we could integrate all data visualization parts into one dashboard using Plotly.subplots. Displaying multiple figures simultaneously can greatly improve the reading efficiency and enhance the comparability among multiple insights. First, create a Plotly Figure containing 2×2 subplots with Line Chart in the left, Map in the top right, and Bar Chart in the bottom right. from plotly.subplots import make_subplotsfig = make_subplots( rows=2, cols=2, column_widths=[1, 0.4], row_heights=[0.6, 0.4], specs=[[{"type": "scatter", "rowspan": 2}, {"type": "choropleth"}], [None, {"type": "bar"}]] ) Add three Lines of negatives, neutrals, and positives in the first subplot using add_trace and go.Scatter . In addition, row and col represent the place of this subplot in the big figure. fig.add_trace(go.Scatter( x=time_series, y=result["Num of '{}' mentions" \ .format(settings.TRACK_WORDS[0])] \ [result['polarity']==0].reset_index(drop=True), \ name="Neural", opacity=0.8), row=1, col=1) fig.add_trace(go.Scatter( x=time_series, y=result["Num of '{}' mentions" \ .format(settings.TRACK_WORDS[0])] \ [result['polarity']==-1].reset_index(drop=True), name="Negative", opacity=0.8), row=1, col=1)fig.add_trace(go.Scatter( x=time_series, y=result["Num of '{}' mentions" \ .format(settings.TRACK_WORDS[0])] \ [result['polarity']==1].reset_index(drop=True), \ name="Positive", opacity=0.8), row=1, col=1) Add the Bar Chart for the topic frequency distribution using add_trace and go.Bar . You may use rgb(xx,xx,xx) or rgba(xx,xx,xx,x) to change the color of certain elements in the figure. fig.add_trace(go.Bar(x=fd["Word"], y=fd["Frequency"], \ name="Freq Dist"), row=2, col=2)fig.update_traces(marker_color='rgb(59, 89, 152)', \ marker_line_color='rgb(8,48,107)', \ marker_line_width=0.5, opacity=0.7, row=2, col=2) Then insert the Map in the top right, and set locations and numbers per location. fig.add_trace(go.Choropleth( locations=geo_dist['State'], # Spatial coordinates z = geo_dist['Log Num'].astype(float), # Data to be color-coded locationmode = 'USA-states', colorscale = "Blues", text=geo_dist['text'], # hover text showscale=False, geo = 'geo' ), row=1, col=2) Add title in the layout of our figure, reduce the geo-scope of our map, turn the template theme into the dark, and add annotations for the layout using go.layout.Annotation. fig.update_layout( title_text = \ "Real-time tracking '{}' mentions on Twitter {} UTC" \ .format(settings.TRACK_WORDS[0] ,datetime.datetime.utcnow().strftime('%m-%d %H:%M') \ ), geo = dict( scope='usa', ), template="plotly_dark", margin=dict(r=20, t=50, b=50, l=20), annotations=[ go.layout.Annotation( text="Source: Twitter", showarrow=False, xref="paper", yref="paper", x=0, y=0) ], showlegend=False, xaxis_rangeslider_visible=True) Last, display all subplots in the single figure. fig.show() Author’s Words: A little bit complex in this chapter as it uses NLP and sentiment analysis approaches to transfer data points into insights. Further improvement on topic tracking can be implemented by using advanced NLP methods. Next chapter will be the most exciting part to integrate and deploy all functions on the Heroku server using Dash. As always, I appreciate for any feedback! 😃 Update on 9/20: Chapter 3 has been published !
[ { "code": null, "e": 361, "s": 171, "text": "The tutorial will teach you how to step-by-step apply 1) Nature Language Processing and Sentiment Analysis on Twitter data, and 2) utilize Plotly to build an interactive data visualization." }, { "code": null, "e": 672, "s": 361, "text": "This a standalone component to perform sentiment analysis & topic tracking and build the analytical dashboard on Jupiter Notebook, although it’s the second part of my comprehensive real-time Twitter monitoring system tutorial. Streaming Twitter data collection is explained and implemented in previous chapter." }, { "code": null, "e": 764, "s": 672, "text": "Chapter 1: Collecting Twitter Data using Streaming Twitter API with Tweepy, MySQL, & Python" }, { "code": null, "e": 889, "s": 764, "text": "Chapter 2 (You’re here!): Twitter Sentiment Analysis and Interactive Data Visualization using RE, TextBlob, NLTK, and Plotly" }, { "code": null, "e": 986, "s": 889, "text": "Chapter 3: Deploy a Real-time Twitter Analytical Web App on Heroku using Dash & Plotly in Python" }, { "code": null, "e": 1096, "s": 986, "text": "Chapter 4 (Optional): Parallelize Streaming Twitter Sentiment Analysis using Scala, Kafka and Spark Streaming" }, { "code": null, "e": 1380, "s": 1096, "text": "The analytical dashboard (with full code) above is what we’ll do today, which lays the foundation of the Real-time Twitter Monitoring Web App below in next chapter, as Dash (python framework for analytical web apps) is written on top of Plotly. Check my GitHub Repo for more details." }, { "code": null, "e": 1479, "s": 1380, "text": "Tech Stack of Chapter: RE, NLTK, TextBlob, Plotly, MySQL, Python (time, datetime, math, itertools)" }, { "code": null, "e": 1591, "s": 1479, "text": "RE: Regular expression operations to identify whether a pattern exists in a given sequence of characters or not" }, { "code": null, "e": 1704, "s": 1591, "text": "NLTK: Natural Language Toolkit, a leading platform for building Python programs to work with human language data" }, { "code": null, "e": 1830, "s": 1704, "text": "TextBlob: Natural Language Processing library for processing textual data, providing a simple API for diving into common NLP." }, { "code": null, "e": 1913, "s": 1830, "text": "Plotly: An interactive, open-source, and browser-based graphing library for Python" }, { "code": null, "e": 2033, "s": 1913, "text": "First, we need to extract the Twitter data from data source. You can directly read from sample_data.csv for simplicity." }, { "code": null, "e": 2069, "s": 2033, "text": "df = pd.read_csv(\"sample_data.csv\")" }, { "code": null, "e": 2211, "s": 2069, "text": "Or in a more formal way, extract data from our MySQL database, which has been set up and filled with real-time Twitter data in the Chapter 1." }, { "code": null, "e": 2535, "s": 2211, "text": "db_connection = mysql.connector.connect( host=\"localhost\", user=\"root\", passwd=\"password\", database=\"TwitterDB\", charset = 'utf8' )time_now = datetime.datetime.utcnow()time_10mins_before = datetime.timedelta(hours=0,minutes=10)) \\ .strftime('%Y-%m-%d %H:%M:%S'time_interval = time_now - time_10mins_before" }, { "code": null, "e": 2626, "s": 2535, "text": "And read data released in last 30 minutes and load it into Pandas DataFrame via SQL query." }, { "code": null, "e": 2844, "s": 2626, "text": "query = \"SELECT id_str, text, created_at, polarity, \\ user_location FROM {} WHERE created_at >= '{}'\" \\ .format(settings.TABLE_NAME, time_interval)df = pd.read_sql(query, con=db_connection)" }, { "code": null, "e": 2918, "s": 2844, "text": "Then convert DATETIME (MySQL data type) into Datetime (Pandas data type)." }, { "code": null, "e": 3000, "s": 2918, "text": "# UTC for date time at defaultdf['created_at'] = pd.to_datetime(df['created_at'])" }, { "code": null, "e": 3316, "s": 3000, "text": "The core of sentiment analysis is to use TextBlob in order to extract the polarity & subjectivity from tweet texts, which is actually done by the data preprocessing for better data storage in the previous chapter. Negative tweets represent as -1, positive tweets represent as +1, and neutral tweets represent as 0 ." }, { "code": null, "e": 3454, "s": 3316, "text": "from textblob import TextBlobsentiment = TextBlob(tweet_text).sentimentpolarity = sentiment.polaritysubjectivity = sentiment.subjectivity" }, { "code": null, "e": 3623, "s": 3454, "text": "Convert the entire time serises into groups of 2 seconds, and count the number of sentiment for each kind of polarities (e.g. -1, 0, and 1) in each time-interval group." }, { "code": null, "e": 3960, "s": 3623, "text": "Apply unstack-stack technology to make sure all categories in each group are displayed even if one of categories doesn't have any value. As we only display real-time tweets posted in last 30 minutes, groups of 2-second interval could best display on the screen in practice. After that, rename the columns to allow them self explanatory." }, { "code": null, "e": 4345, "s": 3960, "text": "# Clean and transform data to enable time seriesresult = df.groupby( \\ [pd.Grouper(key='created_at', freq='2s'), 'polarity'] \\ ).count().unstack(fill_value=0).stack().reset_index()result = result.rename(columns= \\ { \"id_str\": \"Num of '{}' mentions\".format(TRACK_WORD), \\ \"created_at\":\"Time in UTC\" })" }, { "code": null, "e": 4416, "s": 4345, "text": "Record the time series with 2-second interval for further index usage." }, { "code": null, "e": 4506, "s": 4416, "text": "time_series = result[\"Time in UTC\"][result['polarity']==0] \\ .reset_index(drop=True)" }, { "code": null, "e": 4705, "s": 4506, "text": "Use simple Plotly Express to quick visualize the line chart. Note: Plotly Express is a terse, consistent, high-level wrapper of plotly.graph_objects for rapid data exploration and figure generation." }, { "code": null, "e": 4886, "s": 4705, "text": "import plotly.express as pxfig = px.line(result, x='Time in UTC', \\ y=\"Num of '{}' mentions\".format(TRACK_WORD), \\ color='polarity')fig.show()" }, { "code": null, "e": 5104, "s": 4886, "text": "In order to tracking the hottest words or the most frequency tokens in the tweets, we join all tweet texts, remove the urls, clean the ‘RT’ and ‘&’ (a.k.a. ‘&amp;’ )symbols, and convert all characters into lowercases." }, { "code": null, "e": 5309, "s": 5104, "text": "content = ' '.join(df[\"text\"])content = re.sub(r\"http\\S+\", \"\", content)content = content.replace('RT ', ' ').replace('&amp;', 'and')content = re.sub('[^A-Za-z0-9]+', ' ', content)content = content.lower()" }, { "code": null, "e": 5493, "s": 5309, "text": "Use python script to download these 2 files from NLTK at the first time. Punkt Sentence Tokenizer is used to divide a text into a list of sentences by using an unsupervised algorithm." }, { "code": null, "e": 5553, "s": 5493, "text": "import nltknltk.download('punkt')nltk.download('stopwords')" }, { "code": null, "e": 5723, "s": 5553, "text": "Then tokenize the entire text from all tweets, use Stop Words to remove commonly used words, and extract 10 most common words in the Frequency Distribution of all words." }, { "code": null, "e": 6159, "s": 5723, "text": "from nltk.probability import FreqDistfrom nltk.tokenize import word_tokenizefrom nltk.corpus import stopwordstokenized_word = word_tokenize(content)stop_words=set(stopwords.words(\"english\"))filtered_sent=[]for w in tokenized_word: if w not in stop_words: filtered_sent.append(w)fdist = FreqDist(filtered_sent)fd = pd.DataFrame(fdist.most_common(10), \\ columns = [\"Word\",\"Frequency\"]).drop([0]).reindex()" }, { "code": null, "e": 6225, "s": 6159, "text": "Use simple Plotly Express again to quick visualize the bar chart." }, { "code": null, "e": 6465, "s": 6225, "text": "import plotly.express as pxfig = px.bar(fd, x=\"Word\", y=\"Frequency\")fig.update_traces(marker_color='rgb(240,128,128)', \\ marker_line_color='rgb(8,48,107)', \\ marker_line_width=1.5, opacity=0.8)fig.show()" }, { "code": null, "e": 6924, "s": 6465, "text": "To explore users’ geographic distributions, we need to identify their locations through their user profile rather than the locations attached with tweets, since less than 1% people will attach their tweet locations. However, according to locations in users’ profile, they may include one or more of counties, cities, states, countries, or planets. Thus, filtering these data into US state-level locations is the core of geographic segmentation recognization." }, { "code": null, "e": 7030, "s": 6924, "text": "Set up all state names and their abbreviations as constants for further abbreviation-name transformation." }, { "code": null, "e": 7336, "s": 7030, "text": "STATES = ['Alabama', 'AL', 'Alaska', 'AK', \\ ...... # Text hided for readability \\ 'WV', 'Wisconsin', 'WI', 'Wyoming', 'WY']STATE_DICT = dict(itertools.zip_longest(*[iter(STATES)] * 2, fillvalue=\"\"))INV_STATE_DICT = dict((v,k) for k,v in STATE_DICT.items())" }, { "code": null, "e": 7456, "s": 7336, "text": "Extract the state information from their locations by iterating the list of state names and the list of user locations." }, { "code": null, "e": 7843, "s": 7456, "text": "is_in_US=[]geo = df[['user_location']]df = df.fillna(\" \")for x in df['user_location']: check = False for s in STATES: if s in x: is_in_US.append(STATE_DICT[s] if s in STATE_DICT else s) check = True break if not check: is_in_US.append(None)geo_dist = pd.DataFrame(is_in_US, columns['State']) \\ .dropna().reset_index()" }, { "code": null, "e": 8027, "s": 7843, "text": "Count the number of tweets posted in each state of US, and use logarithmic number to avoid the extreme values (e.g. 500+ in California and 3 in North Dakota) for better visualization." }, { "code": null, "e": 8303, "s": 8027, "text": "geo_dist = geo_dist.groupby('State').count(). \\ rename(columns={\"index\": \"Number\"}).sort_values( \\ by=['Number'], ascending=False).reset_index()geo_dist[\"Log Num\"] = geo_dist[\"Number\"] \\ .apply(lambda x: math.log(x, 2))" }, { "code": null, "e": 8375, "s": 8303, "text": "Add explanatory text information for the hover text on later dashboard." }, { "code": null, "e": 8585, "s": 8375, "text": "geo_dist['Full State Name'] = geo_dist['State'] \\ .apply(lambda x: INV_STATE_DICT[x])geo_dist['text'] = geo_dist['Full State Name'] + '<br>' + \\ 'Num: ' + geo_dist['Number'].astype(str)" }, { "code": null, "e": 8657, "s": 8585, "text": "This time, we use Plotly (not Plotly Express) to visualize the USA map." }, { "code": null, "e": 8966, "s": 8657, "text": "Note: plotly.graph_objects is the core of Plotly Library containing more generic functions for more complex usage.locationmode is the set of locations match entries in “locations”. text is the hover text. marker_line_color is the color of line markers between states. Set geo_scope to limit map scope to USA." }, { "code": null, "e": 9389, "s": 8966, "text": "import plotly.graph_objects as gofig = go.Figure(data=go.Choropleth( locations=geo_dist['State'], # Spatial coordinates z = geo_dist['Log Num'].astype(float), # Data to be color-coded locationmode = 'USA-states', colorscale = \"Reds\", text=geo_dist['text'], marker_line_color='white', # line markers between states colorbar_title = \"Numbers in Log2\"))fig.update_layout( geo_scope='usa', )fig.show()" }, { "code": null, "e": 9624, "s": 9389, "text": "Now we could integrate all data visualization parts into one dashboard using Plotly.subplots. Displaying multiple figures simultaneously can greatly improve the reading efficiency and enhance the comparability among multiple insights." }, { "code": null, "e": 9764, "s": 9624, "text": "First, create a Plotly Figure containing 2×2 subplots with Line Chart in the left, Map in the top right, and Bar Chart in the bottom right." }, { "code": null, "e": 10050, "s": 9764, "text": "from plotly.subplots import make_subplotsfig = make_subplots( rows=2, cols=2, column_widths=[1, 0.4], row_heights=[0.6, 0.4], specs=[[{\"type\": \"scatter\", \"rowspan\": 2}, {\"type\": \"choropleth\"}], [None, {\"type\": \"bar\"}]] )" }, { "code": null, "e": 10238, "s": 10050, "text": "Add three Lines of negatives, neutrals, and positives in the first subplot using add_trace and go.Scatter . In addition, row and col represent the place of this subplot in the big figure." }, { "code": null, "e": 11035, "s": 10238, "text": "fig.add_trace(go.Scatter( x=time_series, y=result[\"Num of '{}' mentions\" \\ .format(settings.TRACK_WORDS[0])] \\ [result['polarity']==0].reset_index(drop=True), \\ name=\"Neural\", opacity=0.8), row=1, col=1) fig.add_trace(go.Scatter( x=time_series, y=result[\"Num of '{}' mentions\" \\ .format(settings.TRACK_WORDS[0])] \\ [result['polarity']==-1].reset_index(drop=True), name=\"Negative\", opacity=0.8), row=1, col=1)fig.add_trace(go.Scatter( x=time_series, y=result[\"Num of '{}' mentions\" \\ .format(settings.TRACK_WORDS[0])] \\ [result['polarity']==1].reset_index(drop=True), \\ name=\"Positive\", opacity=0.8), row=1, col=1)" }, { "code": null, "e": 11220, "s": 11035, "text": "Add the Bar Chart for the topic frequency distribution using add_trace and go.Bar . You may use rgb(xx,xx,xx) or rgba(xx,xx,xx,x) to change the color of certain elements in the figure." }, { "code": null, "e": 11493, "s": 11220, "text": "fig.add_trace(go.Bar(x=fd[\"Word\"], y=fd[\"Frequency\"], \\ name=\"Freq Dist\"), row=2, col=2)fig.update_traces(marker_color='rgb(59, 89, 152)', \\ marker_line_color='rgb(8,48,107)', \\ marker_line_width=0.5, opacity=0.7, row=2, col=2)" }, { "code": null, "e": 11575, "s": 11493, "text": "Then insert the Map in the top right, and set locations and numbers per location." }, { "code": null, "e": 11877, "s": 11575, "text": "fig.add_trace(go.Choropleth( locations=geo_dist['State'], # Spatial coordinates z = geo_dist['Log Num'].astype(float), # Data to be color-coded locationmode = 'USA-states', colorscale = \"Blues\", text=geo_dist['text'], # hover text showscale=False, geo = 'geo' ), row=1, col=2)" }, { "code": null, "e": 12051, "s": 11877, "text": "Add title in the layout of our figure, reduce the geo-scope of our map, turn the template theme into the dark, and add annotations for the layout using go.layout.Annotation." }, { "code": null, "e": 12667, "s": 12051, "text": "fig.update_layout( title_text = \\ \"Real-time tracking '{}' mentions on Twitter {} UTC\" \\ .format(settings.TRACK_WORDS[0] ,datetime.datetime.utcnow().strftime('%m-%d %H:%M') \\ ), geo = dict( scope='usa', ), template=\"plotly_dark\", margin=dict(r=20, t=50, b=50, l=20), annotations=[ go.layout.Annotation( text=\"Source: Twitter\", showarrow=False, xref=\"paper\", yref=\"paper\", x=0, y=0) ], showlegend=False, xaxis_rangeslider_visible=True)" }, { "code": null, "e": 12716, "s": 12667, "text": "Last, display all subplots in the single figure." }, { "code": null, "e": 12727, "s": 12716, "text": "fig.show()" }, { "code": null, "e": 12956, "s": 12727, "text": "Author’s Words: A little bit complex in this chapter as it uses NLP and sentiment analysis approaches to transfer data points into insights. Further improvement on topic tracking can be implemented by using advanced NLP methods." }, { "code": null, "e": 13115, "s": 12956, "text": "Next chapter will be the most exciting part to integrate and deploy all functions on the Heroku server using Dash. As always, I appreciate for any feedback! 😃" } ]
Improving Your Data Visualizations with Stacked Bar Charts in Python | by Byron Dolon | Towards Data Science
Just looking at numbers on a table may make it difficult to identify trends in a dataset. Visualizing data makes it a lot easier for people to quickly understand key ideas. An important part of data visualization is choosing the right chart types based on the type of data you are analyzing. Standard scatter charts, line charts, and bar charts are great for visualizing a wide variety of numerical and categorical data. You can improve on these basic charts by adding additional features that make it even easier for the end-user to understand the data. In this piece, let’s take a look at how to create and customize stacked bar charts with the Plotly Express library in Python for data visualization. We’ll also use the Pandas library for some data pre-processing steps, so make sure you have these two packages installed already. Then, import the following and get ready to follow along on your own Jupyter notebook! import pandas as pdimport plotly.express as pximport random Let’s get to it! First, let’s generate some sample data to use in our data analysis and visualizations. To do so, run the following code below. expense_data = { "Person": random.choices(["A", "B"], k=30), "Amount": random.sample(range(100, 200), 10) + random.sample(range(0, 99), 10) + random.sample(range(49, 499), 10), "Category": ["Groceries"] * 10 + ["Restaurant"] * 10 + ["Appliances"] * 10, "Date": pd.to_datetime(pd.date_range('2020-01-01','2020-10-01', freq='MS').tolist() * 3)}df = pd.DataFrame(data=expense_data) In this piece, we’ll be analyzing and visualizing some randomly generated personal expense data. The code should generate a Pandas DataFrame with 30 rows of expenses in three different categories over time. The goal of this data analysis is to examine the spending per category every month and potentially identify trends occurring over time. As such, let’s use some Pandas to group the total spending per month together per category. You can do so using the two lines of code below. df_grouped = df.groupby(by=[pd.Grouper(key="Date", freq="1M"), "Category"])["Amount"]df_grouped = df_grouped.sum().reset_index() Now that our data has been processed to fit our initial question, we can dive straight into visualizing the data. The Plotly library makes clean-looking visualizations that have a bit more style than the standard graphs that you can create with Pandas (or matplotlib). Plotly Express takes it a step further and makes creating visualizations ridiculously easy. We’ll create our initial graph with just one line of code below. fig = px.bar(df_grouped, x="Date", y="Amount", color="Category")fig.show() The first input to the bar method is the grouped DataFrame we just created. Then, we pass the column names from our DataFrame into the x and y parameters of the bar method. Finally, to implement the stacked bar chart, all we need to do is pass the column name that we want to stack into the color parameter. You can further customize the stacked bar chart by filling in the optional barmode parameter. You can see an example of this and the resulting chart below. fig2 = px.bar(df_grouped, x="Date", y="Amount", color="Category", barmode="group")fig2.show() Passing group as an argument to the barmode parameter gives us a graph like above, where the expense per category bars for each month are grouped side by side instead of being stacked vertically. There are four possible options that you can pass into barmode: stack, group, overlay, and relative. As an example of what you might do during your exploratory data analysis phase, you could run the following code to take a look at all the different options for the bar graphs. barmodes = ["stack", "group", "overlay", "relative"]for barmode in barmodes: fig_bar = px.bar(df_grouped, x="Date", y="Amount", color="Category", barmode=barmode) fig_bar.show() Each of the bar mode options will display slightly different graphs. The “relative” bar mode will only be relevant when you have negative values, as this mode will cause Plotly to display the relevant categories with negative values below the axis. You could potentially encapsulate the above code block into a function and then run it on your data as a part of your exploratory data analysis (EDA), where you could also figure out which of these graphs is most suited to the data you’re looking at. Then, once you’ve decided which bar mode works best for you, you could choose either just to only generate one graph or export the graphs to png from your notebook (which is a handy feature of Plotly Express). As we take a look at a few more features you can do with bar charts, lets continue analyzing our sample data and compare the expense data per person over time. To do so, we’ll group the data again using the same groupby method as before. df_people = df.groupby(by=[pd.Grouper(key="Date", freq="1M"), "Person"])["Amount"]df_people = df_people.sum().reset_index() The resulting DataFrame will give us the total spending per person per month in our data set. We can now plug this DataFrame into the Plotly bar method as before but with one small addition. fig_people = px.bar(df_people, x="Date", y="Amount", color="Person", barmode="stack", text="Amount")fig_people.show() We can now clearly see which person spent more on each month with this graph. Since we’re dealing with financial data, it might be useful to have the amounts per category shown directly on the bar (instead of having to guess the rough amounts from the axis). To do so, we set the text parameter in the bar method equal to the column we would like to show up as bar labels, which in this case was “Amount”. You could then potentially remove the y-axis from the graph, since it’s now redundant given the text labels directly on the columns. We can explore one final feature with bar graphs in Plotly Express by analyzing the spending per category per person. We’ll group our data by category and person into a new DataFrame first by running the code below. df_category = df.groupby(["Category", "Person"]).sum().reset_index() Now, using this grouped DataFrame, we can use the same Plotly express bar method with the features we’ve explored so far, but with a few more additions. fig_category = px.bar(df_category, x="Amount", y="Person", color="Category", text="Amount", orientation="h")fig_category = fig_category.update_traces(insidetextanchor="middle", texttemplate="$%{text}")fig_category = fig_category.update_xaxes(visible=False, showticklabels=False)fig_category.show() First, you’ll see that we’ve created a horizontal bar chart instead of the vertical format we’ve been using before. All we had to do to implement this change was pass “h” to the orientation parameter in the bar method. Then, we also wanted to have text labels again, but to make sure that the text labels showed up in the middle of the bar labels, we’ll use the update_traces method and pass “middle” to the insidetextanchor parameter. Also, we can set a custom format for the text labels by setting it in the texttemplate parameter in the update_traces method. We’ll simply add a dollar sign in front of our labels, so in this case we pass in "$%{text}", as in Plotly Express you can reference columns by using the percentage sign followed by the column name in brackets. Finally, since we’ve already added a dollar sign to make the bar values very clear, we can go ahead and remove the axes with the “Amount” column values using the update_xaxes method and setting the visible and showticklabels parameters to “False”. And that’s all! I hope you found this very quick introduction to stacked bar charts with Plotly in Python useful for your data analysis. Using Plotly Express makes it really easy for you to just plug in a Pandas DataFrame and get straight away to visualizing your data with just a few lines of code. Thank you again for reading! If you’re thinking about becoming a paying member on Medium, I would really appreciate it if you sign up using my referral link below! This would let directly receive a portion of your membership fees, so it would be a big help. byrondolon.medium.com More by me:- Check for a Substring in a Pandas DataFrame- Conditional Selection and Assignment With .loc in Pandas- 2 Easy Ways to Get Tables From a Website With Pandas- Top 4 Repositories on GitHub to Learn Pandas- Level Up Your Data Visualizations with Trend Lines in Python- Better Data Visualization with Dual Axis Graphs in Python
[ { "code": null, "e": 463, "s": 171, "text": "Just looking at numbers on a table may make it difficult to identify trends in a dataset. Visualizing data makes it a lot easier for people to quickly understand key ideas. An important part of data visualization is choosing the right chart types based on the type of data you are analyzing." }, { "code": null, "e": 726, "s": 463, "text": "Standard scatter charts, line charts, and bar charts are great for visualizing a wide variety of numerical and categorical data. You can improve on these basic charts by adding additional features that make it even easier for the end-user to understand the data." }, { "code": null, "e": 1092, "s": 726, "text": "In this piece, let’s take a look at how to create and customize stacked bar charts with the Plotly Express library in Python for data visualization. We’ll also use the Pandas library for some data pre-processing steps, so make sure you have these two packages installed already. Then, import the following and get ready to follow along on your own Jupyter notebook!" }, { "code": null, "e": 1152, "s": 1092, "text": "import pandas as pdimport plotly.express as pximport random" }, { "code": null, "e": 1169, "s": 1152, "text": "Let’s get to it!" }, { "code": null, "e": 1296, "s": 1169, "text": "First, let’s generate some sample data to use in our data analysis and visualizations. To do so, run the following code below." }, { "code": null, "e": 1687, "s": 1296, "text": "expense_data = { \"Person\": random.choices([\"A\", \"B\"], k=30), \"Amount\": random.sample(range(100, 200), 10) + random.sample(range(0, 99), 10) + random.sample(range(49, 499), 10), \"Category\": [\"Groceries\"] * 10 + [\"Restaurant\"] * 10 + [\"Appliances\"] * 10, \"Date\": pd.to_datetime(pd.date_range('2020-01-01','2020-10-01', freq='MS').tolist() * 3)}df = pd.DataFrame(data=expense_data)" }, { "code": null, "e": 1894, "s": 1687, "text": "In this piece, we’ll be analyzing and visualizing some randomly generated personal expense data. The code should generate a Pandas DataFrame with 30 rows of expenses in three different categories over time." }, { "code": null, "e": 2171, "s": 1894, "text": "The goal of this data analysis is to examine the spending per category every month and potentially identify trends occurring over time. As such, let’s use some Pandas to group the total spending per month together per category. You can do so using the two lines of code below." }, { "code": null, "e": 2300, "s": 2171, "text": "df_grouped = df.groupby(by=[pd.Grouper(key=\"Date\", freq=\"1M\"), \"Category\"])[\"Amount\"]df_grouped = df_grouped.sum().reset_index()" }, { "code": null, "e": 2726, "s": 2300, "text": "Now that our data has been processed to fit our initial question, we can dive straight into visualizing the data. The Plotly library makes clean-looking visualizations that have a bit more style than the standard graphs that you can create with Pandas (or matplotlib). Plotly Express takes it a step further and makes creating visualizations ridiculously easy. We’ll create our initial graph with just one line of code below." }, { "code": null, "e": 2801, "s": 2726, "text": "fig = px.bar(df_grouped, x=\"Date\", y=\"Amount\", color=\"Category\")fig.show()" }, { "code": null, "e": 3109, "s": 2801, "text": "The first input to the bar method is the grouped DataFrame we just created. Then, we pass the column names from our DataFrame into the x and y parameters of the bar method. Finally, to implement the stacked bar chart, all we need to do is pass the column name that we want to stack into the color parameter." }, { "code": null, "e": 3265, "s": 3109, "text": "You can further customize the stacked bar chart by filling in the optional barmode parameter. You can see an example of this and the resulting chart below." }, { "code": null, "e": 3359, "s": 3265, "text": "fig2 = px.bar(df_grouped, x=\"Date\", y=\"Amount\", color=\"Category\", barmode=\"group\")fig2.show()" }, { "code": null, "e": 3555, "s": 3359, "text": "Passing group as an argument to the barmode parameter gives us a graph like above, where the expense per category bars for each month are grouped side by side instead of being stacked vertically." }, { "code": null, "e": 3833, "s": 3555, "text": "There are four possible options that you can pass into barmode: stack, group, overlay, and relative. As an example of what you might do during your exploratory data analysis phase, you could run the following code to take a look at all the different options for the bar graphs." }, { "code": null, "e": 4017, "s": 3833, "text": "barmodes = [\"stack\", \"group\", \"overlay\", \"relative\"]for barmode in barmodes: fig_bar = px.bar(df_grouped, x=\"Date\", y=\"Amount\", color=\"Category\", barmode=barmode) fig_bar.show()" }, { "code": null, "e": 4266, "s": 4017, "text": "Each of the bar mode options will display slightly different graphs. The “relative” bar mode will only be relevant when you have negative values, as this mode will cause Plotly to display the relevant categories with negative values below the axis." }, { "code": null, "e": 4727, "s": 4266, "text": "You could potentially encapsulate the above code block into a function and then run it on your data as a part of your exploratory data analysis (EDA), where you could also figure out which of these graphs is most suited to the data you’re looking at. Then, once you’ve decided which bar mode works best for you, you could choose either just to only generate one graph or export the graphs to png from your notebook (which is a handy feature of Plotly Express)." }, { "code": null, "e": 4965, "s": 4727, "text": "As we take a look at a few more features you can do with bar charts, lets continue analyzing our sample data and compare the expense data per person over time. To do so, we’ll group the data again using the same groupby method as before." }, { "code": null, "e": 5089, "s": 4965, "text": "df_people = df.groupby(by=[pd.Grouper(key=\"Date\", freq=\"1M\"), \"Person\"])[\"Amount\"]df_people = df_people.sum().reset_index()" }, { "code": null, "e": 5280, "s": 5089, "text": "The resulting DataFrame will give us the total spending per person per month in our data set. We can now plug this DataFrame into the Plotly bar method as before but with one small addition." }, { "code": null, "e": 5398, "s": 5280, "text": "fig_people = px.bar(df_people, x=\"Date\", y=\"Amount\", color=\"Person\", barmode=\"stack\", text=\"Amount\")fig_people.show()" }, { "code": null, "e": 5657, "s": 5398, "text": "We can now clearly see which person spent more on each month with this graph. Since we’re dealing with financial data, it might be useful to have the amounts per category shown directly on the bar (instead of having to guess the rough amounts from the axis)." }, { "code": null, "e": 5937, "s": 5657, "text": "To do so, we set the text parameter in the bar method equal to the column we would like to show up as bar labels, which in this case was “Amount”. You could then potentially remove the y-axis from the graph, since it’s now redundant given the text labels directly on the columns." }, { "code": null, "e": 6153, "s": 5937, "text": "We can explore one final feature with bar graphs in Plotly Express by analyzing the spending per category per person. We’ll group our data by category and person into a new DataFrame first by running the code below." }, { "code": null, "e": 6222, "s": 6153, "text": "df_category = df.groupby([\"Category\", \"Person\"]).sum().reset_index()" }, { "code": null, "e": 6375, "s": 6222, "text": "Now, using this grouped DataFrame, we can use the same Plotly express bar method with the features we’ve explored so far, but with a few more additions." }, { "code": null, "e": 6673, "s": 6375, "text": "fig_category = px.bar(df_category, x=\"Amount\", y=\"Person\", color=\"Category\", text=\"Amount\", orientation=\"h\")fig_category = fig_category.update_traces(insidetextanchor=\"middle\", texttemplate=\"$%{text}\")fig_category = fig_category.update_xaxes(visible=False, showticklabels=False)fig_category.show()" }, { "code": null, "e": 7109, "s": 6673, "text": "First, you’ll see that we’ve created a horizontal bar chart instead of the vertical format we’ve been using before. All we had to do to implement this change was pass “h” to the orientation parameter in the bar method. Then, we also wanted to have text labels again, but to make sure that the text labels showed up in the middle of the bar labels, we’ll use the update_traces method and pass “middle” to the insidetextanchor parameter." }, { "code": null, "e": 7446, "s": 7109, "text": "Also, we can set a custom format for the text labels by setting it in the texttemplate parameter in the update_traces method. We’ll simply add a dollar sign in front of our labels, so in this case we pass in \"$%{text}\", as in Plotly Express you can reference columns by using the percentage sign followed by the column name in brackets." }, { "code": null, "e": 7694, "s": 7446, "text": "Finally, since we’ve already added a dollar sign to make the bar values very clear, we can go ahead and remove the axes with the “Amount” column values using the update_xaxes method and setting the visible and showticklabels parameters to “False”." }, { "code": null, "e": 7710, "s": 7694, "text": "And that’s all!" }, { "code": null, "e": 7994, "s": 7710, "text": "I hope you found this very quick introduction to stacked bar charts with Plotly in Python useful for your data analysis. Using Plotly Express makes it really easy for you to just plug in a Pandas DataFrame and get straight away to visualizing your data with just a few lines of code." }, { "code": null, "e": 8252, "s": 7994, "text": "Thank you again for reading! If you’re thinking about becoming a paying member on Medium, I would really appreciate it if you sign up using my referral link below! This would let directly receive a portion of your membership fees, so it would be a big help." }, { "code": null, "e": 8274, "s": 8252, "text": "byrondolon.medium.com" } ]
Block Scoping in JavaScript.
Block scope is an area between two { curly braces } which can be between loops, if condition or switch statement. The let and const introduced in ES2015 allow us to create block scoped variables that can be accessed only inside those block. Following is the code showing block scoping in JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result{ font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>Block scoping in JavaScript</h1> <div style="color: green;" class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to access variable inside and outside the block</h3> <script> let resEle = document.querySelector(".result"); document.querySelector(".Btn").addEventListener("click", () => { let b = 44;{ let a = 22; } resEle.innerHTML = 'Accessing variable inside its block b = ' + b + '<br>'; try{ a } catch(err){ resEle.innerHTML += 'Accessing variable outside its block a = ' + err; } }); </script> </body> </html> The above code will produce the following output − On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1303, "s": 1062, "text": "Block scope is an area between two { curly braces } which can be between loops, if condition or switch statement. The let and const introduced in ES2015 allow us to create block scoped variables that can be accessed only inside those block." }, { "code": null, "e": 1363, "s": 1303, "text": "Following is the code showing block scoping in JavaScript −" }, { "code": null, "e": 1374, "s": 1363, "text": " Live Demo" }, { "code": null, "e": 2351, "s": 1374, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result{\n font-size: 20px;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>Block scoping in JavaScript</h1>\n<div style=\"color: green;\" class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to access variable inside and outside the block</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n let b = 44;{\n let a = 22;\n }\n resEle.innerHTML = 'Accessing variable inside its block b = ' + b + '<br>';\n try{\n a\n }\n catch(err){\n resEle.innerHTML += 'Accessing variable outside its block a = ' + err;\n }\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2402, "s": 2351, "text": "The above code will produce the following output −" }, { "code": null, "e": 2440, "s": 2402, "text": "On clicking the ‘CLICK HERE’ button −" } ]
How to change the Content of a <textarea> using JavaScript ? - GeeksforGeeks
27 May, 2021 Given an HTML document containing a <textarea> element and the task is to change the content of a <textarea> element with the help of JavaScript. Method 1: This method uses id attribute of textarea with value property to change the content of <textarea> element. JavaScript code is written within the <script> tag. HTML <!DOCTYPE html><html> <head> <title> How to change the Content of a textarea using JavaScript? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> How to change the Content of a <textarea> with JavaScript? </h3> <textarea id="textArea"> A Computer Science Portal </textarea> <br><br> <button onclick="changeContent()"> Click to change </button> <script> // JavaScript code to change // the content of <textarea> function changeContent() { var x = document.getElementById('textArea'); x.value = "GeeksforGeeks"; } </script></body> </html> Output: Before clicking the button: After clicking the button: Method 2: This method uses the id attribute of the textarea with innerHTML property to change the content of <textarea> element. JavaScript code is written within the <script> tag. HTML <!DOCTYPE html><html> <head> <title> How to change the Content of a textarea using JavaScript? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> How to change the Content of a <textarea> with JavaScript? </h3> <textarea id="textArea"> A Computer Science Portal </textarea> <br><br> <button onclick="changeContent()"> Click to change </button> <script> // JavaScript code to change // the content of <textarea> function changeContent() { document.getElementById('textArea').innerHTML = "GeeksforGeeks"; } </script></body> </html> Output: Before clicking the button: After clicking the button: Method 3: This method uses id attribute of the textarea with innerText property to change the content of <textarea> element. JavaScript code is between the <script> tag. HTML <!DOCTYPE html><html> <head> <title> How to change the Content of a textarea using JavaScript? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> How to change the Content of a <textarea> with JavaScript? </h3> <textarea id="textArea"> A Computer Science Portal </textarea> <br><br> <button onclick="changeContent()"> Click to change </button> <script> // JavaScript code to change // the content of <textarea> function changeContent() { document.getElementById('textArea').innerText = "GeeksforGeeks"; } </script></body> </html> Output: Before clicking the button: After clicking the button: surinderdawra388 javascript-basics javascript-string Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to Use the JavaScript Fetch API to Get Data? Difference Between PUT and PATCH Request Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24394, "s": 24366, "text": "\n27 May, 2021" }, { "code": null, "e": 24540, "s": 24394, "text": "Given an HTML document containing a <textarea> element and the task is to change the content of a <textarea> element with the help of JavaScript." }, { "code": null, "e": 24709, "s": 24540, "text": "Method 1: This method uses id attribute of textarea with value property to change the content of <textarea> element. JavaScript code is written within the <script> tag." }, { "code": null, "e": 24714, "s": 24709, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to change the Content of a textarea using JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> How to change the Content of a <textarea> with JavaScript? </h3> <textarea id=\"textArea\"> A Computer Science Portal </textarea> <br><br> <button onclick=\"changeContent()\"> Click to change </button> <script> // JavaScript code to change // the content of <textarea> function changeContent() { var x = document.getElementById('textArea'); x.value = \"GeeksforGeeks\"; } </script></body> </html> ", "e": 25490, "s": 24714, "text": null }, { "code": null, "e": 25499, "s": 25490, "text": "Output: " }, { "code": null, "e": 25529, "s": 25499, "text": "Before clicking the button: " }, { "code": null, "e": 25558, "s": 25529, "text": "After clicking the button: " }, { "code": null, "e": 25739, "s": 25558, "text": "Method 2: This method uses the id attribute of the textarea with innerHTML property to change the content of <textarea> element. JavaScript code is written within the <script> tag." }, { "code": null, "e": 25744, "s": 25739, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to change the Content of a textarea using JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> How to change the Content of a <textarea> with JavaScript? </h3> <textarea id=\"textArea\"> A Computer Science Portal </textarea> <br><br> <button onclick=\"changeContent()\"> Click to change </button> <script> // JavaScript code to change // the content of <textarea> function changeContent() { document.getElementById('textArea').innerHTML = \"GeeksforGeeks\"; } </script></body> </html> ", "e": 26519, "s": 25744, "text": null }, { "code": null, "e": 26528, "s": 26519, "text": "Output: " }, { "code": null, "e": 26558, "s": 26528, "text": "Before clicking the button: " }, { "code": null, "e": 26587, "s": 26558, "text": "After clicking the button: " }, { "code": null, "e": 26757, "s": 26587, "text": "Method 3: This method uses id attribute of the textarea with innerText property to change the content of <textarea> element. JavaScript code is between the <script> tag." }, { "code": null, "e": 26762, "s": 26757, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to change the Content of a textarea using JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> How to change the Content of a <textarea> with JavaScript? </h3> <textarea id=\"textArea\"> A Computer Science Portal </textarea> <br><br> <button onclick=\"changeContent()\"> Click to change </button> <script> // JavaScript code to change // the content of <textarea> function changeContent() { document.getElementById('textArea').innerText = \"GeeksforGeeks\"; } </script></body> </html> ", "e": 27539, "s": 26762, "text": null }, { "code": null, "e": 27548, "s": 27539, "text": "Output: " }, { "code": null, "e": 27578, "s": 27548, "text": "Before clicking the button: " }, { "code": null, "e": 27607, "s": 27578, "text": "After clicking the button: " }, { "code": null, "e": 27626, "s": 27609, "text": "surinderdawra388" }, { "code": null, "e": 27644, "s": 27626, "text": "javascript-basics" }, { "code": null, "e": 27662, "s": 27644, "text": "javascript-string" }, { "code": null, "e": 27669, "s": 27662, "text": "Picked" }, { "code": null, "e": 27680, "s": 27669, "text": "JavaScript" }, { "code": null, "e": 27697, "s": 27680, "text": "Web Technologies" }, { "code": null, "e": 27724, "s": 27697, "text": "Web technologies Questions" }, { "code": null, "e": 27822, "s": 27724, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27831, "s": 27822, "text": "Comments" }, { "code": null, "e": 27844, "s": 27831, "text": "Old Comments" }, { "code": null, "e": 27905, "s": 27844, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27950, "s": 27905, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28022, "s": 27950, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28071, "s": 28022, "text": "How to Use the JavaScript Fetch API to Get Data?" }, { "code": null, "e": 28112, "s": 28071, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28168, "s": 28112, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28201, "s": 28168, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28263, "s": 28201, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28306, "s": 28263, "text": "How to fetch data from an API in ReactJS ?" } ]
Find Maximum value | Practice | GeeksforGeeks
Given an array A[ ] your task is to complete the function max_val which finds the maximum value of abs(i – j) * min(arr[i], arr[j]) where i and j vary from 0 to n-1. Example 1: Input: N = 4 arr[] = 3 2 1 4 Output: 9 Explanation: Here, a[0] = 3 and a[3] = 4 and thus result is abs(0-3)*min(3,4) = 9. Example 2: Input: N= 4 arr[] = 8 1 9 4 Output: 16 Explanation: Here, a[0]=8 and a[2]=9 thus result is abs(0-2)*min(8,9)=16. +1 ayerajkumar2 months ago class Solution { /*You are required to complete this method*/ int max_val(int arr[], int n) { int max=Integer.MIN_VALUE; int i=0,j=n-1; while(i<j){ max=Math.max(max, Math.abs(i-j)*Math.min(arr[i],arr[j])); if(arr[i]<arr[j]) i++; else j--; } return max; } } 0 guleriatarun672Premium3 months ago // { Driver Code Starts what is error?#include <bits/stdc++.h>using namespace std; // } Driver Code Ends/*The function returns an integerwhich denotes the max value of abs(i – j) * min(arr[i], arr[j]) in the array.*/ /*You are required to complete this method*/class Solution{ public: int max_val(int arr[], int n) { //Your code here int max = INT_MIN; long int indexm = 0; int max1 = INT_MIN; long int indexm1 = 0; for(int i = 0; i<n; i++) { if(arr[i]>max){ max = arr[i]; indexm = i; } } for(int i = 0; i<n; i++) { if(arr[i]>max1 && arr[i]<max) { max1 = arr[i]; indexm1 = i; } } long long int ans = abs((indexm1-indexm))*(max1); return ans; }}; // { Driver Code Starts. int main() {// your code goes hereint t;cin>>t;while(t--){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; Solution ob; cout<<ob.max_val(a,n)<<endl; }return 0;} // } Driver Code Ends 0 shubhanshujhas196 months ago Solution in Java class Solution { int max_val(int arr[], int n) { int i = 0, j = n - 1, max = Integer.MIN_VALUE; while(i < j) { if (max < Math.abs(i - j) * Math.min(arr[i], arr[j])) max = Math.abs(i - j) * Math.min(arr[i], arr[j]); if (arr[i] < arr[j]) i++; else j--; } return max; }} 0 ankitsinha1112007 months ago class Solution { public: int max_val(int arr[], int n) { int i=0,j=n-1,max1=INT_MIN; while(i<j) { if(max1<abs(i-j)*min(arr[i],arr[j])) max1=abs(i-j)*min(arr[i],arr[j]); if(arr[i]<arr[j]) i++; else j--; } return max1; } }; 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": 405, "s": 238, "text": "Given an array A[ ] your task is to complete the function max_val which finds the maximum value of abs(i – j) * min(arr[i], arr[j]) where i and j vary from 0 to n-1. " }, { "code": null, "e": 416, "s": 405, "text": "Example 1:" }, { "code": null, "e": 541, "s": 416, "text": "Input:\nN = 4\narr[] = 3 2 1 4\nOutput: 9\nExplanation:\nHere, a[0] = 3 and a[3] = 4 \nand thus result is \nabs(0-3)*min(3,4) = 9." }, { "code": null, "e": 552, "s": 541, "text": "Example 2:" }, { "code": null, "e": 667, "s": 552, "text": "Input:\nN= 4\narr[] = 8 1 9 4\nOutput: 16\nExplanation:\nHere, a[0]=8 and a[2]=9 thus \nresult is abs(0-2)*min(8,9)=16. " }, { "code": null, "e": 670, "s": 667, "text": "+1" }, { "code": null, "e": 694, "s": 670, "text": "ayerajkumar2 months ago" }, { "code": null, "e": 1061, "s": 694, "text": "class Solution\n{\n /*You are required to complete this method*/\n int max_val(int arr[], int n)\n {\n\t int max=Integer.MIN_VALUE;\n\t int i=0,j=n-1;\n\t while(i<j){\n\t max=Math.max(max, Math.abs(i-j)*Math.min(arr[i],arr[j]));\n if(arr[i]<arr[j])\n i++;\n else\n j--;\n\t }\n\t return max;\n }\n}" }, { "code": null, "e": 1063, "s": 1061, "text": "0" }, { "code": null, "e": 1098, "s": 1063, "text": "guleriatarun672Premium3 months ago" }, { "code": null, "e": 1122, "s": 1098, "text": "// { Driver Code Starts" }, { "code": null, "e": 1181, "s": 1122, "text": "what is error?#include <bits/stdc++.h>using namespace std;" }, { "code": null, "e": 1318, "s": 1181, "text": "// } Driver Code Ends/*The function returns an integerwhich denotes the max value of abs(i – j) * min(arr[i], arr[j]) in the array.*/" }, { "code": null, "e": 1992, "s": 1318, "text": "/*You are required to complete this method*/class Solution{ public: int max_val(int arr[], int n) { //Your code here int max = INT_MIN; long int indexm = 0; int max1 = INT_MIN; long int indexm1 = 0; for(int i = 0; i<n; i++) { if(arr[i]>max){ max = arr[i]; indexm = i; } } for(int i = 0; i<n; i++) { if(arr[i]>max1 && arr[i]<max) { max1 = arr[i]; indexm1 = i; } } long long int ans = abs((indexm1-indexm))*(max1); return ans; }};" }, { "code": null, "e": 2017, "s": 1992, "text": "// { Driver Code Starts." }, { "code": null, "e": 2211, "s": 2017, "text": "int main() {// your code goes hereint t;cin>>t;while(t--){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; Solution ob; cout<<ob.max_val(a,n)<<endl; }return 0;} // } Driver Code Ends" }, { "code": null, "e": 2213, "s": 2211, "text": "0" }, { "code": null, "e": 2242, "s": 2213, "text": "shubhanshujhas196 months ago" }, { "code": null, "e": 2259, "s": 2242, "text": "Solution in Java" }, { "code": null, "e": 2627, "s": 2259, "text": "class Solution { int max_val(int arr[], int n) { int i = 0, j = n - 1, max = Integer.MIN_VALUE; while(i < j) { if (max < Math.abs(i - j) * Math.min(arr[i], arr[j])) max = Math.abs(i - j) * Math.min(arr[i], arr[j]); if (arr[i] < arr[j]) i++; else j--; } return max; }}" }, { "code": null, "e": 2629, "s": 2627, "text": "0" }, { "code": null, "e": 2658, "s": 2629, "text": "ankitsinha1112007 months ago" }, { "code": null, "e": 3008, "s": 2658, "text": "class Solution\n{\n public:\n int max_val(int arr[], int n)\n {\n int i=0,j=n-1,max1=INT_MIN;\n while(i<j)\n {\n if(max1<abs(i-j)*min(arr[i],arr[j]))\n max1=abs(i-j)*min(arr[i],arr[j]);\n if(arr[i]<arr[j])\n i++;\n else\n j--;\n }\n return max1;\n }\n};" }, { "code": null, "e": 3154, "s": 3008, "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": 3190, "s": 3154, "text": " Login to access your submissions. " }, { "code": null, "e": 3200, "s": 3190, "text": "\nProblem\n" }, { "code": null, "e": 3210, "s": 3200, "text": "\nContest\n" }, { "code": null, "e": 3273, "s": 3210, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3421, "s": 3273, "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": 3629, "s": 3421, "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": 3735, "s": 3629, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to convert XML to JSON array in Java?
A JSON is a lightweight data-interchange format and the format of JSON is like a key-value pair. We can convert XML to JSON array using org.json.XML class, this provides a static method, XML.toJSONObject() to convert XML to JSON array. public static JSONObject toJSONObject(java.lang.String string) throws JSONException In the below example, converting XML to JSON array import org.json.*; public class ConvertXMLToJSONArrayTest { public static String xmlString= "<?xml version=\"1.0\" ?><root><test attrib=\"jsontext1\">tutorialspoint</test><test attrib=\"jsontext2\">tutorix</test></root>"; public static void main(String[] args) { try { JSONObject json = XML.toJSONObject(xmlString); // converts xml to json String jsonPrettyPrintString = json.toString(4); // json pretty print System.out.println(jsonPrettyPrintString); } catch(JSONException je) { System.out.println(je.toString()); } } } {"root": {"test": [ { "attrib": "jsontext1", "content": "tutorialspoint" }, { "attrib": "jsontext2", "content": "tutorix" } ]}}
[ { "code": null, "e": 1298, "s": 1062, "text": "A JSON is a lightweight data-interchange format and the format of JSON is like a key-value pair. We can convert XML to JSON array using org.json.XML class, this provides a static method, XML.toJSONObject() to convert XML to JSON array." }, { "code": null, "e": 1382, "s": 1298, "text": "public static JSONObject toJSONObject(java.lang.String string) throws JSONException" }, { "code": null, "e": 1433, "s": 1382, "text": "In the below example, converting XML to JSON array" }, { "code": null, "e": 2024, "s": 1433, "text": "import org.json.*;\npublic class ConvertXMLToJSONArrayTest {\n public static String xmlString= \"<?xml version=\\\"1.0\\\" ?><root><test attrib=\\\"jsontext1\\\">tutorialspoint</test><test attrib=\\\"jsontext2\\\">tutorix</test></root>\";\n public static void main(String[] args) {\n try {\n JSONObject json = XML.toJSONObject(xmlString); // converts xml to json\n String jsonPrettyPrintString = json.toString(4); // json pretty print\n System.out.println(jsonPrettyPrintString);\n } catch(JSONException je) {\n System.out.println(je.toString());\n }\n }\n}" }, { "code": null, "e": 2184, "s": 2024, "text": "{\"root\": {\"test\": [\n {\n \"attrib\": \"jsontext1\",\n \"content\": \"tutorialspoint\"\n },\n {\n \"attrib\": \"jsontext2\",\n \"content\": \"tutorix\"\n }\n]}}" } ]
Playit
div#myDIV { position:static; width:100px; height:100px; background:red; left:10px; top:100px;}
[]
How to divide an array into half in java?
Using the copyOfRange() method you can copy an array within a range. This method accepts three parameters, an array that you want to copy, start and end indexes of the range. You split an array using this method by copying the array ranging from 0 to length/2 to one array and length/2 to length to other. import java.util.Arrays; import java.util.Scanner; public class SplittingAnArray { public static void main(String args[]) { Scanner s =new Scanner(System.in); System.out.println("Enter the required size of the array ::"); int size = s.nextInt(); int [] myArray = new int[size]; System.out.println("Enter elements of the array"); for(int i=0; i< size; i++) { myArray[i] = s.nextInt(); } System.out.println(Arrays.toString(myArray)); int[] myArray1 = Arrays.copyOfRange(myArray, 0, myArray.length/2); int[] myArray2 = Arrays.copyOfRange(myArray, myArray.length/2, myArray.length); System.out.println("First half of the array:: "+Arrays.toString(myArray1)); System.out.println("First second of the array:: "+Arrays.toString(myArray2)); } } Enter the required size of the array :: 6 Enter elements of the array 45 63 78 96 42 19 [45, 63, 78, 96, 42, 19] First half of the array:: [45, 63, 78] First second of the array:: [96, 42, 19]
[ { "code": null, "e": 1237, "s": 1062, "text": "Using the copyOfRange() method you can copy an array within a range. This method accepts three parameters, an array that you want to copy, start and end indexes of the range." }, { "code": null, "e": 1368, "s": 1237, "text": "You split an array using this method by copying the array ranging from 0 to length/2 to one array and length/2 to length to other." }, { "code": null, "e": 2193, "s": 1368, "text": "import java.util.Arrays;\nimport java.util.Scanner;\n\npublic class SplittingAnArray {\n public static void main(String args[]) {\n Scanner s =new Scanner(System.in);\n System.out.println(\"Enter the required size of the array ::\");\n int size = s.nextInt();\n int [] myArray = new int[size];\n System.out.println(\"Enter elements of the array\");\n for(int i=0; i< size; i++) {\n myArray[i] = s.nextInt();\n }\n System.out.println(Arrays.toString(myArray));\n int[] myArray1 = Arrays.copyOfRange(myArray, 0, myArray.length/2);\n int[] myArray2 = Arrays.copyOfRange(myArray, myArray.length/2, myArray.length);\n System.out.println(\"First half of the array:: \"+Arrays.toString(myArray1));\n System.out.println(\"First second of the array:: \"+Arrays.toString(myArray2));\n }\n}" }, { "code": null, "e": 2386, "s": 2193, "text": "Enter the required size of the array ::\n6\nEnter elements of the array\n45\n63\n78\n96\n42\n19\n[45, 63, 78, 96, 42, 19]\nFirst half of the array:: [45, 63, 78]\nFirst second of the array:: [96, 42, 19]" } ]
Convert Hex String to byte Array in Java
To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str.length() / 2]; Now, take a for loop until the length of the byte array. for (int i = 0; i < val.length; i++) { int index = i * 2; int j = Integer.parseInt(str.substring(index, index + 2), 16); val[i] = (byte) j; } Let us see the complete example. Live Demo public class Demo { public static void main(String args[]) { String str = "p"; byte[] val = new byte[str.length() / 2]; for (int i = 0; i < val.length; i++) { int index = i * 2; int j = Integer.parseInt(str.substring(index, index + 2), 16); val[i] = (byte) j; } System.out.println(val); } } [B@2a139a55
[ { "code": null, "e": 1200, "s": 1062, "text": "To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array." }, { "code": null, "e": 1241, "s": 1200, "text": "byte[] val = new byte[str.length() / 2];" }, { "code": null, "e": 1298, "s": 1241, "text": "Now, take a for loop until the length of the byte array." }, { "code": null, "e": 1449, "s": 1298, "text": "for (int i = 0; i < val.length; i++) {\n int index = i * 2;\n int j = Integer.parseInt(str.substring(index, index + 2), 16);\n val[i] = (byte) j;\n}" }, { "code": null, "e": 1482, "s": 1449, "text": "Let us see the complete example." }, { "code": null, "e": 1493, "s": 1482, "text": " Live Demo" }, { "code": null, "e": 1847, "s": 1493, "text": "public class Demo {\n public static void main(String args[]) {\n String str = \"p\";\n byte[] val = new byte[str.length() / 2];\n for (int i = 0; i < val.length; i++) {\n int index = i * 2;\n int j = Integer.parseInt(str.substring(index, index + 2), 16);\n val[i] = (byte) j;\n }\n System.out.println(val);\n }\n}" }, { "code": null, "e": 1859, "s": 1847, "text": "[B@2a139a55" } ]
Python MySQL - Delete Data
To delete records from a MySQL table, you need to use the DELETE FROM statement. To remove specific records, you need to use WHERE clause along with it. Following is the syntax of the DELETE query in MYSQL − DELETE FROM table_name [WHERE Clause] Assume we have created a table in MySQL with name EMPLOYEES as − mysql> CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT ); Query OK, 0 rows affected (0.36 sec) And if we have inserted 4 records in to it using INSERT statements as − mysql> INSERT INTO EMPLOYEE VALUES ('Krishna', 'Sharma', 19, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000), ('Ramya', 'Ramapriya', 25, 'F', 5000), ('Mac', 'Mohan', 26, 'M', 2000); Following MySQL statement deletes the record of the employee with FIRST_NAME ”Mac”. mysql> DELETE FROM EMPLOYEE WHERE FIRST_NAME = 'Mac'; Query OK, 1 row affected (0.12 sec) If you retrieve the contents of the table, you can see only 3 records since we have deleted one. mysql> select * from EMPLOYEE; +------------+-----------+------+------+--------+ | FIRST_NAME | LAST_NAME | AGE | SEX | INCOME | +------------+-----------+------+------+--------+ | Krishna | Sharma | 20 | M | 2000 | | Raj | Kandukuri | 21 | M | 7000 | | Ramya | Ramapriya | 25 | F | 5000 | +------------+-----------+------+------+--------+ 3 rows in set (0.00 sec) If you execute the DELETE statement without the WHERE clause all the records from the specified table will be deleted. mysql> DELETE FROM EMPLOYEE; Query OK, 3 rows affected (0.09 sec) If you retrieve the contents of the table, you will get an empty set as shown below − mysql> select * from EMPLOYEE; Empty set (0.00 sec) DELETE operation is required when you want to delete some records from your database. To delete the records in a table − import mysql.connector package. import mysql.connector package. Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a cursor object by invoking the cursor() method on the connection object created above. Create a cursor object by invoking the cursor() method on the connection object created above. Then, execute the DELETE statement by passing it as a parameter to the execute() method. Then, execute the DELETE statement by passing it as a parameter to the execute() method. Following program deletes all the records from EMPLOYEE whose AGE is more than 20 − import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving single row print("Contents of the table: ") cursor.execute("SELECT * from EMPLOYEE") print(cursor.fetchall()) #Preparing the query to delete records sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (25) try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database conn.commit() except: # Roll back in case there is any error conn.rollback() #Retrieving data print("Contents of the table after delete operation ") cursor.execute("SELECT * from EMPLOYEE") print(cursor.fetchall()) #Closing the connection conn.close() Contents of the table: [('Krishna', 'Sharma', 22, 'M', 2000.0), ('Raj', 'Kandukuri', 23, 'M', 7000.0), ('Ramya', 'Ramapriya', 26, 'F', 5000.0), ('Mac', 'Mohan', 20, 'M', 2000.0), ('Ramya', 'Rama priya', 27, 'F', 9000.0)] Contents of the table after delete operation: [('Krishna', 'Sharma', 22, 'M', 2000.0), ('Raj', 'Kandukuri', 23, 'M', 7000.0), ('Mac', 'Mohan', 20, 'M', 2000.0)] 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3358, "s": 3205, "text": "To delete records from a MySQL table, you need to use the DELETE FROM statement. To remove specific records, you need to use WHERE clause along with it." }, { "code": null, "e": 3413, "s": 3358, "text": "Following is the syntax of the DELETE query in MYSQL −" }, { "code": null, "e": 3452, "s": 3413, "text": "DELETE FROM table_name [WHERE Clause]\n" }, { "code": null, "e": 3517, "s": 3452, "text": "Assume we have created a table in MySQL with name EMPLOYEES as −" }, { "code": null, "e": 3687, "s": 3517, "text": "mysql> CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n);\nQuery OK, 0 rows affected (0.36 sec)" }, { "code": null, "e": 3759, "s": 3687, "text": "And if we have inserted 4 records in to it using INSERT statements as −" }, { "code": null, "e": 3954, "s": 3759, "text": "mysql> INSERT INTO EMPLOYEE VALUES\n ('Krishna', 'Sharma', 19, 'M', 2000),\n ('Raj', 'Kandukuri', 20, 'M', 7000),\n ('Ramya', 'Ramapriya', 25, 'F', 5000),\n ('Mac', 'Mohan', 26, 'M', 2000);\n" }, { "code": null, "e": 4038, "s": 3954, "text": "Following MySQL statement deletes the record of the employee with FIRST_NAME ”Mac”." }, { "code": null, "e": 4128, "s": 4038, "text": "mysql> DELETE FROM EMPLOYEE WHERE FIRST_NAME = 'Mac';\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 4225, "s": 4128, "text": "If you retrieve the contents of the table, you can see only 3 records since we have deleted one." }, { "code": null, "e": 4632, "s": 4225, "text": "mysql> select * from EMPLOYEE;\n+------------+-----------+------+------+--------+\n| FIRST_NAME | LAST_NAME | AGE | SEX | INCOME |\n+------------+-----------+------+------+--------+\n| Krishna | Sharma | 20 | M | 2000 |\n| Raj | Kandukuri | 21 | M | 7000 |\n| Ramya | Ramapriya | 25 | F | 5000 |\n+------------+-----------+------+------+--------+\n3 rows in set (0.00 sec)\n" }, { "code": null, "e": 4751, "s": 4632, "text": "If you execute the DELETE statement without the WHERE clause all the records from the specified table will be deleted." }, { "code": null, "e": 4818, "s": 4751, "text": "mysql> DELETE FROM EMPLOYEE;\nQuery OK, 3 rows affected (0.09 sec)\n" }, { "code": null, "e": 4904, "s": 4818, "text": "If you retrieve the contents of the table, you will get an empty set as shown below −" }, { "code": null, "e": 4957, "s": 4904, "text": "mysql> select * from EMPLOYEE;\nEmpty set (0.00 sec)\n" }, { "code": null, "e": 5043, "s": 4957, "text": "DELETE operation is required when you want to delete some records from your database." }, { "code": null, "e": 5078, "s": 5043, "text": "To delete the records in a table −" }, { "code": null, "e": 5110, "s": 5078, "text": "import mysql.connector package." }, { "code": null, "e": 5142, "s": 5110, "text": "import mysql.connector package." }, { "code": null, "e": 5330, "s": 5142, "text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 5518, "s": 5330, "text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 5613, "s": 5518, "text": "Create a cursor object by invoking the cursor() method on the connection object created above." }, { "code": null, "e": 5708, "s": 5613, "text": "Create a cursor object by invoking the cursor() method on the connection object created above." }, { "code": null, "e": 5797, "s": 5708, "text": "Then, execute the DELETE statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 5886, "s": 5797, "text": "Then, execute the DELETE statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 5970, "s": 5886, "text": "Following program deletes all the records from EMPLOYEE whose AGE is more than 20 −" }, { "code": null, "e": 6785, "s": 5970, "text": "import mysql.connector\n\n#establishing the connection\nconn = mysql.connector.connect(\n user='root', password='password', host='127.0.0.1', database='mydb')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving single row\nprint(\"Contents of the table: \")\ncursor.execute(\"SELECT * from EMPLOYEE\")\nprint(cursor.fetchall())\n\n#Preparing the query to delete records\nsql = \"DELETE FROM EMPLOYEE WHERE AGE > '%d'\" % (25)\n\ntry:\n # Execute the SQL command\n cursor.execute(sql)\n \n # Commit your changes in the database\n conn.commit()\nexcept:\n # Roll back in case there is any error\n conn.rollback()\n\n#Retrieving data\nprint(\"Contents of the table after delete operation \")\ncursor.execute(\"SELECT * from EMPLOYEE\")\nprint(cursor.fetchall())\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 7193, "s": 6785, "text": "Contents of the table:\n[('Krishna', 'Sharma', 22, 'M', 2000.0), \n ('Raj', 'Kandukuri', 23, 'M', 7000.0), \n ('Ramya', 'Ramapriya', 26, 'F', 5000.0), \n ('Mac', 'Mohan', 20, 'M', 2000.0), \n ('Ramya', 'Rama priya', 27, 'F', 9000.0)]\n\nContents of the table after delete operation:\n[('Krishna', 'Sharma', 22, 'M', 2000.0), \n ('Raj', 'Kandukuri', 23, 'M', 7000.0), \n ('Mac', 'Mohan', 20, 'M', 2000.0)]\n" }, { "code": null, "e": 7230, "s": 7193, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 7246, "s": 7230, "text": " Malhar Lathkar" }, { "code": null, "e": 7279, "s": 7246, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 7298, "s": 7279, "text": " Arnab Chakraborty" }, { "code": null, "e": 7333, "s": 7298, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 7355, "s": 7333, "text": " In28Minutes Official" }, { "code": null, "e": 7389, "s": 7355, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 7417, "s": 7389, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7452, "s": 7417, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 7466, "s": 7452, "text": " Lets Kode It" }, { "code": null, "e": 7499, "s": 7466, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 7516, "s": 7499, "text": " Abhilash Nelson" }, { "code": null, "e": 7523, "s": 7516, "text": " Print" }, { "code": null, "e": 7534, "s": 7523, "text": " Add Notes" } ]
How to Use Airflow without Headaches | by Simon Hawe | Towards Data Science
Data pipelines and/or batch jobs that process and move data on a scheduled basis are well known to all us data folks. The de-facto standard tool to orchestrate all that is Apache Airflow. It is a platform to programmatically author, schedule, and monitor workflows. A workflow is a sequence of tasks represented as a Direct Acyclic Graph (DAG). As an example, think of an extract, transform, load (ETL) job as a workflow/DAG with the E, T, and L steps being its tasks. You configure a workflow in code using Python. This allows you to version your workflows in a source control system like Git, which is super handy. All in all, Airflow is an awesome tool and I love it. But, I initially used it the wrong way, and probably others also do. This misusage leads to headaches, especially when it comes to workflow deployments. Why? In short, we use it for both orchestrating workflows and running tasks on the same Airflow instance. In this article, I gonna tell you why this is an issue. For sure, I will also show you how you can easily fix that. I hope this leads to reducing your Aspirin consumption in the future as it did for me:) I start this article with a short story about myself and Airflow. When you create a workflow, you need to implement and combine various tasks. In Airflow, you implement a task using Operators. Airflow offers a set of operators out of the box, like a BashOperator and PythonOperator just to mention a few. Obviously, I heavily used the PythonOperator for my tasks as I am a Data Scientist and Python lover. This started very well, but after a while, I thought “Hm how am I gonna deploy my workflow to our production instance? How are my packages and other dependencies installed there?” One way is adding a requirements.txt file for each workflow, which gets installed on all Airflow workers on deployment. We tried that but my tasks required a different Pandas version than a colleague’s task. Due to this package dependency issue, the workflows cannot run on the same Python instance. And not only that, I used the Dataclasses package which requires Python 3.7 but on the production instance, we only had Python 3.6 installed. That’s not good. So I went on and googled a little bit to find another solution suggested by Airflow which is named Packaged-DAGs. This says: “Package all your DAGs and external dependencies into a zip file and deploy that.” You can follow this link for more details. To me, this does not sound like a great solution. It also doesn’t solve the Python version issue. Another possibility, offered as an Operator, is wrapping your task inside a PythonVirtualEnvOperator. I have to say, I haven’t tried that out, as it still doesn’t solve the Python version issue. But, I guess it might be rather slow if you have to create a virtual environment every time you execute a task. Apart from that, it has a couple of other caveats mentioned in the documentation. Damm, three tries and still no satisfying solution for deploying tasks written in Python. Last, I asked myself how can I write a task using other languages than Python? Can that step become language agnostic? Can even someone implement a task who doesn’t know the specifics of Airflow? And how do I deploy and integrate such a task into Airflow? Do I have to compile it and install the result with all dependencies on each worker to finally invoke it through the BashOperator? That sounds like a painful deployment and development experience. Furthermore, this might again lead to clashing dependencies. Altogether, this does not sound very satisfying. But I want to use Airflow! So, can we fix it? Whenever I hear things like “dependency clashes”, “version issues”, or “I want to be language agnostic” I immediately think about containers and Docker. Luckily, Airflow offers a DockerOperator (and also one for Kubernetes) out of the box. This allows us to invoke isolated docker containers as tasks from Airflow. That was quick :) But now, a bit more in detail. In the following, I show you how the process from developing Docker-based tasks and DAGs to deploying them looks like end-to-end. For each step, I highlight the respective issues solved. Develop and test your task in any language and version of the language you want. This allows you to test and develop tasks in isolation from Airflow specifics and other tasks. It reduces the entry barrier for new developers as they can choose the language they are most comfortable with.Package the artifacts together with all dependencies into a Docker image. This solves issues with dependencies and version clashes. It heavily contributes to reducing your headaches.Expose an Entrypoint from your container to invoke and parameterize a task using the DockerOperator. This enables you to use your images from Airflow.Build your image, tag it, and push it to a central Docker registry. Ideally, that is automated and part of your CI/CD pipeline. From the registry, Airflow pulls the images to the machines executing the tasks. This facilitates deploying tasks. Again a headache reduction step. Furthermore, it allows you to have multiple versions of the same task. Last, having a central registry enables you to share and reuse tasks across your organization. Develop and test your task in any language and version of the language you want. This allows you to test and develop tasks in isolation from Airflow specifics and other tasks. It reduces the entry barrier for new developers as they can choose the language they are most comfortable with. Package the artifacts together with all dependencies into a Docker image. This solves issues with dependencies and version clashes. It heavily contributes to reducing your headaches. Expose an Entrypoint from your container to invoke and parameterize a task using the DockerOperator. This enables you to use your images from Airflow. Build your image, tag it, and push it to a central Docker registry. Ideally, that is automated and part of your CI/CD pipeline. From the registry, Airflow pulls the images to the machines executing the tasks. This facilitates deploying tasks. Again a headache reduction step. Furthermore, it allows you to have multiple versions of the same task. Last, having a central registry enables you to share and reuse tasks across your organization. Build your DAG using the DockerOperator as the only operator. Use it to invoke various tasks available from your Docker registry. For me, this made my DAG definitions small, clean, and readable. I also did not have to learn any specific Airflow operators other than the DockerOperator.Put your DAG into a version control system. With this, deploying your DAG is just a git push and pull away. Again, this should be automated and be part of your CI/CD pipeline. Build your DAG using the DockerOperator as the only operator. Use it to invoke various tasks available from your Docker registry. For me, this made my DAG definitions small, clean, and readable. I also did not have to learn any specific Airflow operators other than the DockerOperator. Put your DAG into a version control system. With this, deploying your DAG is just a git push and pull away. Again, this should be automated and be part of your CI/CD pipeline. I hope that sound reasonable and you get the many advantages it offers. All you have to do is learn Docker if you don’t know it yet and you are ready to go. Now, we know what to do. In the next paragraph, let’s go through an example to see how to do it. Let’s quickly step through an example DAG where I only use the DockerOperator. With this DAG, I simulate an ETL job. Note that the DAG definition file does not reveal that it is just a simulated ETL job. It could be a super complex one or just a dummy one. The actual complexity is taken away from the DAG definition and moved to the respective task implementations. The resulting DAG definition file is concise and readable. You can find all the code in my Github repository. You not only find the DAG definition there but also how to build and run a corresponding Airflow instance using Docker. You also find the simulated ETL task implementation together with the Dockerfile. But now, let’s get concrete. First, let’s import the necessary modules and define the default arguments for our DAG. from datetime import datetime, timedeltafrom airflow import DAGfrom airflow.operators.docker_operator import DockerOperatord_args = { "start_date": datetime(2019, 11, 14), "owner": "shawe", "depends_on_past": False, "retries": 1, "retry_delay": timedelta(minutes=5),} Nothing fancy here, but you see that I have only imported DAG, which is always required, and the DockerOperator. We need nothing else at this stage from Airflow. Before we build the DAG, some more words about the DockerOperator and what you gonna see. All my tasks use the same Docker image named etl-dummy tagged with latest. The image offers a CLI named etl. This CLI has 3 sub-CLIs namely extract, transform, and load. The sub CLIs have different arguments. To run for example the transform task, you need to call etl --out-dir /some/path transform --upper To invoke a Docker image from the DockerOperator, you just have to specify the image name as name:tag, and the command you want to invoke. Note that my image is stored in my local Docker registry. With this, my etl dag definition looks like si = "@hourly"with DAG("etl", default_args=d_args, schedule_interval=si) as dag: def etl_operator(task_id: str, sub_cli_cmd: str): out_dir = "/usr/local/share" cmd = f"'etl --out-dir {out_dir} {sub_cli_cmd}'" return DockerOperator( command=cmd, task_id=task_id, image=f"etl-dummy:latest", volumes=[f"/usr/local/share:{out_dir}"], ) extract = etl_operator("e-step", "extract --url http://etl.de") transform = etl_operator("t-step", "transform --lower") load = etl_operator("l-step", "load --db 9000://fake-db") # Combine the tasks to a DAG extract >> transform >> load I just added a small helper function to create the DockerOperators. To me, this looks nice and clean. If you host your images in a remotely accessible Docker registry, you have to pass the image name as registry-name/image-name:image-tag. Furthermore, you have to provide a docker_conn_id to enable Airflow to access the registry. This docker_conn_id references a secret managed by Airflow. Another feature you can add is storing the image name and tag as variables in Airflow. If you want to update your DAG, all you have to do is push another image to your registry with a new tag, and change the value of the variable in Airflow. Finally, I want to repeat that you can find all the code including Airflow on Docker and the example Docker image in my Github repository. I hope this article was useful for you, and if you had headaches in the past, I hope they will go away in the future. Thank you for following this post. As always, feel free to contact me for questions, comments, or suggestions.
[ { "code": null, "e": 789, "s": 172, "text": "Data pipelines and/or batch jobs that process and move data on a scheduled basis are well known to all us data folks. The de-facto standard tool to orchestrate all that is Apache Airflow. It is a platform to programmatically author, schedule, and monitor workflows. A workflow is a sequence of tasks represented as a Direct Acyclic Graph (DAG). As an example, think of an extract, transform, load (ETL) job as a workflow/DAG with the E, T, and L steps being its tasks. You configure a workflow in code using Python. This allows you to version your workflows in a source control system like Git, which is super handy." }, { "code": null, "e": 1306, "s": 789, "text": "All in all, Airflow is an awesome tool and I love it. But, I initially used it the wrong way, and probably others also do. This misusage leads to headaches, especially when it comes to workflow deployments. Why? In short, we use it for both orchestrating workflows and running tasks on the same Airflow instance. In this article, I gonna tell you why this is an issue. For sure, I will also show you how you can easily fix that. I hope this leads to reducing your Aspirin consumption in the future as it did for me:)" }, { "code": null, "e": 1372, "s": 1306, "text": "I start this article with a short story about myself and Airflow." }, { "code": null, "e": 1765, "s": 1372, "text": "When you create a workflow, you need to implement and combine various tasks. In Airflow, you implement a task using Operators. Airflow offers a set of operators out of the box, like a BashOperator and PythonOperator just to mention a few. Obviously, I heavily used the PythonOperator for my tasks as I am a Data Scientist and Python lover. This started very well, but after a while, I thought" }, { "code": null, "e": 1892, "s": 1765, "text": "“Hm how am I gonna deploy my workflow to our production instance? How are my packages and other dependencies installed there?”" }, { "code": null, "e": 2351, "s": 1892, "text": "One way is adding a requirements.txt file for each workflow, which gets installed on all Airflow workers on deployment. We tried that but my tasks required a different Pandas version than a colleague’s task. Due to this package dependency issue, the workflows cannot run on the same Python instance. And not only that, I used the Dataclasses package which requires Python 3.7 but on the production instance, we only had Python 3.6 installed. That’s not good." }, { "code": null, "e": 2700, "s": 2351, "text": "So I went on and googled a little bit to find another solution suggested by Airflow which is named Packaged-DAGs. This says: “Package all your DAGs and external dependencies into a zip file and deploy that.” You can follow this link for more details. To me, this does not sound like a great solution. It also doesn’t solve the Python version issue." }, { "code": null, "e": 3089, "s": 2700, "text": "Another possibility, offered as an Operator, is wrapping your task inside a PythonVirtualEnvOperator. I have to say, I haven’t tried that out, as it still doesn’t solve the Python version issue. But, I guess it might be rather slow if you have to create a virtual environment every time you execute a task. Apart from that, it has a couple of other caveats mentioned in the documentation." }, { "code": null, "e": 3179, "s": 3089, "text": "Damm, three tries and still no satisfying solution for deploying tasks written in Python." }, { "code": null, "e": 3742, "s": 3179, "text": "Last, I asked myself how can I write a task using other languages than Python? Can that step become language agnostic? Can even someone implement a task who doesn’t know the specifics of Airflow? And how do I deploy and integrate such a task into Airflow? Do I have to compile it and install the result with all dependencies on each worker to finally invoke it through the BashOperator? That sounds like a painful deployment and development experience. Furthermore, this might again lead to clashing dependencies. Altogether, this does not sound very satisfying." }, { "code": null, "e": 3769, "s": 3742, "text": "But I want to use Airflow!" }, { "code": null, "e": 3788, "s": 3769, "text": "So, can we fix it?" }, { "code": null, "e": 4103, "s": 3788, "text": "Whenever I hear things like “dependency clashes”, “version issues”, or “I want to be language agnostic” I immediately think about containers and Docker. Luckily, Airflow offers a DockerOperator (and also one for Kubernetes) out of the box. This allows us to invoke isolated docker containers as tasks from Airflow." }, { "code": null, "e": 4121, "s": 4103, "text": "That was quick :)" }, { "code": null, "e": 4339, "s": 4121, "text": "But now, a bit more in detail. In the following, I show you how the process from developing Docker-based tasks and DAGs to deploying them looks like end-to-end. For each step, I highlight the respective issues solved." }, { "code": null, "e": 5400, "s": 4339, "text": "Develop and test your task in any language and version of the language you want. This allows you to test and develop tasks in isolation from Airflow specifics and other tasks. It reduces the entry barrier for new developers as they can choose the language they are most comfortable with.Package the artifacts together with all dependencies into a Docker image. This solves issues with dependencies and version clashes. It heavily contributes to reducing your headaches.Expose an Entrypoint from your container to invoke and parameterize a task using the DockerOperator. This enables you to use your images from Airflow.Build your image, tag it, and push it to a central Docker registry. Ideally, that is automated and part of your CI/CD pipeline. From the registry, Airflow pulls the images to the machines executing the tasks. This facilitates deploying tasks. Again a headache reduction step. Furthermore, it allows you to have multiple versions of the same task. Last, having a central registry enables you to share and reuse tasks across your organization." }, { "code": null, "e": 5688, "s": 5400, "text": "Develop and test your task in any language and version of the language you want. This allows you to test and develop tasks in isolation from Airflow specifics and other tasks. It reduces the entry barrier for new developers as they can choose the language they are most comfortable with." }, { "code": null, "e": 5871, "s": 5688, "text": "Package the artifacts together with all dependencies into a Docker image. This solves issues with dependencies and version clashes. It heavily contributes to reducing your headaches." }, { "code": null, "e": 6022, "s": 5871, "text": "Expose an Entrypoint from your container to invoke and parameterize a task using the DockerOperator. This enables you to use your images from Airflow." }, { "code": null, "e": 6464, "s": 6022, "text": "Build your image, tag it, and push it to a central Docker registry. Ideally, that is automated and part of your CI/CD pipeline. From the registry, Airflow pulls the images to the machines executing the tasks. This facilitates deploying tasks. Again a headache reduction step. Furthermore, it allows you to have multiple versions of the same task. Last, having a central registry enables you to share and reuse tasks across your organization." }, { "code": null, "e": 6925, "s": 6464, "text": "Build your DAG using the DockerOperator as the only operator. Use it to invoke various tasks available from your Docker registry. For me, this made my DAG definitions small, clean, and readable. I also did not have to learn any specific Airflow operators other than the DockerOperator.Put your DAG into a version control system. With this, deploying your DAG is just a git push and pull away. Again, this should be automated and be part of your CI/CD pipeline." }, { "code": null, "e": 7211, "s": 6925, "text": "Build your DAG using the DockerOperator as the only operator. Use it to invoke various tasks available from your Docker registry. For me, this made my DAG definitions small, clean, and readable. I also did not have to learn any specific Airflow operators other than the DockerOperator." }, { "code": null, "e": 7387, "s": 7211, "text": "Put your DAG into a version control system. With this, deploying your DAG is just a git push and pull away. Again, this should be automated and be part of your CI/CD pipeline." }, { "code": null, "e": 7544, "s": 7387, "text": "I hope that sound reasonable and you get the many advantages it offers. All you have to do is learn Docker if you don’t know it yet and you are ready to go." }, { "code": null, "e": 7641, "s": 7544, "text": "Now, we know what to do. In the next paragraph, let’s go through an example to see how to do it." }, { "code": null, "e": 8349, "s": 7641, "text": "Let’s quickly step through an example DAG where I only use the DockerOperator. With this DAG, I simulate an ETL job. Note that the DAG definition file does not reveal that it is just a simulated ETL job. It could be a super complex one or just a dummy one. The actual complexity is taken away from the DAG definition and moved to the respective task implementations. The resulting DAG definition file is concise and readable. You can find all the code in my Github repository. You not only find the DAG definition there but also how to build and run a corresponding Airflow instance using Docker. You also find the simulated ETL task implementation together with the Dockerfile. But now, let’s get concrete." }, { "code": null, "e": 8437, "s": 8349, "text": "First, let’s import the necessary modules and define the default arguments for our DAG." }, { "code": null, "e": 8720, "s": 8437, "text": "from datetime import datetime, timedeltafrom airflow import DAGfrom airflow.operators.docker_operator import DockerOperatord_args = { \"start_date\": datetime(2019, 11, 14), \"owner\": \"shawe\", \"depends_on_past\": False, \"retries\": 1, \"retry_delay\": timedelta(minutes=5),}" }, { "code": null, "e": 8882, "s": 8720, "text": "Nothing fancy here, but you see that I have only imported DAG, which is always required, and the DockerOperator. We need nothing else at this stage from Airflow." }, { "code": null, "e": 9237, "s": 8882, "text": "Before we build the DAG, some more words about the DockerOperator and what you gonna see. All my tasks use the same Docker image named etl-dummy tagged with latest. The image offers a CLI named etl. This CLI has 3 sub-CLIs namely extract, transform, and load. The sub CLIs have different arguments. To run for example the transform task, you need to call" }, { "code": null, "e": 9280, "s": 9237, "text": "etl --out-dir /some/path transform --upper" }, { "code": null, "e": 9521, "s": 9280, "text": "To invoke a Docker image from the DockerOperator, you just have to specify the image name as name:tag, and the command you want to invoke. Note that my image is stored in my local Docker registry. With this, my etl dag definition looks like" }, { "code": null, "e": 10179, "s": 9521, "text": "si = \"@hourly\"with DAG(\"etl\", default_args=d_args, schedule_interval=si) as dag: def etl_operator(task_id: str, sub_cli_cmd: str): out_dir = \"/usr/local/share\" cmd = f\"'etl --out-dir {out_dir} {sub_cli_cmd}'\" return DockerOperator( command=cmd, task_id=task_id, image=f\"etl-dummy:latest\", volumes=[f\"/usr/local/share:{out_dir}\"], ) extract = etl_operator(\"e-step\", \"extract --url http://etl.de\") transform = etl_operator(\"t-step\", \"transform --lower\") load = etl_operator(\"l-step\", \"load --db 9000://fake-db\") # Combine the tasks to a DAG extract >> transform >> load" }, { "code": null, "e": 10281, "s": 10179, "text": "I just added a small helper function to create the DockerOperators. To me, this looks nice and clean." }, { "code": null, "e": 10570, "s": 10281, "text": "If you host your images in a remotely accessible Docker registry, you have to pass the image name as registry-name/image-name:image-tag. Furthermore, you have to provide a docker_conn_id to enable Airflow to access the registry. This docker_conn_id references a secret managed by Airflow." }, { "code": null, "e": 10812, "s": 10570, "text": "Another feature you can add is storing the image name and tag as variables in Airflow. If you want to update your DAG, all you have to do is push another image to your registry with a new tag, and change the value of the variable in Airflow." }, { "code": null, "e": 10951, "s": 10812, "text": "Finally, I want to repeat that you can find all the code including Airflow on Docker and the example Docker image in my Github repository." } ]
How to select specific columns in MongoDB query?
To select specific columns, you can ignore the rest of them i.e. to hide those columns, set them to 0. Let us first create a collection with documents − > db.demo415.insertOne({"ClientName":"Robert","ClientCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5e72329db912067e57771adc") } > db.demo415.insertOne({"ClientName":"David","ClientCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5e7232acb912067e57771add") } > db.demo415.insertOne({"ClientName":"Bob","ClientCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5e7232b4b912067e57771ade") } Display all documents from a collection with the help of find() method − > db.demo415.find(); This will produce the following output − { "_id" : ObjectId("5e72329db912067e57771adc"), "ClientName" : "Robert", "ClientCountryName" : "US" } { "_id" : ObjectId("5e7232acb912067e57771add"), "ClientName" : "David", "ClientCountryName" : "UK" } { "_id" : ObjectId("5e7232b4b912067e57771ade"), "ClientName" : "Bob", "ClientCountryName" : "AUS" } Following is the query to select specific columns. Here, we have ignored rest of the columns to display the column “ClientCountryName” − > db.demo415.find({},{_id:0,ClientName:0}); This will produce the following output − { "ClientCountryName" : "US" } { "ClientCountryName" : "UK" } { "ClientCountryName" : "AUS" }
[ { "code": null, "e": 1215, "s": 1062, "text": "To select specific columns, you can ignore the rest of them i.e. to hide those columns, set them to 0. Let us first create a collection with documents −" }, { "code": null, "e": 1689, "s": 1215, "text": "> db.demo415.insertOne({\"ClientName\":\"Robert\",\"ClientCountryName\":\"US\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e72329db912067e57771adc\")\n}\n> db.demo415.insertOne({\"ClientName\":\"David\",\"ClientCountryName\":\"UK\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e7232acb912067e57771add\")\n}\n> db.demo415.insertOne({\"ClientName\":\"Bob\",\"ClientCountryName\":\"AUS\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e7232b4b912067e57771ade\")\n}" }, { "code": null, "e": 1762, "s": 1689, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1783, "s": 1762, "text": "> db.demo415.find();" }, { "code": null, "e": 1824, "s": 1783, "text": "This will produce the following output −" }, { "code": null, "e": 2127, "s": 1824, "text": "{ \"_id\" : ObjectId(\"5e72329db912067e57771adc\"), \"ClientName\" : \"Robert\", \"ClientCountryName\" : \"US\" }\n{ \"_id\" : ObjectId(\"5e7232acb912067e57771add\"), \"ClientName\" : \"David\", \"ClientCountryName\" : \"UK\" }\n{ \"_id\" : ObjectId(\"5e7232b4b912067e57771ade\"), \"ClientName\" : \"Bob\", \"ClientCountryName\" : \"AUS\" }" }, { "code": null, "e": 2264, "s": 2127, "text": "Following is the query to select specific columns. Here, we have ignored rest of the columns to display the column “ClientCountryName” −" }, { "code": null, "e": 2308, "s": 2264, "text": "> db.demo415.find({},{_id:0,ClientName:0});" }, { "code": null, "e": 2349, "s": 2308, "text": "This will produce the following output −" }, { "code": null, "e": 2443, "s": 2349, "text": "{ \"ClientCountryName\" : \"US\" }\n{ \"ClientCountryName\" : \"UK\" }\n{ \"ClientCountryName\" : \"AUS\" }" } ]
How to find the percentage of missing values in an R data frame?
To find the percentage of missing values in an R data frame, we can use sum function with the prod function. For example, if we have a data frame called df that contains some missing values then the percentage of missing values can be calculated by using the command: (sum(is.na(df))/prod(dim(df)))*100 Live Demo Consider the below data frame − x1<−sample(c(NA,1,5,10,15),20,replace=TRUE) x2<−sample(c(NA,rnorm(5)),20,replace=TRUE) x3<−sample(c(NA,100,200),20,replace=TRUE) x4<−sample(c(NA,0,1),20,replace=TRUE) df1<−data.frame(x1,x2,x3,x4) df1 x1 x2 x3 x4 1 10 −0.7734719 NA 1 2 10 −1.8581538 200 0 3 10 −0.7734719 100 1 4 1 NA 200 1 5 5 −1.8581538 100 NA 6 10 −0.7734719 100 0 7 5 −1.8581538 200 0 8 10 −0.3188769 NA NA 9 5 −0.7734719 NA 1 10 NA 1.0589124 200 0 11 NA −0.7734719 200 0 12 15 −1.8581538 NA 1 13 5 −0.7734719 200 NA 14 5 −0.7734719 200 0 15 10 −0.3188769 200 1 16 15 −1.8581538 NA 1 17 NA −1.8581538 200 0 18 15 1.0589124 NA 1 19 10 −0.7734719 NA 1 20 5 −1.8581538 100 NA Finding the percentage of missing values in df1 − (sum(is.na(df1))/prod(dim(df1)))*100 [1] 18.75 Live Demo y1<−sample(c(NA,rpois(2,1)),20,replace=TRUE) y2<−sample(c(NA,rpois(2,1)),20,replace=TRUE) y3<−sample(c(NA,rpois(2,5)),20,replace=TRUE) y4<−sample(c(NA,rpois(2,3)),20,replace=TRUE) y5<−sample(c(NA,rpois(2,2)),20,replace=TRUE) y6<−sample(c(NA,rpois(2,5)),20,replace=TRUE) df2<−data.frame(y1,y2,y3,y4,y5,y6) df2 y1 y2 y3 y4 y5 y6 1 2 NA NA 2 NA 5 2 1 NA 9 NA 2 5 3 1 1 9 NA 3 5 4 NA 0 6 3 3 5 5 2 1 NA 3 2 NA 6 2 NA 6 NA 3 NA 7 NA 0 6 2 3 NA 8 2 NA NA 3 NA 5 9 1 1 9 NA 3 NA 10 2 NA NA 3 NA 2 11 NA 1 6 3 3 NA 12 2 NA 6 3 2 2 13 NA NA 6 2 2 NA 14 2 0 6 NA NA NA 15 2 0 6 3 NA 5 16 NA 1 9 3 2 2 17 2 NA 6 3 2 NA 18 2 1 6 3 NA 2 19 NA 1 NA NA 3 2 20 2 NA 6 3 NA 5 Finding the percentage of missing values in df2 − (sum(is.na(df2))/prod(dim(df2)))*100 [1] 34.16667
[ { "code": null, "e": 1365, "s": 1062, "text": "To find the percentage of missing values in an R data frame, we can use sum function with the prod function. For example, if we have a data frame called df that contains some missing values then the percentage of missing values can be calculated by using the command: (sum(is.na(df))/prod(dim(df)))*100" }, { "code": null, "e": 1376, "s": 1365, "text": " Live Demo" }, { "code": null, "e": 1408, "s": 1376, "text": "Consider the below data frame −" }, { "code": null, "e": 1608, "s": 1408, "text": "x1<−sample(c(NA,1,5,10,15),20,replace=TRUE)\nx2<−sample(c(NA,rnorm(5)),20,replace=TRUE)\nx3<−sample(c(NA,100,200),20,replace=TRUE)\nx4<−sample(c(NA,0,1),20,replace=TRUE)\ndf1<−data.frame(x1,x2,x3,x4)\ndf1" }, { "code": null, "e": 2051, "s": 1608, "text": "x1 x2 x3 x4\n1 10 −0.7734719 NA 1\n2 10 −1.8581538 200 0\n3 10 −0.7734719 100 1\n4 1 NA 200 1\n5 5 −1.8581538 100 NA\n6 10 −0.7734719 100 0\n7 5 −1.8581538 200 0\n8 10 −0.3188769 NA NA\n9 5 −0.7734719 NA 1\n10 NA 1.0589124 200 0\n11 NA −0.7734719 200 0\n12 15 −1.8581538 NA 1\n13 5 −0.7734719 200 NA\n14 5 −0.7734719 200 0\n15 10 −0.3188769 200 1\n16 15 −1.8581538 NA 1\n17 NA −1.8581538 200 0\n18 15 1.0589124 NA 1\n19 10 −0.7734719 NA 1\n20 5 −1.8581538 100 NA" }, { "code": null, "e": 2101, "s": 2051, "text": "Finding the percentage of missing values in df1 −" }, { "code": null, "e": 2138, "s": 2101, "text": "(sum(is.na(df1))/prod(dim(df1)))*100" }, { "code": null, "e": 2148, "s": 2138, "text": "[1] 18.75" }, { "code": null, "e": 2159, "s": 2148, "text": " Live Demo" }, { "code": null, "e": 2468, "s": 2159, "text": "y1<−sample(c(NA,rpois(2,1)),20,replace=TRUE)\ny2<−sample(c(NA,rpois(2,1)),20,replace=TRUE)\ny3<−sample(c(NA,rpois(2,5)),20,replace=TRUE)\ny4<−sample(c(NA,rpois(2,3)),20,replace=TRUE)\ny5<−sample(c(NA,rpois(2,2)),20,replace=TRUE)\ny6<−sample(c(NA,rpois(2,5)),20,replace=TRUE)\ndf2<−data.frame(y1,y2,y3,y4,y5,y6)\ndf2" }, { "code": null, "e": 2818, "s": 2468, "text": "y1 y2 y3 y4 y5 y6\n1 2 NA NA 2 NA 5\n2 1 NA 9 NA 2 5\n3 1 1 9 NA 3 5\n4 NA 0 6 3 3 5\n5 2 1 NA 3 2 NA\n6 2 NA 6 NA 3 NA\n7 NA 0 6 2 3 NA\n8 2 NA NA 3 NA 5\n9 1 1 9 NA 3 NA\n10 2 NA NA 3 NA 2\n11 NA 1 6 3 3 NA\n12 2 NA 6 3 2 2\n13 NA NA 6 2 2 NA\n14 2 0 6 NA NA NA\n15 2 0 6 3 NA 5\n16 NA 1 9 3 2 2\n17 2 NA 6 3 2 NA\n18 2 1 6 3 NA 2\n19 NA 1 NA NA 3 2\n20 2 NA 6 3 NA 5" }, { "code": null, "e": 2868, "s": 2818, "text": "Finding the percentage of missing values in df2 −" }, { "code": null, "e": 2905, "s": 2868, "text": "(sum(is.na(df2))/prod(dim(df2)))*100" }, { "code": null, "e": 2918, "s": 2905, "text": "[1] 34.16667" } ]
Java 8 groupingBy Example | Collectors.groupingBy() Java 8 online Tutorialspoint
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 In this tutorial, I am going to show you how to group a list of objects in Java 8. groupingBy() is a static method available in java.util.stream.Collectors. Which is used to grouping the objects on the basis of any key and then it returns a Collector. The above groupingBy() method, grouping the input elements(T) according to the classification function and returning the Map as a Collector. In this example, we are going to group the Employee objects according to the department ids. public class Employee { private int id; private int department; private String name; public Employee(int id, int department, String name) { super(); this.id = id; this.department = department; this.name = name; } public int getId() { return id; } public int getDepartment() { return department; } public String getName() { return name; } } Grouping Emploeyee objects using Java8 package com.onlinetutorialspoint.java8; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Java8_GroupingBy { public static void main(String[] args) { List < Employee > employees = Arrays.asList( new Employee(1, 10, "Chandra"), new Employee(1, 20, "Rajesh"), new Employee(1, 30, "Rahul"), new Employee(1, 20, "Ramana")); Map < Integer, List < Employee >> byDept = employees.stream().collect( Collectors.groupingBy(Employee::getDepartment)); byDept.forEach((k, v) -> System.out.println("DeptId:" +k +" " + ((List < Employee > ) v).stream().map(m -> m.getName()) .collect(Collectors.joining(",")))); } } Output: DeptId:20 Rajesh,Ramana DeptId:10 Chandra DeptId:30 Rahul Happy Learning 🙂 How to convert List to Map in Java 8 How to calculate Employees Salaries Java 8 summingInt Resolve NullPointerException in Collectors.toMap Java 8 Stream Filter Example with Objects How to get Stream count in Java 8 How to Merge Streams in Java 8 Spring Collection Dependency List Example Parallel Streams in Java 8 Example How to Convert Iterable to Stream Java 8 How to Filter null values from Java8 Stream Java 8 How to convert Stream to List How to Filter a Map in Java 8 User defined sorting with Java 8 Comparator Java 8 walk How to Read all files in a folder Java 8 how to remove duplicates from list How to convert List to Map in Java 8 How to calculate Employees Salaries Java 8 summingInt Resolve NullPointerException in Collectors.toMap Java 8 Stream Filter Example with Objects How to get Stream count in Java 8 How to Merge Streams in Java 8 Spring Collection Dependency List Example Parallel Streams in Java 8 Example How to Convert Iterable to Stream Java 8 How to Filter null values from Java8 Stream Java 8 How to convert Stream to List How to Filter a Map in Java 8 User defined sorting with Java 8 Comparator Java 8 walk How to Read all files in a folder Java 8 how to remove duplicates from list santosh miriyala April 10, 2017 at 5:52 am - Reply Hi chandrashekhar, its a nice article, Can you please prepare few posts I wish to perform the same grouping mechanism in java 7 or below versions. Milana Travis October 25, 2017 at 12:17 pm - Reply Thank you very much for your blog. I enjoyed reading this article. santosh miriyala April 10, 2017 at 5:52 am - Reply Hi chandrashekhar, its a nice article, Can you please prepare few posts I wish to perform the same grouping mechanism in java 7 or below versions. Hi chandrashekhar, its a nice article, Can you please prepare few posts I wish to perform the same grouping mechanism in java 7 or below versions. Milana Travis October 25, 2017 at 12:17 pm - Reply Thank you very much for your blog. I enjoyed reading this article. Thank you very much for your blog. I enjoyed reading this article. Δ Java8 – Install Windows Java8 – foreach Java8 – forEach with index Java8 – Stream Filter Objects Java8 – Comparator Userdefined Java8 – GroupingBy Java8 – SummingInt Java8 – walk ReadFiles Java8 – JAVA_HOME on Windows Howto – Install Java on Mac OS Howto – Convert Iterable to Stream Howto – Get common elements from two Lists Howto – Convert List to String Howto – Concatenate Arrays using Stream Howto – Remove duplicates from List Howto – Filter null values from Stream Howto – Convert List to Map Howto – Convert Stream to List Howto – Sort a Map Howto – Filter a Map Howto – Get Current UTC Time Howto – Verify an Array contains a specific value Howto – Convert ArrayList to Array Howto – Read File Line By Line Howto – Convert Date to LocalDate Howto – Merge Streams Howto – Resolve NullPointerException in toMap Howto -Get Stream count Howto – Get Min and Max values in a Stream Howto – Convert InputStream to String
[ { "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": 481, "s": 398, "text": "In this tutorial, I am going to show you how to group a list of objects in Java 8." }, { "code": null, "e": 650, "s": 481, "text": "groupingBy() is a static method available in java.util.stream.Collectors. Which is used to grouping the objects on the basis of any key and then it returns a Collector." }, { "code": null, "e": 791, "s": 650, "text": "The above groupingBy() method, grouping the input elements(T) according to the classification function and returning the Map as a Collector." }, { "code": null, "e": 884, "s": 791, "text": "In this example, we are going to group the Employee objects according to the department ids." }, { "code": null, "e": 1326, "s": 884, "text": "public class Employee {\n private int id;\n private int department;\n private String name;\n\n public Employee(int id, int department, String name) {\n super();\n this.id = id;\n this.department = department;\n this.name = name;\n }\n public int getId() {\n return id;\n }\n public int getDepartment() {\n return department;\n }\n public String getName() {\n return name;\n }\n\n}" }, { "code": null, "e": 1365, "s": 1326, "text": "Grouping Emploeyee objects using Java8" }, { "code": null, "e": 2067, "s": 1365, "text": "package com.onlinetutorialspoint.java8;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\npublic class Java8_GroupingBy {\n\n public static void main(String[] args) {\n\n List < Employee > employees = Arrays.asList(\n new Employee(1, 10, \"Chandra\"), new Employee(1, 20, \"Rajesh\"),\n new Employee(1, 30, \"Rahul\"), new Employee(1, 20, \"Ramana\"));\n\n Map < Integer, List < Employee >> byDept = employees.stream().collect(\n Collectors.groupingBy(Employee::getDepartment));\n\n byDept.forEach((k, v) -> System.out.println(\"DeptId:\" +k +\" \" +\n ((List < Employee > ) v).stream().map(m -> m.getName())\n .collect(Collectors.joining(\",\"))));\n }\n\n}" }, { "code": null, "e": 2075, "s": 2067, "text": "Output:" }, { "code": null, "e": 2136, "s": 2075, "text": "DeptId:20 Rajesh,Ramana\nDeptId:10 Chandra\nDeptId:30 Rahul" }, { "code": null, "e": 2153, "s": 2136, "text": "Happy Learning 🙂" }, { "code": null, "e": 2763, "s": 2153, "text": "\nHow to convert List to Map in Java 8\nHow to calculate Employees Salaries Java 8 summingInt\nResolve NullPointerException in Collectors.toMap\nJava 8 Stream Filter Example with Objects\nHow to get Stream count in Java 8\nHow to Merge Streams in Java 8\nSpring Collection Dependency List Example\nParallel Streams in Java 8 Example\nHow to Convert Iterable to Stream Java 8\nHow to Filter null values from Java8 Stream\nJava 8 How to convert Stream to List\nHow to Filter a Map in Java 8\nUser defined sorting with Java 8 Comparator\nJava 8 walk How to Read all files in a folder\nJava 8 how to remove duplicates from list\n" }, { "code": null, "e": 2800, "s": 2763, "text": "How to convert List to Map in Java 8" }, { "code": null, "e": 2854, "s": 2800, "text": "How to calculate Employees Salaries Java 8 summingInt" }, { "code": null, "e": 2903, "s": 2854, "text": "Resolve NullPointerException in Collectors.toMap" }, { "code": null, "e": 2945, "s": 2903, "text": "Java 8 Stream Filter Example with Objects" }, { "code": null, "e": 2979, "s": 2945, "text": "How to get Stream count in Java 8" }, { "code": null, "e": 3010, "s": 2979, "text": "How to Merge Streams in Java 8" }, { "code": null, "e": 3052, "s": 3010, "text": "Spring Collection Dependency List Example" }, { "code": null, "e": 3087, "s": 3052, "text": "Parallel Streams in Java 8 Example" }, { "code": null, "e": 3128, "s": 3087, "text": "How to Convert Iterable to Stream Java 8" }, { "code": null, "e": 3172, "s": 3128, "text": "How to Filter null values from Java8 Stream" }, { "code": null, "e": 3209, "s": 3172, "text": "Java 8 How to convert Stream to List" }, { "code": null, "e": 3239, "s": 3209, "text": "How to Filter a Map in Java 8" }, { "code": null, "e": 3283, "s": 3239, "text": "User defined sorting with Java 8 Comparator" }, { "code": null, "e": 3329, "s": 3283, "text": "Java 8 walk How to Read all files in a folder" }, { "code": null, "e": 3371, "s": 3329, "text": "Java 8 how to remove duplicates from list" }, { "code": null, "e": 3711, "s": 3371, "text": "\n\n\n\n\n\nsantosh miriyala\nApril 10, 2017 at 5:52 am - Reply \n\nHi chandrashekhar, its a nice article, Can you please prepare few posts I wish to perform the same grouping mechanism in java 7 or below versions.\n\n\n\n\n\n\n\n\n\nMilana Travis\nOctober 25, 2017 at 12:17 pm - Reply \n\nThank you very much for your blog.\nI enjoyed reading this article.\n\n\n\n\n" }, { "code": null, "e": 3920, "s": 3711, "text": "\n\n\n\n\nsantosh miriyala\nApril 10, 2017 at 5:52 am - Reply \n\nHi chandrashekhar, its a nice article, Can you please prepare few posts I wish to perform the same grouping mechanism in java 7 or below versions.\n\n\n\n" }, { "code": null, "e": 4067, "s": 3920, "text": "Hi chandrashekhar, its a nice article, Can you please prepare few posts I wish to perform the same grouping mechanism in java 7 or below versions." }, { "code": null, "e": 4196, "s": 4067, "text": "\n\n\n\n\nMilana Travis\nOctober 25, 2017 at 12:17 pm - Reply \n\nThank you very much for your blog.\nI enjoyed reading this article.\n\n\n\n" }, { "code": null, "e": 4231, "s": 4196, "text": "Thank you very much for your blog." }, { "code": null, "e": 4263, "s": 4231, "text": "I enjoyed reading this article." }, { "code": null, "e": 4269, "s": 4267, "text": "Δ" }, { "code": null, "e": 4294, "s": 4269, "text": " Java8 – Install Windows" }, { "code": null, "e": 4311, "s": 4294, "text": " Java8 – foreach" }, { "code": null, "e": 4339, "s": 4311, "text": " Java8 – forEach with index" }, { "code": null, "e": 4370, "s": 4339, "text": " Java8 – Stream Filter Objects" }, { "code": null, "e": 4402, "s": 4370, "text": " Java8 – Comparator Userdefined" }, { "code": null, "e": 4422, "s": 4402, "text": " Java8 – GroupingBy" }, { "code": null, "e": 4442, "s": 4422, "text": " Java8 – SummingInt" }, { "code": null, "e": 4466, "s": 4442, "text": " Java8 – walk ReadFiles" }, { "code": null, "e": 4496, "s": 4466, "text": " Java8 – JAVA_HOME on Windows" }, { "code": null, "e": 4528, "s": 4496, "text": " Howto – Install Java on Mac OS" }, { "code": null, "e": 4564, "s": 4528, "text": " Howto – Convert Iterable to Stream" }, { "code": null, "e": 4608, "s": 4564, "text": " Howto – Get common elements from two Lists" }, { "code": null, "e": 4640, "s": 4608, "text": " Howto – Convert List to String" }, { "code": null, "e": 4681, "s": 4640, "text": " Howto – Concatenate Arrays using Stream" }, { "code": null, "e": 4718, "s": 4681, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 4758, "s": 4718, "text": " Howto – Filter null values from Stream" }, { "code": null, "e": 4787, "s": 4758, "text": " Howto – Convert List to Map" }, { "code": null, "e": 4819, "s": 4787, "text": " Howto – Convert Stream to List" }, { "code": null, "e": 4839, "s": 4819, "text": " Howto – Sort a Map" }, { "code": null, "e": 4861, "s": 4839, "text": " Howto – Filter a Map" }, { "code": null, "e": 4891, "s": 4861, "text": " Howto – Get Current UTC Time" }, { "code": null, "e": 4942, "s": 4891, "text": " Howto – Verify an Array contains a specific value" }, { "code": null, "e": 4978, "s": 4942, "text": " Howto – Convert ArrayList to Array" }, { "code": null, "e": 5010, "s": 4978, "text": " Howto – Read File Line By Line" }, { "code": null, "e": 5045, "s": 5010, "text": " Howto – Convert Date to LocalDate" }, { "code": null, "e": 5068, "s": 5045, "text": " Howto – Merge Streams" }, { "code": null, "e": 5115, "s": 5068, "text": " Howto – Resolve NullPointerException in toMap" }, { "code": null, "e": 5140, "s": 5115, "text": " Howto -Get Stream count" }, { "code": null, "e": 5184, "s": 5140, "text": " Howto – Get Min and Max values in a Stream" } ]
SAP ABAP - Data Types
While programming in ABAP, we need to use a variety of variables to store various information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. You may like to store information of various data types like character, integer, floating point, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. ABAP offers the programmer a rich assortment of fixed length as well as variable length data types. Following table lists down ABAP elementary data types − Some of the fields and numbers can be modified using one or more names as the following − byte numeric character-like The following table shows the data type, how much memory it takes to store the value in memory, and the minimum and maximum value that could be stored in such type of variables. REPORT YR_SEP_12. DATA text_line TYPE C LENGTH 40. text_line = 'A Chapter on Data Types'. Write text_line. DATA text_string TYPE STRING. text_string = 'A Program in ABAP'. Write / text_string. DATA d_date TYPE D. d_date = SY-DATUM. Write / d_date. In this example, we have a character string of type C with a predefined length 40. STRING is a data type that can be used for any character string of variable length (text strings). Type STRING data objects should generally be used for character-like content where fixed length is not important. The above code produces the following output − A Chapter on Data Types A Program in ABAP 12092015 The DATE type is used for the storage of date information and can store eight digits as shown above. The complex types are classified into Structure types and Table types. In the structure types, elementary types and structures (i.e. structure embedded in a structure) are grouped together. You may consider only the grouping of elementary types. But you must be aware of the availability of nesting of structures. When the elementary types are grouped together, the data item can be accessed as a grouped data item or the individual elementary type data items (structure fields) can be accessed. The table types are better known as arrays in other programming languages. Arrays can be simple or structure arrays. In ABAP, arrays are called internal tables and they can be declared and operated upon in many ways when compared to other programming languages. The following table shows the parameters according to which internal tables are characterized. Line or row type Row of an internal table can be of elementary, complex or reference type. Key Specifies a field or a group of fields as a key of an internal table that identifies the table rows. A key contains the fields of elementary types. Access method Describes how ABAP programs access individual table entries. Reference types are used to refer to instances of classes, interfaces, and run-time data items. The ABAP OOP run-time type services (RTTS) enables declaration of data items at run-time. 25 Lectures 6 hours Sanjo Thomas 26 Lectures 2 hours Neha Gupta 30 Lectures 2.5 hours Sumit Agarwal 30 Lectures 4 hours Sumit Agarwal 14 Lectures 1.5 hours Neha Malik 13 Lectures 1.5 hours Neha Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 3372, "s": 2898, "text": "While programming in ABAP, we need to use a variety of variables to store various information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. You may like to store information of various data types like character, integer, floating point, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory." }, { "code": null, "e": 3528, "s": 3372, "text": "ABAP offers the programmer a rich assortment of fixed length as well as variable length data types. Following table lists down ABAP elementary data types −" }, { "code": null, "e": 3618, "s": 3528, "text": "Some of the fields and numbers can be modified using one or more names as the following −" }, { "code": null, "e": 3623, "s": 3618, "text": "byte" }, { "code": null, "e": 3631, "s": 3623, "text": "numeric" }, { "code": null, "e": 3646, "s": 3631, "text": "character-like" }, { "code": null, "e": 3824, "s": 3646, "text": "The following table shows the data type, how much memory it takes to store the value in memory, and the minimum and maximum value that could be stored in such type of variables." }, { "code": null, "e": 4083, "s": 3824, "text": "REPORT YR_SEP_12. \nDATA text_line TYPE C LENGTH 40. \ntext_line = 'A Chapter on Data Types'. \nWrite text_line. \n\nDATA text_string TYPE STRING. \ntext_string = 'A Program in ABAP'. \nWrite / text_string. \n\nDATA d_date TYPE D. \nd_date = SY-DATUM. \nWrite / d_date." }, { "code": null, "e": 4379, "s": 4083, "text": "In this example, we have a character string of type C with a predefined length 40. STRING is a data type that can be used for any character string of variable length (text strings). Type STRING data objects should generally be used for character-like content where fixed length is not important." }, { "code": null, "e": 4426, "s": 4379, "text": "The above code produces the following output −" }, { "code": null, "e": 4481, "s": 4426, "text": "A Chapter on Data Types \nA Program in ABAP \n12092015 \n" }, { "code": null, "e": 4582, "s": 4481, "text": "The DATE type is used for the storage of date information and can store eight digits as shown above." }, { "code": null, "e": 4896, "s": 4582, "text": "The complex types are classified into Structure types and Table types. In the structure types, elementary types and structures (i.e. structure embedded in a structure) are grouped together. You may consider only the grouping of elementary types. But you must be aware of the availability of nesting of structures." }, { "code": null, "e": 5435, "s": 4896, "text": "When the elementary types are grouped together, the data item can be accessed as a grouped data item or the individual elementary type data items (structure fields) can be accessed. The table types are better known as arrays in other programming languages. Arrays can be simple or structure arrays. In ABAP, arrays are called internal tables and they can be declared and operated upon in many ways when compared to other programming languages. The following table shows the parameters according to which internal tables are characterized." }, { "code": null, "e": 5452, "s": 5435, "text": "Line or row type" }, { "code": null, "e": 5526, "s": 5452, "text": "Row of an internal table can be of elementary, complex or reference type." }, { "code": null, "e": 5530, "s": 5526, "text": "Key" }, { "code": null, "e": 5678, "s": 5530, "text": "Specifies a field or a group of fields as a key of an internal table that identifies the table rows. A key contains the fields of elementary types." }, { "code": null, "e": 5692, "s": 5678, "text": "Access method" }, { "code": null, "e": 5753, "s": 5692, "text": "Describes how ABAP programs access individual table entries." }, { "code": null, "e": 5939, "s": 5753, "text": "Reference types are used to refer to instances of classes, interfaces, and run-time data items. The ABAP OOP run-time type services (RTTS) enables declaration of data items at run-time." }, { "code": null, "e": 5972, "s": 5939, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 5986, "s": 5972, "text": " Sanjo Thomas" }, { "code": null, "e": 6019, "s": 5986, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 6031, "s": 6019, "text": " Neha Gupta" }, { "code": null, "e": 6066, "s": 6031, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6081, "s": 6066, "text": " Sumit Agarwal" }, { "code": null, "e": 6114, "s": 6081, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 6129, "s": 6114, "text": " Sumit Agarwal" }, { "code": null, "e": 6164, "s": 6129, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6176, "s": 6164, "text": " Neha Malik" }, { "code": null, "e": 6211, "s": 6176, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6223, "s": 6211, "text": " Neha Malik" }, { "code": null, "e": 6230, "s": 6223, "text": " Print" }, { "code": null, "e": 6241, "s": 6230, "text": " Add Notes" } ]
How to Use str_replace in R? - GeeksforGeeks
02 Dec, 2021 str_replace() is used to replace the given string with a particular value in R Programming Language. It is available in stringr library, so we have to load this library. Syntax: str_replace( "replacing string", "replaced string") where, replacing string is the string to be replaced replaced string is the final string We will use str_replace in dataframe. We can replace particular string in dataframe column by using the following syntax str_replace(dataframe$column_name, "replacing string", "replaced string") where, dataframe is the input dataframe column_name is the column in the dataframe Example: R # load the librarylibrary(stringr) # create a dataframe with 3 columnsdata = data.frame(name1=c('java', 'python', 'php'), name2=c('html', 'css', 'jsp'), marks=c(78, 89, 77)) # replace the java with oops in name1 columnprint(str_replace(data$name1, "java", "oops")) # replace the htmlwith oops in name2 columnprint(str_replace(data$name2, "html", "HTML5")) Output: [1] "oops" "python" "php" [1] "HTML5" "css" "jsp" We can replace the string with “” empty. Syntax: str_replace(dataframe$column_name, "replacing string", "") Example : R # load the librarylibrary(stringr) # create a dataframe with 3 columnsdata = data.frame(name1=c('java', 'python', 'php'), name2=c('html', 'css', 'jsp'), marks=c(78, 89, 77)) # replace the java with nothing in name1 columnprint(str_replace(data$name1, "java", "")) # replace the html with nothing in name2 columnprint(str_replace(data$name2, "html", "")) Output: [1] "" "python" "php" [1] "" "css" "jsp" We can replace multiple string in a particular column by using str_replace_all method. Syntax: str_replace_all(dataframe$column_name, c(“string1” = “new string”,.................,”stringn” = “new string”)) Example: R # load the librarylibrary(stringr) # create a dataframe with 3 columnsdata = data.frame(name1=c('java', 'python', 'php'), name2=c('html', 'css', 'jsp'), marks=c(78, 89, 77)) # replace the java with oops and php with sql in name1 columnprint(str_replace_all(data$name1, c("java"="oops", "php"="sql"))) # replace the html with r and jsp with servletsin name2 columnprint(str_replace_all(data$name2, c("html"="R", "jsp"="servlets"))) Output: [1] "oops" "python" "sql" [1] "R" "css" "servlets" kapoorsagar226 sumitgumber28 Picked R-Functions R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? How to change the order of bars in bar chart in R ?
[ { "code": null, "e": 24851, "s": 24823, "text": "\n02 Dec, 2021" }, { "code": null, "e": 25021, "s": 24851, "text": "str_replace() is used to replace the given string with a particular value in R Programming Language. It is available in stringr library, so we have to load this library." }, { "code": null, "e": 25029, "s": 25021, "text": "Syntax:" }, { "code": null, "e": 25081, "s": 25029, "text": "str_replace( \"replacing string\", \"replaced string\")" }, { "code": null, "e": 25088, "s": 25081, "text": "where," }, { "code": null, "e": 25134, "s": 25088, "text": "replacing string is the string to be replaced" }, { "code": null, "e": 25170, "s": 25134, "text": "replaced string is the final string" }, { "code": null, "e": 25291, "s": 25170, "text": "We will use str_replace in dataframe. We can replace particular string in dataframe column by using the following syntax" }, { "code": null, "e": 25365, "s": 25291, "text": "str_replace(dataframe$column_name, \"replacing string\", \"replaced string\")" }, { "code": null, "e": 25372, "s": 25365, "text": "where," }, { "code": null, "e": 25405, "s": 25372, "text": "dataframe is the input dataframe" }, { "code": null, "e": 25448, "s": 25405, "text": "column_name is the column in the dataframe" }, { "code": null, "e": 25457, "s": 25448, "text": "Example:" }, { "code": null, "e": 25459, "s": 25457, "text": "R" }, { "code": "# load the librarylibrary(stringr) # create a dataframe with 3 columnsdata = data.frame(name1=c('java', 'python', 'php'), name2=c('html', 'css', 'jsp'), marks=c(78, 89, 77)) # replace the java with oops in name1 columnprint(str_replace(data$name1, \"java\", \"oops\")) # replace the htmlwith oops in name2 columnprint(str_replace(data$name2, \"html\", \"HTML5\"))", "e": 25849, "s": 25459, "text": null }, { "code": null, "e": 25857, "s": 25849, "text": "Output:" }, { "code": null, "e": 25916, "s": 25857, "text": "[1] \"oops\" \"python\" \"php\" \n[1] \"HTML5\" \"css\" \"jsp\" " }, { "code": null, "e": 25957, "s": 25916, "text": "We can replace the string with “” empty." }, { "code": null, "e": 25965, "s": 25957, "text": "Syntax:" }, { "code": null, "e": 26024, "s": 25965, "text": "str_replace(dataframe$column_name, \"replacing string\", \"\")" }, { "code": null, "e": 26034, "s": 26024, "text": "Example :" }, { "code": null, "e": 26036, "s": 26034, "text": "R" }, { "code": "# load the librarylibrary(stringr) # create a dataframe with 3 columnsdata = data.frame(name1=c('java', 'python', 'php'), name2=c('html', 'css', 'jsp'), marks=c(78, 89, 77)) # replace the java with nothing in name1 columnprint(str_replace(data$name1, \"java\", \"\")) # replace the html with nothing in name2 columnprint(str_replace(data$name2, \"html\", \"\"))", "e": 26424, "s": 26036, "text": null }, { "code": null, "e": 26432, "s": 26424, "text": "Output:" }, { "code": null, "e": 26485, "s": 26432, "text": "[1] \"\" \"python\" \"php\" \n[1] \"\" \"css\" \"jsp\"" }, { "code": null, "e": 26572, "s": 26485, "text": "We can replace multiple string in a particular column by using str_replace_all method." }, { "code": null, "e": 26580, "s": 26572, "text": "Syntax:" }, { "code": null, "e": 26691, "s": 26580, "text": "str_replace_all(dataframe$column_name, c(“string1” = “new string”,.................,”stringn” = “new string”))" }, { "code": null, "e": 26700, "s": 26691, "text": "Example:" }, { "code": null, "e": 26702, "s": 26700, "text": "R" }, { "code": "# load the librarylibrary(stringr) # create a dataframe with 3 columnsdata = data.frame(name1=c('java', 'python', 'php'), name2=c('html', 'css', 'jsp'), marks=c(78, 89, 77)) # replace the java with oops and php with sql in name1 columnprint(str_replace_all(data$name1, c(\"java\"=\"oops\", \"php\"=\"sql\"))) # replace the html with r and jsp with servletsin name2 columnprint(str_replace_all(data$name2, c(\"html\"=\"R\", \"jsp\"=\"servlets\")))", "e": 27168, "s": 26702, "text": null }, { "code": null, "e": 27176, "s": 27168, "text": "Output:" }, { "code": null, "e": 27244, "s": 27176, "text": "[1] \"oops\" \"python\" \"sql\" \n[1] \"R\" \"css\" \"servlets\"" }, { "code": null, "e": 27259, "s": 27244, "text": "kapoorsagar226" }, { "code": null, "e": 27273, "s": 27259, "text": "sumitgumber28" }, { "code": null, "e": 27280, "s": 27273, "text": "Picked" }, { "code": null, "e": 27292, "s": 27280, "text": "R-Functions" }, { "code": null, "e": 27303, "s": 27292, "text": "R Language" }, { "code": null, "e": 27401, "s": 27303, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27410, "s": 27401, "text": "Comments" }, { "code": null, "e": 27423, "s": 27410, "text": "Old Comments" }, { "code": null, "e": 27475, "s": 27423, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27513, "s": 27475, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27548, "s": 27513, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27606, "s": 27548, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27649, "s": 27606, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27698, "s": 27649, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27748, "s": 27698, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27765, "s": 27748, "text": "R - if statement" }, { "code": null, "e": 27802, "s": 27765, "text": "How to import an Excel File into R ?" } ]
Class and Static Variables in C#
Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it. Static variables can be initialized outside the member function or class definition. You can also initialize static variables inside the class definition. Live Demo using System; namespace StaticVarApplication { class StaticVar { public static int num; public void count() { num++; } public int getNum() { return num; } } class StaticTester { static void Main(string[] args) { StaticVar s1 = new StaticVar(); StaticVar s2 = new StaticVar(); s1.count(); s1.count(); s1.count(); s2.count(); s2.count(); s2.count(); Console.WriteLine("Variable num for s1: {0}", s1.getNum()); Console.WriteLine("Variable num for s2: {0}", s2.getNum()); Console.ReadKey(); } } } Variable num for s1: 6 Variable num for s2: 6 Class variables are the attributes of an object (from design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions. Let us see an example − Live Demo using System; namespace BoxApplication { class Box { private double length; // Length of a box private double breadth; // Breadth of a box private double height; // Height of a box public void setLength( double len ) { length = len; } public void setBreadth( double bre ) { breadth = bre; } public void setHeight( double hei ) { height = hei; } public double getVolume() { return length * breadth * height; } } class Boxtester { static void Main(string[] args) { Box Box1 = new Box(); // Declare Box1 of type Box Box Box2 = new Box(); double volume; // Declare Box2 of type Box // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // volume of box 1 volume = Box1.getVolume(); Console.WriteLine("Volume of Box1 : {0}" ,volume); // volume of box 2 volume = Box2.getVolume(); Console.WriteLine("Volume of Box2 : {0}", volume); Console.ReadKey(); } } } Volume of Box1 : 210 Volume of Box2 : 1560
[ { "code": null, "e": 1362, "s": 1062, "text": "Static variables are used for defining constants because their values can be retrieved by invoking the\nclass without creating an instance of it. Static variables can be initialized outside the member function or class definition. You can also initialize static variables inside the class definition." }, { "code": null, "e": 1373, "s": 1362, "text": " Live Demo" }, { "code": null, "e": 2042, "s": 1373, "text": "using System;\n\nnamespace StaticVarApplication {\n class StaticVar {\n public static int num;\n\n public void count() {\n num++;\n }\n public int getNum() {\n return num;\n }\n }\n class StaticTester {\n static void Main(string[] args) {\n StaticVar s1 = new StaticVar();\n StaticVar s2 = new StaticVar();\n\n s1.count();\n s1.count();\n s1.count();\n\n s2.count();\n s2.count();\n s2.count();\n\n Console.WriteLine(\"Variable num for s1: {0}\", s1.getNum());\n Console.WriteLine(\"Variable num for s2: {0}\", s2.getNum());\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 2088, "s": 2042, "text": "Variable num for s1: 6\nVariable num for s2: 6" }, { "code": null, "e": 2288, "s": 2088, "text": "Class variables are the attributes of an object (from design perspective) and they are kept private to\nimplement encapsulation. These variables can only be accessed using the public member functions." }, { "code": null, "e": 2312, "s": 2288, "text": "Let us see an example −" }, { "code": null, "e": 2323, "s": 2312, "text": " Live Demo" }, { "code": null, "e": 3600, "s": 2323, "text": "using System;\n\nnamespace BoxApplication {\n class Box {\n private double length; // Length of a box\n private double breadth; // Breadth of a box\n private double height; // Height of a box\n\n public void setLength( double len ) {\n length = len;\n }\n public void setBreadth( double bre ) {\n breadth = bre;\n }\n public void setHeight( double hei ) {\n height = hei;\n }\n public double getVolume() {\n return length * breadth * height;\n }\n }\n class Boxtester {\n static void Main(string[] args) {\n Box Box1 = new Box(); // Declare Box1 of type Box\n Box Box2 = new Box();\n double volume;\n\n // Declare Box2 of type Box\n // box 1 specification\n Box1.setLength(6.0);\n Box1.setBreadth(7.0);\n Box1.setHeight(5.0);\n\n // box 2 specification\n Box2.setLength(12.0);\n Box2.setBreadth(13.0);\n Box2.setHeight(10.0);\n\n // volume of box 1\n volume = Box1.getVolume();\n Console.WriteLine(\"Volume of Box1 : {0}\" ,volume);\n\n // volume of box 2\n volume = Box2.getVolume();\n Console.WriteLine(\"Volume of Box2 : {0}\", volume);\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 3643, "s": 3600, "text": "Volume of Box1 : 210\nVolume of Box2 : 1560" } ]
MySQL query to count rows with mutual relation using JOIN?
For this, use aggregate function COUNT(*). Let us first create a table − mysql> create table DemoTable1543 -> ( -> Value1 int, -> Value2 int -> ); Query OK, 0 rows affected (1.36 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1543 values(57,60); Query OK, 1 row affected (0.52 sec) mysql> insert into DemoTable1543 values(60,68); Query OK, 1 row affected (0.38 sec) mysql> insert into DemoTable1543 values(90,98); Query OK, 1 row affected (0.36 sec) mysql> insert into DemoTable1543 values(98,90); Query OK, 1 row affected (0.20 sec) Display all records from the table using select statement − mysql> select * from DemoTable1543; This will produce the following output − +--------+--------+ | Value1 | Value2 | +--------+--------+ | 57 | 60 | | 60 | 68 | | 90 | 98 | | 98 | 90 | +--------+--------+ 4 rows in set (0.00 sec) Here is the query to count rows with mutual relation like the number 90 in both the columns − mysql> select count(*) from DemoTable1543 tbl1 -> join DemoTable1543 tbl2 -> on tbl1.Value2=tbl2.Value1 -> where tbl1.Value1=90 and tbl2.Value2=90; This will produce the following output − +----------+ | count(*) | +----------+ | 1 | +----------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1135, "s": 1062, "text": "For this, use aggregate function COUNT(*). Let us first create a table −" }, { "code": null, "e": 1258, "s": 1135, "text": "mysql> create table DemoTable1543\n -> (\n -> Value1 int,\n -> Value2 int\n -> );\nQuery OK, 0 rows affected (1.36 sec)" }, { "code": null, "e": 1314, "s": 1258, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1650, "s": 1314, "text": "mysql> insert into DemoTable1543 values(57,60);\nQuery OK, 1 row affected (0.52 sec)\nmysql> insert into DemoTable1543 values(60,68);\nQuery OK, 1 row affected (0.38 sec)\nmysql> insert into DemoTable1543 values(90,98);\nQuery OK, 1 row affected (0.36 sec)\nmysql> insert into DemoTable1543 values(98,90);\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 1710, "s": 1650, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1746, "s": 1710, "text": "mysql> select * from DemoTable1543;" }, { "code": null, "e": 1787, "s": 1746, "text": "This will produce the following output −" }, { "code": null, "e": 1972, "s": 1787, "text": "+--------+--------+\n| Value1 | Value2 |\n+--------+--------+\n| 57 | 60 |\n| 60 | 68 |\n| 90 | 98 |\n| 98 | 90 |\n+--------+--------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2066, "s": 1972, "text": "Here is the query to count rows with mutual relation like the number 90 in both the columns −" }, { "code": null, "e": 2223, "s": 2066, "text": "mysql> select count(*) from DemoTable1543 tbl1\n -> join DemoTable1543 tbl2\n -> on tbl1.Value2=tbl2.Value1\n -> where tbl1.Value1=90 and tbl2.Value2=90;" }, { "code": null, "e": 2264, "s": 2223, "text": "This will produce the following output −" }, { "code": null, "e": 2353, "s": 2264, "text": "+----------+\n| count(*) |\n+----------+\n| 1 |\n+----------+\n1 row in set (0.00 sec)" } ]
How to convert a color integer to a hex String in Android?
This example demonstrates how do I in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:textSize="24sp" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.textView); int intColor = -16895234; String hexColor = Integer.toHexString(intColor).substring(2); textView.setText("#"+hexColor); } } 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" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code
[ { "code": null, "e": 1109, "s": 1062, "text": "This example demonstrates how do I in android." }, { "code": null, "e": 1238, "s": 1109, "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": 1303, "s": 1238, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1835, "s": 1303, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout 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 <TextView\n android:id=\"@+id/textView\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"/>\n</RelativeLayout>" }, { "code": null, "e": 1892, "s": 1835, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2410, "s": 1892, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView textView = findViewById(R.id.textView);\n int intColor = -16895234;\n String hexColor = Integer.toHexString(intColor).substring(2);\n textView.setText(\"#\"+hexColor);\n }\n}" }, { "code": null, "e": 2465, "s": 2410, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3138, "s": 2465, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n 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 <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3486, "s": 3138, "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": 3526, "s": 3486, "text": "Click here to download the project code" } ]
Bootstrap .has-error class
The has-error class allows you to set error for input. You can try to run the following code to implement the has-error class Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <form class = "form-horizontal" role = "form"> <div class = "form-group has-error"> <label class = "col-sm-2 control-label" for = "inputError"> Input with error </label> <div class = "col-sm-10"> <input type = "text" class = "form-control" id = "inputError"> </div> </div> </form> </body> </html>
[ { "code": null, "e": 1117, "s": 1062, "text": "The has-error class allows you to set error for input." }, { "code": null, "e": 1188, "s": 1117, "text": "You can try to run the following code to implement the has-error class" }, { "code": null, "e": 1198, "s": 1188, "text": "Live Demo" }, { "code": null, "e": 1891, "s": 1198, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <form class = \"form-horizontal\" role = \"form\">\n <div class = \"form-group has-error\">\n <label class = \"col-sm-2 control-label\" for = \"inputError\">\n Input with error\n </label>\n <div class = \"col-sm-10\">\n <input type = \"text\" class = \"form-control\" id = \"inputError\">\n </div>\n </div>\n </form>\n </body>\n</html>" } ]
bits.Sub() Function in Golang with Examples - GeeksforGeeks
28 Apr, 2020 The bits.Sub() Function in Golang is used to find the difference of a, b and borrow, i.e. diff = a – b – borrow. Here the borrow must be 0 or 1; otherwise, the behavior is undefined. To access this function, one needs to imports the math/bits package in the program. The return value of the borrowOutput will be always 0 or 1 in any case. Syntax: func Sub(a, b, borrow uint) (diff, borrowOut uint) Parameters: This function takes three parameters of uint type, i.e., a, b, and borrow. The value of borrow parameter is either 1 or 0 Return Value: This function return two values of uint type, i.e., diff and borrowOut. Here diff contains the result of a – b – borrow and borrowOut is either 1 or 0. Example 1: // Golang program to illustrate bits.Sub() Function package main import ( "fmt" "math/bits") // Main function func main() { // Finding diff and borrowOu // of the specified numbers // Using Sub() function nvalue_1, borrowOut := bits.Sub(4, 3, 0) fmt.Println("Diff:", nvalue_1) fmt.Println("BorrowOut :", borrowOut ) } Output: Diff: 1 BorrowOut : 0 Example 2: // Golang program to illustrate bits.Sub() Functionpackage main import ( "fmt" "math/bits") // Main functionfunc main() { // Finding diff and borrowOut // of the specified numbers // Using Sub() function var a, b, borrow uint = 10, 5, 1 Diff, borrowOut := bits.Sub(a, b, borrow) fmt.Println("Number 1:", a) fmt.Println("Number 2:", b) fmt.Println("Borrow :", borrow) fmt.Println("Diff:", Diff) fmt.Println("BorrowOut :", borrowOut) } Output: Number 1: 10 Number 2: 5 Borrow : 1 Diff: 4 BorrowOut : 0 Golang-bits Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments strings.Replace() Function in Golang With Examples How to Split a String in Golang? Arrays in Go How to Trim a String in Golang? How to convert a string in lower case in Golang? Golang Maps Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang? Slices in Golang Inheritance in GoLang
[ { "code": null, "e": 24340, "s": 24312, "text": "\n28 Apr, 2020" }, { "code": null, "e": 24679, "s": 24340, "text": "The bits.Sub() Function in Golang is used to find the difference of a, b and borrow, i.e. diff = a – b – borrow. Here the borrow must be 0 or 1; otherwise, the behavior is undefined. To access this function, one needs to imports the math/bits package in the program. The return value of the borrowOutput will be always 0 or 1 in any case." }, { "code": null, "e": 24687, "s": 24679, "text": "Syntax:" }, { "code": null, "e": 24739, "s": 24687, "text": "func Sub(a, b, borrow uint) (diff, borrowOut uint)\n" }, { "code": null, "e": 24873, "s": 24739, "text": "Parameters: This function takes three parameters of uint type, i.e., a, b, and borrow. The value of borrow parameter is either 1 or 0" }, { "code": null, "e": 25039, "s": 24873, "text": "Return Value: This function return two values of uint type, i.e., diff and borrowOut. Here diff contains the result of a – b – borrow and borrowOut is either 1 or 0." }, { "code": null, "e": 25050, "s": 25039, "text": "Example 1:" }, { "code": "// Golang program to illustrate bits.Sub() Function package main import ( \"fmt\" \"math/bits\") // Main function func main() { // Finding diff and borrowOu // of the specified numbers // Using Sub() function nvalue_1, borrowOut := bits.Sub(4, 3, 0) fmt.Println(\"Diff:\", nvalue_1) fmt.Println(\"BorrowOut :\", borrowOut ) } ", "e": 25416, "s": 25050, "text": null }, { "code": null, "e": 25424, "s": 25416, "text": "Output:" }, { "code": null, "e": 25447, "s": 25424, "text": "Diff: 1\nBorrowOut : 0\n" }, { "code": null, "e": 25458, "s": 25447, "text": "Example 2:" }, { "code": "// Golang program to illustrate bits.Sub() Functionpackage main import ( \"fmt\" \"math/bits\") // Main functionfunc main() { // Finding diff and borrowOut // of the specified numbers // Using Sub() function var a, b, borrow uint = 10, 5, 1 Diff, borrowOut := bits.Sub(a, b, borrow) fmt.Println(\"Number 1:\", a) fmt.Println(\"Number 2:\", b) fmt.Println(\"Borrow :\", borrow) fmt.Println(\"Diff:\", Diff) fmt.Println(\"BorrowOut :\", borrowOut) }", "e": 25935, "s": 25458, "text": null }, { "code": null, "e": 25943, "s": 25935, "text": "Output:" }, { "code": null, "e": 26002, "s": 25943, "text": "Number 1: 10\nNumber 2: 5\nBorrow : 1\nDiff: 4\nBorrowOut : 0\n" }, { "code": null, "e": 26014, "s": 26002, "text": "Golang-bits" }, { "code": null, "e": 26026, "s": 26014, "text": "Go Language" }, { "code": null, "e": 26124, "s": 26026, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26133, "s": 26124, "text": "Comments" }, { "code": null, "e": 26146, "s": 26133, "text": "Old Comments" }, { "code": null, "e": 26197, "s": 26146, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 26230, "s": 26197, "text": "How to Split a String in Golang?" }, { "code": null, "e": 26243, "s": 26230, "text": "Arrays in Go" }, { "code": null, "e": 26275, "s": 26243, "text": "How to Trim a String in Golang?" }, { "code": null, "e": 26324, "s": 26275, "text": "How to convert a string in lower case in Golang?" }, { "code": null, "e": 26336, "s": 26324, "text": "Golang Maps" }, { "code": null, "e": 26390, "s": 26336, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 26419, "s": 26390, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 26436, "s": 26419, "text": "Slices in Golang" } ]
Deploy ML models at scale. Part 1: API service for ML models | by Prajwal Shreyas | Towards Data Science
Let’s assume that you have built a ML model and that you are happy with its performance. Then the next step is to deploy the model into production. In this blog series I will cover how you can deploy your model for large scale consumption with in a scalable Infrastructure using AWS using docker container service. In this blog I will start with the first step of building an API framework for the ML model and running it in you local machine. For the purpose of this blog, let’s consider the Sentiment classification model built here. In order to deploy this model we will follow the below steps: Convert the model into .hdf5 file or .pkl fileImplement a Flask APIRun the API Convert the model into .hdf5 file or .pkl file Implement a Flask API Run the API In case the model is a built on sklearn, it would be best to save it as a ‘.pkl’ file. Alternatively if it is a deep learning model then it is recommended to save the model as a ‘HDF’ file. The main difference between ‘.pkl’ and ‘.hdf’ is, pickle requires a large amount of memory to save a data structure to disk, where as HDF is designed to efficiently store large data sets. Save model in Pickle(.pkl): from sklearn.externals import joblib # Save to file# Fit the model (example of a model in sklearn)model = LogisticRegression()model.fit(X_train, Y_train)#working directoryjoblib_file = "best_model.pkl" joblib.dump(model, joblib_file) Save model in HDF(.hdf5): Once you have trained your deep learning model in keras or tensorflow you can save the model architecture and its weights using a .hdf5 file system. # save the best model and early stoppingsaveBestModel = keras.callbacks.ModelCheckpoint('/best_model.hdf5', monitor='val_acc', verbose=0, save_best_only=True, save_weights_only=False, mode='auto', period=1) Step 1: Load the saved model (as per previous section) by one of the following methods depending on the type of file i.e. ‘hdf5’ or ‘pkl’. HDF5: from keras.models import load_modelimport h5pyprd_model = load_model('best_model.hdf5') PKL: from sklearn.externals import joblibloaded_model = joblib.load('best_model.pkl') Step 2: Import flask and create a flask application object as shown below: from flask import Flask, url_for, requestapp = Flask(__name__) Step 3: The next step is to build a test API function which returns the “API working” string. This can be used to ensure the health of the API when it is deployed in production. Here we use ‘@app.route’, which is a python decorator ( a decorator is a function that takes another function and extends the behaviour of the latter function without explicitly modifying it) @app.route(‘/apitest')def apitest(): return ‘API working’ Step 4: The next step is to build a “POST” request api for processing requests to our sentiment model. We are using the path name “/sentiment”. The function reads the json input and converts it into pandas dataframe. It extracts the relevant fields from the json and calls the “get_sentiment_DL” function for processing. “get_sentiment_DL” function contains the trained model which has been loaded via ‘hdf5’ file. It finally will return back the results of the model in the form of json result. # main API [email protected](‘/sentiment’, methods=[‘POST’])def sentiment(): if request.method == ‘POST’: text_data = pd.DataFrame(request.json) text_out = get_sentiment_DL(prd_model, text_data, word_idx) text_out = text_out[[‘ref’,’Sentiment_Score’]] #Convert df to dict and then to Json text_out_dict = text_out.to_dict(orient=’records’) text_out_json = json.dumps(text_out_dict, ensure_ascii=False) return text_out_json Step 5: The detailed model processing steps will be performed by “get_sentiment_DL” function. In the case of our deep learning sentiment model we are passing: best_model: the loaded model best_model: the loaded model 2. text_data: Input text for sentiment classification 3. word_idx: Word index from the GloVe file (details of the model here). def get_sentiment_DL(best_model, text_data, word_idx):'''Modle Processing''' return sentiment_score Step 6: Add the below section to run the app. Here Host is set as “0.0.0.0” as we are hosting in our local server. However you can configure it to your network settings. Debug can be set to True at the time of building the API functionality. The Port is set to 5005, however this can be configured as per your requirement. if __name__ == “__main__”: app.run(host=”0.0.0.0", debug=False, port=5005) To run the API, open a command line window and go to the directory where the code is stored. Run the python script by running the below command (“sentiment.py” is the name of the file with the above API implementation). python sentiment.py On running the above command you will be able to see the below result in your command line window: Once the API is running you can test the API by going to your browser and typing “0.0.0.0:5005/apitest”. You will get the below result in you browser. You can now pass any data to the API using python as shown below. The address in our case is “http://0.0.0.0:5005/sentiment”. The results of the model will be returned and stored in “response” field. import requestsimport jsonimport urllib.parsedata_json = '''{"ref":[1], "text":["I am well"]}'''head= {“Content-type”: “application/json”}response = requests.post(‘http://0.0.0.0:5005/sentiment', json = data_json, headers = head)result = response.content.decode(‘utf8’) In conclusion, we have covered steps to deploy the model into an api service in your local computer. The next step is to deploy this in a cloud server as a micro service. In following blog’s I will cover the use of container service such as docker and deploy it in AWS.
[ { "code": null, "e": 487, "s": 172, "text": "Let’s assume that you have built a ML model and that you are happy with its performance. Then the next step is to deploy the model into production. In this blog series I will cover how you can deploy your model for large scale consumption with in a scalable Infrastructure using AWS using docker container service." }, { "code": null, "e": 770, "s": 487, "text": "In this blog I will start with the first step of building an API framework for the ML model and running it in you local machine. For the purpose of this blog, let’s consider the Sentiment classification model built here. In order to deploy this model we will follow the below steps:" }, { "code": null, "e": 849, "s": 770, "text": "Convert the model into .hdf5 file or .pkl fileImplement a Flask APIRun the API" }, { "code": null, "e": 896, "s": 849, "text": "Convert the model into .hdf5 file or .pkl file" }, { "code": null, "e": 918, "s": 896, "text": "Implement a Flask API" }, { "code": null, "e": 930, "s": 918, "text": "Run the API" }, { "code": null, "e": 1308, "s": 930, "text": "In case the model is a built on sklearn, it would be best to save it as a ‘.pkl’ file. Alternatively if it is a deep learning model then it is recommended to save the model as a ‘HDF’ file. The main difference between ‘.pkl’ and ‘.hdf’ is, pickle requires a large amount of memory to save a data structure to disk, where as HDF is designed to efficiently store large data sets." }, { "code": null, "e": 1336, "s": 1308, "text": "Save model in Pickle(.pkl):" }, { "code": null, "e": 1573, "s": 1336, "text": "from sklearn.externals import joblib # Save to file# Fit the model (example of a model in sklearn)model = LogisticRegression()model.fit(X_train, Y_train)#working directoryjoblib_file = \"best_model.pkl\" joblib.dump(model, joblib_file)" }, { "code": null, "e": 1599, "s": 1573, "text": "Save model in HDF(.hdf5):" }, { "code": null, "e": 1748, "s": 1599, "text": "Once you have trained your deep learning model in keras or tensorflow you can save the model architecture and its weights using a .hdf5 file system." }, { "code": null, "e": 1955, "s": 1748, "text": "# save the best model and early stoppingsaveBestModel = keras.callbacks.ModelCheckpoint('/best_model.hdf5', monitor='val_acc', verbose=0, save_best_only=True, save_weights_only=False, mode='auto', period=1)" }, { "code": null, "e": 2094, "s": 1955, "text": "Step 1: Load the saved model (as per previous section) by one of the following methods depending on the type of file i.e. ‘hdf5’ or ‘pkl’." }, { "code": null, "e": 2100, "s": 2094, "text": "HDF5:" }, { "code": null, "e": 2188, "s": 2100, "text": "from keras.models import load_modelimport h5pyprd_model = load_model('best_model.hdf5')" }, { "code": null, "e": 2193, "s": 2188, "text": "PKL:" }, { "code": null, "e": 2274, "s": 2193, "text": "from sklearn.externals import joblibloaded_model = joblib.load('best_model.pkl')" }, { "code": null, "e": 2349, "s": 2274, "text": "Step 2: Import flask and create a flask application object as shown below:" }, { "code": null, "e": 2412, "s": 2349, "text": "from flask import Flask, url_for, requestapp = Flask(__name__)" }, { "code": null, "e": 2782, "s": 2412, "text": "Step 3: The next step is to build a test API function which returns the “API working” string. This can be used to ensure the health of the API when it is deployed in production. Here we use ‘@app.route’, which is a python decorator ( a decorator is a function that takes another function and extends the behaviour of the latter function without explicitly modifying it)" }, { "code": null, "e": 2843, "s": 2782, "text": "@app.route(‘/apitest')def apitest(): return ‘API working’" }, { "code": null, "e": 3339, "s": 2843, "text": "Step 4: The next step is to build a “POST” request api for processing requests to our sentiment model. We are using the path name “/sentiment”. The function reads the json input and converts it into pandas dataframe. It extracts the relevant fields from the json and calls the “get_sentiment_DL” function for processing. “get_sentiment_DL” function contains the trained model which has been loaded via ‘hdf5’ file. It finally will return back the results of the model in the form of json result." }, { "code": null, "e": 3776, "s": 3339, "text": "# main API [email protected](‘/sentiment’, methods=[‘POST’])def sentiment(): if request.method == ‘POST’: text_data = pd.DataFrame(request.json) text_out = get_sentiment_DL(prd_model, text_data, word_idx) text_out = text_out[[‘ref’,’Sentiment_Score’]] #Convert df to dict and then to Json text_out_dict = text_out.to_dict(orient=’records’) text_out_json = json.dumps(text_out_dict, ensure_ascii=False) return text_out_json" }, { "code": null, "e": 3935, "s": 3776, "text": "Step 5: The detailed model processing steps will be performed by “get_sentiment_DL” function. In the case of our deep learning sentiment model we are passing:" }, { "code": null, "e": 3964, "s": 3935, "text": "best_model: the loaded model" }, { "code": null, "e": 3993, "s": 3964, "text": "best_model: the loaded model" }, { "code": null, "e": 4047, "s": 3993, "text": "2. text_data: Input text for sentiment classification" }, { "code": null, "e": 4120, "s": 4047, "text": "3. word_idx: Word index from the GloVe file (details of the model here)." }, { "code": null, "e": 4220, "s": 4120, "text": "def get_sentiment_DL(best_model, text_data, word_idx):'''Modle Processing''' return sentiment_score" }, { "code": null, "e": 4543, "s": 4220, "text": "Step 6: Add the below section to run the app. Here Host is set as “0.0.0.0” as we are hosting in our local server. However you can configure it to your network settings. Debug can be set to True at the time of building the API functionality. The Port is set to 5005, however this can be configured as per your requirement." }, { "code": null, "e": 4619, "s": 4543, "text": "if __name__ == “__main__”: app.run(host=”0.0.0.0\", debug=False, port=5005)" }, { "code": null, "e": 4839, "s": 4619, "text": "To run the API, open a command line window and go to the directory where the code is stored. Run the python script by running the below command (“sentiment.py” is the name of the file with the above API implementation)." }, { "code": null, "e": 4859, "s": 4839, "text": "python sentiment.py" }, { "code": null, "e": 4958, "s": 4859, "text": "On running the above command you will be able to see the below result in your command line window:" }, { "code": null, "e": 5109, "s": 4958, "text": "Once the API is running you can test the API by going to your browser and typing “0.0.0.0:5005/apitest”. You will get the below result in you browser." }, { "code": null, "e": 5309, "s": 5109, "text": "You can now pass any data to the API using python as shown below. The address in our case is “http://0.0.0.0:5005/sentiment”. The results of the model will be returned and stored in “response” field." }, { "code": null, "e": 5579, "s": 5309, "text": "import requestsimport jsonimport urllib.parsedata_json = '''{\"ref\":[1], \"text\":[\"I am well\"]}'''head= {“Content-type”: “application/json”}response = requests.post(‘http://0.0.0.0:5005/sentiment', json = data_json, headers = head)result = response.content.decode(‘utf8’)" }, { "code": null, "e": 5680, "s": 5579, "text": "In conclusion, we have covered steps to deploy the model into an api service in your local computer." } ]
Erlang - list_to_tuple
This method is to convert a list to a tuple. list_to_tuple(list) list − This is the list which needs to be converted to a tuple. list − This is the list which needs to be converted to a tuple. Returns a tuple based on the list provided. -module(helloworld). -export([start/0]). start() -> io:fwrite("~w",[list_to_tuple([1,2,3])]). The output of the above program is as follows {1,2,3} Print Add Notes Bookmark this page
[ { "code": null, "e": 2346, "s": 2301, "text": "This method is to convert a list to a tuple." }, { "code": null, "e": 2367, "s": 2346, "text": "list_to_tuple(list)\n" }, { "code": null, "e": 2431, "s": 2367, "text": "list − This is the list which needs to be converted to a tuple." }, { "code": null, "e": 2495, "s": 2431, "text": "list − This is the list which needs to be converted to a tuple." }, { "code": null, "e": 2539, "s": 2495, "text": "Returns a tuple based on the list provided." }, { "code": null, "e": 2640, "s": 2539, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n io:fwrite(\"~w\",[list_to_tuple([1,2,3])])." }, { "code": null, "e": 2686, "s": 2640, "text": "The output of the above program is as follows" }, { "code": null, "e": 2695, "s": 2686, "text": "{1,2,3}\n" }, { "code": null, "e": 2702, "s": 2695, "text": " Print" }, { "code": null, "e": 2713, "s": 2702, "text": " Add Notes" } ]
How to display the JList items from top to bottom and left to right in Java?
For this, set the layout orientation to the following − setLayoutOrientation(JList.VERTICAL_WRAP); The following is an example to display the JList items from top to bottom and left to right − package my; import java.awt.BorderLayout; import java.util.ArrayList ; import java.util.List; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; public class SwingDemo { public static void main(String[] args) { JPanel panel = new JPanel(new BorderLayout()); List<String> myList = new ArrayList<>(10); for (int index = 0; index < 20; index++) { myList.add("List Item " + index); } final JList<String> list = new JList<String>(myList.toArray(new String[myList.size()])); JScrollPane scrollPane = new JScrollPane(); scrollPane.setViewportView(list); list.setLayoutOrientation(JList.VERTICAL_WRAP); panel.add(scrollPane); JFrame frame = new JFrame("Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(panel); frame.setSize(500, 250); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
[ { "code": null, "e": 1118, "s": 1062, "text": "For this, set the layout orientation to the following −" }, { "code": null, "e": 1161, "s": 1118, "text": "setLayoutOrientation(JList.VERTICAL_WRAP);" }, { "code": null, "e": 1255, "s": 1161, "text": "The following is an example to display the JList items from top to bottom and left to right −" }, { "code": null, "e": 2234, "s": 1255, "text": "package my;\nimport java.awt.BorderLayout;\nimport java.util.ArrayList ;\nimport java.util.List;\nimport javax.swing.JFrame;\nimport javax.swing.JList;\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\npublic class SwingDemo {\n public static void main(String[] args) {\n JPanel panel = new JPanel(new BorderLayout());\n List<String> myList = new ArrayList<>(10);\n for (int index = 0; index < 20; index++) {\n myList.add(\"List Item \" + index);\n }\n final JList<String> list = new JList<String>(myList.toArray(new String[myList.size()]));\n JScrollPane scrollPane = new JScrollPane();\n scrollPane.setViewportView(list);\n list.setLayoutOrientation(JList.VERTICAL_WRAP);\n panel.add(scrollPane);\n JFrame frame = new JFrame(\"Demo\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.add(panel);\n frame.setSize(500, 250);\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n }\n}" } ]
Only Numpy: Implementing Different combination of L1 /L2 norm/regularization to Deep Neural Network (regression) with interactive code | by Jae Duk Seo | Towards Data Science
I was always interested in different kind of cost function, and regularization techniques, so today, I will implement different combination of Loss function with regularization to see which performs the best. We’ll also take a look at absolute sum of each model’s weight to see how small the weights became. L1-norm loss function and L2-norm loss function I think the above explanation is the most simple yet effective explanation of both cost functions. So I won’t add anything more, know lets take a look at regularizes. 1. Making a Simple Neural Network 2. Keras Cheat Sheet: Neural Networks in Python 3. A noob’s guide to implementing RNN-LSTM using Tensorflow L1 regularization and L2 regularization Again the red box from top to bottom represent L1 regularization and L2 regularization. Crispy clear nothing for me to add. However since I have to drive derivative (back propagation) I will touch on something. Derivative of Absolute Function As seen above, derivative of absolute function have three different cases, when X > 1, X < 1 and X = 0. Option 1 → When X > 1, derivative = 1Option 2 → When X = 0, derivative = undefinedOption 3 → When X < 1, derivative = -1 Since we can’t just let the gradient to be ‘undefined’ I BREAK THIS RULE. Above, is the function that I will use to calculate the derivative of value X. And as seen above, I don’t have the second option, we merged that into first option. Initialize Hyper parameters and Weights Above is creating training data and declaring some noise as well as learning rate and the alpha value (these are for regularization). Initialize weights and copy them to each cases. Network Architecture + Forward Feed There is nothing special about the network arch, simply put. Denoted by the red marker below each layer.Layer 1 → 100 NeuronsLayer 2 → 104 NeuronsLayer 3 → 200 NeuronsLayer 4 → 1 Neuron And the weights have appropriate dimension to perform transformation between the layers. However, there are two boxes that I wish to touch upon. Red Box → Identity Activation Function def IDEN(x): return xdef d_IDEN(x): return 1 If implemented in python it would look something like above, very simple linear function. We need this since we are going to perform regression on continuous values. If you want to know why we need activation functions please read my other blog post “Only Numpy: Why we need Activation Function (Non-Linearity), in Deep Neural Network — With Interactive Code” Blue Box → Arctan Sigmoid Function Think of this function as just as tanh() function but with a wider range. I personally believe that we don’t have to stick to logistic sigmoid or tanh. I think there is an whole wide variety of activation functions we need to explore. Anyway if you want the visualized archtan() please see the below image. Cost Function and Regularization Cases As seen above, there are in total of 6 (ignore 7) cases that we can work with. Case 1 → L1 norm lossCase 2 → L2 norm loss Case 3 → L1 norm loss + L1 regularization Case 4 → L2 norm loss + L2 regularizationCase 5 → L1 norm loss + L2 regularizationCase 6 → L2 norm loss + L1 regularization And we will see how each case function differ from one another! Back Propagation (on case 1, 3, and 4) Since, every other cases can be derived from those 3 cases, I won’t do every back propagation process. However, there is one thing that I want you to know. The parts written in red marker are the places where we BREAK THE RULE of taking derivative of absolute function! (Note this!!) Regular Results As expected the network with regularization were most robust to noises. However the model with pure L1 norm function was the least to change, but there is a catch! If you see where the green star is located, we can see that the red regression line’s accuracy falls dramatically. Also, one thing to note is where the blue star lies, most of the model fails to predict the right value of Y at the beginning of X, this was very interesting to me. Know, lets take a look at the absolute sum of the weights. Overall it becomes very clear that the models with the regularization have much smaller weights. Among them L1 cost function with L2 regularization had the smallest weight values. Thinking outside the convention: Results Where and how did I get the above result? Simple, rather than following the strict derivative of absolute function, I loosen up the derivative a bit. See below for the exact difference. As seen above, rather than following the strict rule of derivation, I just adjusted the cost function to be (Layer_4_act — Y)/m. I think when it comes to deep learning, sometimes creativity gives better results, I am not sure but Dr. Hinton did something with randomly decreasing weights in back propagation and still achieving good results. Anyway, lets take a look at the summed absolute value of the weights. Interactive Code — Regular Results Please follow this link to see the result and the code. Interactive Code- Thinking outside the convention: Results Please follow this link to see the result and the code. I saw from other article that there are in total of 7 regularization techniques, so I am just scratching the surface. Can’t wait to know more. If any errors are found, please email me at [email protected]. Meanwhile follow me on my twitter here, and visit my website, or my Youtube channel for more content. I also did deriving back propagation on simple RNN here if you are interested. References Seo, J. D. (2018, January 16). Only Numpy: Why we need Activation Function (Non-Linearity), in Deep Neural Network — With... Retrieved January 20, 2018, from https://medium.com/@SeoJaeDuk/only-numpy-why-we-need-activation-function-non-linearity-in-deep-neural-network-with-529e928820bcInverse Tangent. (n.d.). Retrieved January 20, 2018, from http://mathworld.wolfram.com/InverseTangent.htmlSigmoid function. (2018, January 18). Retrieved January 20, 2018, from https://en.wikipedia.org/wiki/Sigmoid_function(n.d.). Retrieved January 20, 2018, from http://www.chioka.in/differences-between-l1-and-l2-as-loss-function-and-regularization/Finding the Derivative of |x| using the Limit Definition. (n.d.). Retrieved January 20, 2018, from https://math.stackexchange.com/questions/83861/finding-the-derivative-of-x-using-the-limit-definitionRobust linear model estimation using RANSAC¶. (n.d.). Retrieved January 20, 2018, from http://scikit-learn.org/stable/auto_examples/linear_model/plot_ransac.html#sphx-glr-auto-examples-linear-model-plot-ransac-pyJain, A., Shaikh, F., Choudhary, A., Singh, G., & Kaur, P. (2016, February 07). A Complete Tutorial on Ridge and Lasso Regression in Python. Retrieved January 20, 2018, from https://www.analyticsvidhya.com/blog/2016/01/complete-tutorial-ridge-lasso-regression-python/Jerkic, M. (2017, October 30). Build A Multi Layer Neural Network With L2 Regularization Using Tensorflow. Retrieved January 20, 2018, from https://markojerkic.com/build-a-multi-layer-neural-network-with-l2-regularization-with-tensorflow/ Seo, J. D. (2018, January 16). Only Numpy: Why we need Activation Function (Non-Linearity), in Deep Neural Network — With... Retrieved January 20, 2018, from https://medium.com/@SeoJaeDuk/only-numpy-why-we-need-activation-function-non-linearity-in-deep-neural-network-with-529e928820bc Inverse Tangent. (n.d.). Retrieved January 20, 2018, from http://mathworld.wolfram.com/InverseTangent.html Sigmoid function. (2018, January 18). Retrieved January 20, 2018, from https://en.wikipedia.org/wiki/Sigmoid_function (n.d.). Retrieved January 20, 2018, from http://www.chioka.in/differences-between-l1-and-l2-as-loss-function-and-regularization/ Finding the Derivative of |x| using the Limit Definition. (n.d.). Retrieved January 20, 2018, from https://math.stackexchange.com/questions/83861/finding-the-derivative-of-x-using-the-limit-definition Robust linear model estimation using RANSAC¶. (n.d.). Retrieved January 20, 2018, from http://scikit-learn.org/stable/auto_examples/linear_model/plot_ransac.html#sphx-glr-auto-examples-linear-model-plot-ransac-py Jain, A., Shaikh, F., Choudhary, A., Singh, G., & Kaur, P. (2016, February 07). A Complete Tutorial on Ridge and Lasso Regression in Python. Retrieved January 20, 2018, from https://www.analyticsvidhya.com/blog/2016/01/complete-tutorial-ridge-lasso-regression-python/ Jerkic, M. (2017, October 30). Build A Multi Layer Neural Network With L2 Regularization Using Tensorflow. Retrieved January 20, 2018, from https://markojerkic.com/build-a-multi-layer-neural-network-with-l2-regularization-with-tensorflow/
[ { "code": null, "e": 480, "s": 172, "text": "I was always interested in different kind of cost function, and regularization techniques, so today, I will implement different combination of Loss function with regularization to see which performs the best. We’ll also take a look at absolute sum of each model’s weight to see how small the weights became." }, { "code": null, "e": 528, "s": 480, "text": "L1-norm loss function and L2-norm loss function" }, { "code": null, "e": 695, "s": 528, "text": "I think the above explanation is the most simple yet effective explanation of both cost functions. So I won’t add anything more, know lets take a look at regularizes." }, { "code": null, "e": 729, "s": 695, "text": "1. Making a Simple Neural Network" }, { "code": null, "e": 777, "s": 729, "text": "2. Keras Cheat Sheet: Neural Networks in Python" }, { "code": null, "e": 837, "s": 777, "text": "3. A noob’s guide to implementing RNN-LSTM using Tensorflow" }, { "code": null, "e": 877, "s": 837, "text": "L1 regularization and L2 regularization" }, { "code": null, "e": 1088, "s": 877, "text": "Again the red box from top to bottom represent L1 regularization and L2 regularization. Crispy clear nothing for me to add. However since I have to drive derivative (back propagation) I will touch on something." }, { "code": null, "e": 1120, "s": 1088, "text": "Derivative of Absolute Function" }, { "code": null, "e": 1224, "s": 1120, "text": "As seen above, derivative of absolute function have three different cases, when X > 1, X < 1 and X = 0." }, { "code": null, "e": 1345, "s": 1224, "text": "Option 1 → When X > 1, derivative = 1Option 2 → When X = 0, derivative = undefinedOption 3 → When X < 1, derivative = -1" }, { "code": null, "e": 1419, "s": 1345, "text": "Since we can’t just let the gradient to be ‘undefined’ I BREAK THIS RULE." }, { "code": null, "e": 1583, "s": 1419, "text": "Above, is the function that I will use to calculate the derivative of value X. And as seen above, I don’t have the second option, we merged that into first option." }, { "code": null, "e": 1623, "s": 1583, "text": "Initialize Hyper parameters and Weights" }, { "code": null, "e": 1757, "s": 1623, "text": "Above is creating training data and declaring some noise as well as learning rate and the alpha value (these are for regularization)." }, { "code": null, "e": 1805, "s": 1757, "text": "Initialize weights and copy them to each cases." }, { "code": null, "e": 1841, "s": 1805, "text": "Network Architecture + Forward Feed" }, { "code": null, "e": 1902, "s": 1841, "text": "There is nothing special about the network arch, simply put." }, { "code": null, "e": 2027, "s": 1902, "text": "Denoted by the red marker below each layer.Layer 1 → 100 NeuronsLayer 2 → 104 NeuronsLayer 3 → 200 NeuronsLayer 4 → 1 Neuron" }, { "code": null, "e": 2172, "s": 2027, "text": "And the weights have appropriate dimension to perform transformation between the layers. However, there are two boxes that I wish to touch upon." }, { "code": null, "e": 2211, "s": 2172, "text": "Red Box → Identity Activation Function" }, { "code": null, "e": 2262, "s": 2211, "text": "def IDEN(x): return xdef d_IDEN(x): return 1" }, { "code": null, "e": 2622, "s": 2262, "text": "If implemented in python it would look something like above, very simple linear function. We need this since we are going to perform regression on continuous values. If you want to know why we need activation functions please read my other blog post “Only Numpy: Why we need Activation Function (Non-Linearity), in Deep Neural Network — With Interactive Code”" }, { "code": null, "e": 2657, "s": 2622, "text": "Blue Box → Arctan Sigmoid Function" }, { "code": null, "e": 2964, "s": 2657, "text": "Think of this function as just as tanh() function but with a wider range. I personally believe that we don’t have to stick to logistic sigmoid or tanh. I think there is an whole wide variety of activation functions we need to explore. Anyway if you want the visualized archtan() please see the below image." }, { "code": null, "e": 3003, "s": 2964, "text": "Cost Function and Regularization Cases" }, { "code": null, "e": 3082, "s": 3003, "text": "As seen above, there are in total of 6 (ignore 7) cases that we can work with." }, { "code": null, "e": 3291, "s": 3082, "text": "Case 1 → L1 norm lossCase 2 → L2 norm loss Case 3 → L1 norm loss + L1 regularization Case 4 → L2 norm loss + L2 regularizationCase 5 → L1 norm loss + L2 regularizationCase 6 → L2 norm loss + L1 regularization" }, { "code": null, "e": 3355, "s": 3291, "text": "And we will see how each case function differ from one another!" }, { "code": null, "e": 3394, "s": 3355, "text": "Back Propagation (on case 1, 3, and 4)" }, { "code": null, "e": 3678, "s": 3394, "text": "Since, every other cases can be derived from those 3 cases, I won’t do every back propagation process. However, there is one thing that I want you to know. The parts written in red marker are the places where we BREAK THE RULE of taking derivative of absolute function! (Note this!!)" }, { "code": null, "e": 3694, "s": 3678, "text": "Regular Results" }, { "code": null, "e": 3973, "s": 3694, "text": "As expected the network with regularization were most robust to noises. However the model with pure L1 norm function was the least to change, but there is a catch! If you see where the green star is located, we can see that the red regression line’s accuracy falls dramatically." }, { "code": null, "e": 4197, "s": 3973, "text": "Also, one thing to note is where the blue star lies, most of the model fails to predict the right value of Y at the beginning of X, this was very interesting to me. Know, lets take a look at the absolute sum of the weights." }, { "code": null, "e": 4377, "s": 4197, "text": "Overall it becomes very clear that the models with the regularization have much smaller weights. Among them L1 cost function with L2 regularization had the smallest weight values." }, { "code": null, "e": 4418, "s": 4377, "text": "Thinking outside the convention: Results" }, { "code": null, "e": 4604, "s": 4418, "text": "Where and how did I get the above result? Simple, rather than following the strict derivative of absolute function, I loosen up the derivative a bit. See below for the exact difference." }, { "code": null, "e": 4733, "s": 4604, "text": "As seen above, rather than following the strict rule of derivation, I just adjusted the cost function to be (Layer_4_act — Y)/m." }, { "code": null, "e": 5016, "s": 4733, "text": "I think when it comes to deep learning, sometimes creativity gives better results, I am not sure but Dr. Hinton did something with randomly decreasing weights in back propagation and still achieving good results. Anyway, lets take a look at the summed absolute value of the weights." }, { "code": null, "e": 5051, "s": 5016, "text": "Interactive Code — Regular Results" }, { "code": null, "e": 5107, "s": 5051, "text": "Please follow this link to see the result and the code." }, { "code": null, "e": 5166, "s": 5107, "text": "Interactive Code- Thinking outside the convention: Results" }, { "code": null, "e": 5222, "s": 5166, "text": "Please follow this link to see the result and the code." }, { "code": null, "e": 5365, "s": 5222, "text": "I saw from other article that there are in total of 7 regularization techniques, so I am just scratching the surface. Can’t wait to know more." }, { "code": null, "e": 5432, "s": 5365, "text": "If any errors are found, please email me at [email protected]." }, { "code": null, "e": 5613, "s": 5432, "text": "Meanwhile follow me on my twitter here, and visit my website, or my Youtube channel for more content. I also did deriving back propagation on simple RNN here if you are interested." }, { "code": null, "e": 5624, "s": 5613, "text": "References" }, { "code": null, "e": 7178, "s": 5624, "text": "Seo, J. D. (2018, January 16). Only Numpy: Why we need Activation Function (Non-Linearity), in Deep Neural Network — With... Retrieved January 20, 2018, from https://medium.com/@SeoJaeDuk/only-numpy-why-we-need-activation-function-non-linearity-in-deep-neural-network-with-529e928820bcInverse Tangent. (n.d.). Retrieved January 20, 2018, from http://mathworld.wolfram.com/InverseTangent.htmlSigmoid function. (2018, January 18). Retrieved January 20, 2018, from https://en.wikipedia.org/wiki/Sigmoid_function(n.d.). Retrieved January 20, 2018, from http://www.chioka.in/differences-between-l1-and-l2-as-loss-function-and-regularization/Finding the Derivative of |x| using the Limit Definition. (n.d.). Retrieved January 20, 2018, from https://math.stackexchange.com/questions/83861/finding-the-derivative-of-x-using-the-limit-definitionRobust linear model estimation using RANSAC¶. (n.d.). Retrieved January 20, 2018, from http://scikit-learn.org/stable/auto_examples/linear_model/plot_ransac.html#sphx-glr-auto-examples-linear-model-plot-ransac-pyJain, A., Shaikh, F., Choudhary, A., Singh, G., & Kaur, P. (2016, February 07). A Complete Tutorial on Ridge and Lasso Regression in Python. Retrieved January 20, 2018, from https://www.analyticsvidhya.com/blog/2016/01/complete-tutorial-ridge-lasso-regression-python/Jerkic, M. (2017, October 30). Build A Multi Layer Neural Network With L2 Regularization Using Tensorflow. Retrieved January 20, 2018, from https://markojerkic.com/build-a-multi-layer-neural-network-with-l2-regularization-with-tensorflow/" }, { "code": null, "e": 7464, "s": 7178, "text": "Seo, J. D. (2018, January 16). Only Numpy: Why we need Activation Function (Non-Linearity), in Deep Neural Network — With... Retrieved January 20, 2018, from https://medium.com/@SeoJaeDuk/only-numpy-why-we-need-activation-function-non-linearity-in-deep-neural-network-with-529e928820bc" }, { "code": null, "e": 7571, "s": 7464, "text": "Inverse Tangent. (n.d.). Retrieved January 20, 2018, from http://mathworld.wolfram.com/InverseTangent.html" }, { "code": null, "e": 7689, "s": 7571, "text": "Sigmoid function. (2018, January 18). Retrieved January 20, 2018, from https://en.wikipedia.org/wiki/Sigmoid_function" }, { "code": null, "e": 7818, "s": 7689, "text": "(n.d.). Retrieved January 20, 2018, from http://www.chioka.in/differences-between-l1-and-l2-as-loss-function-and-regularization/" }, { "code": null, "e": 8019, "s": 7818, "text": "Finding the Derivative of |x| using the Limit Definition. (n.d.). Retrieved January 20, 2018, from https://math.stackexchange.com/questions/83861/finding-the-derivative-of-x-using-the-limit-definition" }, { "code": null, "e": 8232, "s": 8019, "text": "Robust linear model estimation using RANSAC¶. (n.d.). Retrieved January 20, 2018, from http://scikit-learn.org/stable/auto_examples/linear_model/plot_ransac.html#sphx-glr-auto-examples-linear-model-plot-ransac-py" }, { "code": null, "e": 8500, "s": 8232, "text": "Jain, A., Shaikh, F., Choudhary, A., Singh, G., & Kaur, P. (2016, February 07). A Complete Tutorial on Ridge and Lasso Regression in Python. Retrieved January 20, 2018, from https://www.analyticsvidhya.com/blog/2016/01/complete-tutorial-ridge-lasso-regression-python/" } ]
Ways to arrange Balls such that adjacent balls are of different types - GeeksforGeeks
07 Jul, 2021 There are ‘p’ balls of type P, ‘q’ balls of type Q and ‘r’ balls of type R. Using the balls we want to create a straight line such that no two balls of same type are adjacent.Examples : Input : p = 1, q = 1, r = 0 Output : 2 There are only two arrangements PQ and QP Input : p = 1, q = 1, r = 1 Output : 6 There are only six arrangements PQR, QPR, QRP, RQP, PRQ and RPQ Input : p = 2, q = 1, r = 1 Output : 6 There are only six arrangements PQRP, QPRP, PRQP, RPQP, PRPQ and PQPR Naive Solution: The naive solution to this problem is a recursive solution. We recursively call for three cases 1) Last ball to be placed is of type P 2) Last ball to be placed is of type Q 3) Last ball to be placed is of type RBelow is the implementation of above idea. C++ Java Python3 C# PHP Javascript // C++ program to count number of ways to arrange three// types of balls such that no two balls of same color// are adjacent to each other#include<bits/stdc++.h>using namespace std; // Returns count of arrangements where last placed ball is// 'last'. 'last' is 0 for 'p', 1 for 'q' and 2 for 'r'int countWays(int p, int q, int r, int last){ // if number of balls of any color becomes less // than 0 the number of ways arrangements is 0. if (p<0 || q<0 || r<0) return 0; // If last ball required is of type P and the number // of balls of P type is 1 while number of balls of // other color is 0 the number of ways is 1. if (p==1 && q==0 && r==0 && last==0) return 1; // Same case as above for 'q' and 'r' if (p==0 && q==1 && r==0 && last==1) return 1; if (p==0 && q==0 && r==1 && last==2) return 1; // if last ball required is P and the number of ways is // the sum of number of ways to form sequence with 'p-1' P // balls, q Q Balls and r R balls ending with Q and R. if (last==0) return countWays(p-1,q,r,1) + countWays(p-1,q,r,2); // Same as above case for 'q' and 'r' if (last==1) return countWays(p,q-1,r,0) + countWays(p,q-1,r,2); if (last==2) return countWays(p,q,r-1,0) + countWays(p,q,r-1,1);} // Returns count of required arrangementsint countUtil(int p, int q, int r){ // Three cases arise: return countWays(p, q, r, 0) + // Last required balls is type P countWays(p, q, r, 1) + // Last required balls is type Q countWays(p, q, r, 2); // Last required balls is type R} // Driver code to test aboveint main(){ int p = 1, q = 1, r = 1; printf("%d", countUtil(p, q, r)); return 0;} // Java program to count number// of ways to arrange three types of// balls such that no two balls of// same color are adjacent to each otherclass GFG { // Returns count of arrangements // where last placed ball is // 'last'. 'last' is 0 for 'p', // 1 for 'q' and 2 for 'r' static int countWays(int p, int q, int r, int last) { // if number of balls of any // color becomes less than 0 // the number of ways arrangements is 0. if (p < 0 || q < 0 || r < 0) return 0; // If last ball required is // of type P and the number // of balls of P type is 1 // while number of balls of // other color is 0 the number // of ways is 1. if (p == 1 && q == 0 && r == 0 && last == 0) return 1; // Same case as above for 'q' and 'r' if (p == 0 && q == 1 && r == 0 && last == 1) return 1; if (p == 0 && q == 0 && r == 1 && last == 2) return 1; // if last ball required is P // and the number of ways is // the sum of number of ways // to form sequence with 'p-1' P // balls, q Q Balls and r R balls // ending with Q and R. if (last == 0) return countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2); // Same as above case for 'q' and 'r' if (last == 1) return countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2); if (last == 2) return countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1); return 0; } // Returns count of required arrangements static int countUtil(int p, int q, int r) { // Three cases arise: return countWays(p, q, r, 0) + // Last required balls is type P countWays(p, q, r, 1) + // Last required balls is type Q countWays(p, q, r, 2); // Last required balls is type R } // Driver code public static void main(String[] args) { int p = 1, q = 1, r = 1; System.out.print(countUtil(p, q, r)); }} // This code is contributed by Anant Agarwal. # Python3 program to count# number of ways to arrange# three types of balls such # that no two balls of same# color are adjacent to each# other # Returns count of arrangements# where last placed ball is# 'last'. 'last' is 0 for 'p',# 1 for 'q' and 2 for 'r'def countWays(p, q, r, last): # if number of balls of # any color becomes less # than 0 the number of # ways arrangements is 0. if (p < 0 or q < 0 or r < 0): return 0; # If last ball required is # of type P and the number # of balls of P type is 1 # while number of balls of # other color is 0 the number # of ways is 1. if (p == 1 and q == 0 and r == 0 and last == 0): return 1; # Same case as above # for 'q' and 'r' if (p == 0 and q == 1 and r == 0 and last == 1): return 1; if (p == 0 and q == 0 and r == 1 and last == 2): return 1; # if last ball required is P # and the number of ways is # the sum of number of ways # to form sequence with 'p-1' P # balls, q Q Balls and r R # balls ending with Q and R. if (last == 0): return (countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2)); # Same as above case # for 'q' and 'r' if (last == 1): return (countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2)); if (last == 2): return (countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1)); # Returns count of# required arrangementsdef countUtil(p, q, r): # Three cases arise: # Last required balls is type P # Last required balls is type Q # Last required balls is type R return (countWays(p, q, r, 0) + countWays(p, q, r, 1) + countWays(p, q, r, 2)); # Driver Codep = 1;q = 1;r = 1;print(countUtil(p, q, r)); # This code is contributed by mits // C# program to count number// of ways to arrange three types of// balls such that no two balls of// same color are adjacent to each otherusing System; class GFG { // Returns count of arrangements // where last placed ball is // 'last'. 'last' is 0 for 'p', // 1 for 'q' and 2 for 'r' static int countWays(int p, int q, int r, int last) { // if number of balls of any // color becomes less than 0 // the number of ways // arrangements is 0. if (p < 0 || q < 0 || r < 0) return 0; // If last ball required is // of type P and the number // of balls of P type is 1 // while number of balls of // other color is 0 the number // of ways is 1. if (p == 1 && q == 0 && r == 0 && last == 0) return 1; // Same case as above for 'q' and 'r' if (p == 0 && q == 1 && r == 0 && last == 1) return 1; if (p == 0 && q == 0 && r == 1 && last == 2) return 1; // if last ball required is P // and the number of ways is // the sum of number of ways // to form sequence with 'p-1' P // balls, q Q Balls and r R balls // ending with Q and R. if (last == 0) return countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2); // Same as above case for 'q' and 'r' if (last == 1) return countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2); if (last == 2) return countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1); return 0; } // Returns count of required arrangements static int countUtil(int p, int q, int r) { // Three cases arise: // 1. Last required balls is type P // 2. Last required balls is type Q // 3. Last required balls is type R return countWays(p, q, r, 0) + countWays(p, q, r, 1) + countWays(p, q, r, 2); } // Driver code public static void Main() { int p = 1, q = 1, r = 1; Console.Write(countUtil(p, q, r)); }} // This code is contributed by nitin mittal. <?php// PHP program to count number// of ways to arrange three// types of balls such that// no two balls of same color// are adjacent to each other // Returns count of arrangements// where last placed ball is// 'last'. 'last' is 0 for 'p',// 1 for 'q' and 2 for 'r'function countWays($p, $q, $r, $last){ // if number of balls of // any color becomes less // than 0 the number of // ways arrangements is 0. if ($p < 0 || $q < 0 || $r < 0) return 0; // If last ball required is // of type P and the number // of balls of P type is 1 // while number of balls of // other color is 0 the number // of ways is 1. if ($p == 1 && $q == 0 && $r == 0 && $last == 0) return 1; // Same case as above // for 'q' and 'r' if ($p == 0 && $q == 1 && $r == 0 && $last == 1) return 1; if ($p == 0 && $q == 0 && $r == 1 && $last == 2) return 1; // if last ball required is P // and the number of ways is // the sum of number of ways // to form sequence with 'p-1' P // balls, q Q Balls and r R // balls ending with Q and R. if ($last == 0) return countWays($p - 1, $q, $r, 1) + countWays($p - 1, $q, $r, 2); // Same as above case // for 'q' and 'r' if ($last == 1) return countWays($p, $q - 1, $r, 0) + countWays($p, $q - 1, $r, 2); if ($last == 2) return countWays($p, $q, $r - 1, 0) + countWays($p, $q, $r - 1, 1);} // Returns count of// required arrangementsfunction countUtil($p, $q, $r){ // Three cases arise: // Last required balls is type P // Last required balls is type Q // Last required balls is type R return countWays($p, $q, $r, 0) + countWays($p, $q, $r, 1) + countWays($p, $q, $r, 2);} // Driver Code $p = 1; $q = 1; $r = 1; echo(countUtil($p, $q, $r)); // This code is contributed by nitin mittal.?> <script> // JavaScript program to count number// of ways to arrange three// types of balls such that no// two balls of same color// are adjacent to each other // Returns count of arrangements // where last placed ball is // 'last'. 'last' is 0 for 'p', // 1 for 'q' and 2 for 'r' function countWays(p, q, r, last) { // if number of balls of any // color becomes less than 0 // the number of ways arrangements is 0. if (p < 0 || q < 0 || r < 0) return 0; // If last ball required is // of type P and the number // of balls of P type is 1 // while number of balls of // other color is 0 the number // of ways is 1. if (p == 1 && q == 0 && r == 0 && last == 0) return 1; // Same case as above for 'q' and 'r' if (p == 0 && q == 1 && r == 0 && last == 1) return 1; if (p == 0 && q == 0 && r == 1 && last == 2) return 1; // if last ball required is P // and the number of ways is // the sum of number of ways // to form sequence with 'p-1' P // balls, q Q Balls and r R balls // ending with Q and R. if (last == 0) return countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2); // Same as above case for 'q' and 'r' if (last == 1) return countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2); if (last == 2) return countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1); return 0; } // Returns count of required arrangements function countUtil(p, q, r) { // Three cases arise: return countWays(p, q, r, 0) + // Last required balls is type P countWays(p, q, r, 1) + // Last required balls is type Q countWays(p, q, r, 2); // Last required balls is type R } // Driver Code let p = 1, q = 1, r = 1; document.write(countUtil(p, q, r)); // This code is contributed by target_2.</script> Output: 6 Time Complexity of this solution is exponential.We can observe that there are many subproblems being solved again and again so the problem can be solved using Dynamic Programming (DP). We can easily make memoization solution to this problem. C++ Java C# Python3 PHP Javascript // C++ program to count number of ways to arrange three// types of balls such that no two balls of same color// are adjacent to each other#include<bits/stdc++.h>using namespace std;#define MAX 100 // table to store to store results of subproblemsint dp[MAX][MAX][MAX][3]; // Returns count of arrangements where last placed ball is// 'last'. 'last' is 0 for 'p', 1 for 'q' and 2 for 'r'int countWays(int p, int q, int r, int last){ // if number of balls of any color becomes less // than 0 the number of ways arrangements is 0. if (p<0 || q<0 || r<0) return 0; // If last ball required is of type P and the number // of balls of P type is 1 while number of balls of // other color is 0 the number of ways is 1. if (p==1 && q==0 && r==0 && last==0) return 1; // Same case as above for 'q' and 'r' if (p==0 && q==1 && r==0 && last==1) return 1; if (p==0 && q==0 && r==1 && last==2) return 1; // If this subproblem is already evaluated if (dp[p][q][r][last] != -1) return dp[p][q][r][last]; // if last ball required is P and the number of ways is // the sum of number of ways to form sequence with 'p-1' P // balls, q Q Balls and r R balls ending with Q and R. if (last==0) dp[p][q][r][last] = countWays(p-1,q,r,1) + countWays(p-1,q,r,2); // Same as above case for 'q' and 'r' else if (last==1) dp[p][q][r][last] = countWays(p,q-1,r,0) + countWays(p,q-1,r,2); else //(last==2) dp[p][q][r][last] = countWays(p,q,r-1,0) + countWays(p,q,r-1,1); return dp[p][q][r][last];} // Returns count of required arrangementsint countUtil(int p, int q, int r){ // Initialize 'dp' array memset(dp, -1, sizeof(dp)); // Three cases arise: return countWays(p, q, r, 0) + // Last required balls is type P countWays(p, q, r, 1) + // Last required balls is type Q countWays(p, q, r, 2); // Last required balls is type R} // Driver code to test aboveint main(){ int p = 1, q = 1, r = 1; printf("%d", countUtil(p, q, r)); return 0;} // Java program to count number// of ways to arrange three// types of balls such that no// two balls of same color// are adjacent to each otherimport java.util.Arrays; class GFG{ static final int MAX = 100; // table to store to store results of subproblems static int dp[][][][] = new int[MAX][MAX][MAX][3]; // Returns count of arrangements // where last placed ball is // 'last'. 'last' is 0 for 'p', // 1 for 'q' and 2 for 'r' static int countWays(int p, int q, int r, int last) { // if number of balls of any // color becomes less than 0 // the number of ways arrangements is 0. if (p < 0 || q < 0 || r < 0) return 0; // If last ball required is // of type P and the number // of balls of P type is 1 // while number of balls of // other color is 0 the number // of ways is 1. if (p == 1 && q == 0 && r == 0 && last == 0) return 1; // Same case as above for 'q' and 'r' if (p == 0 && q == 1 && r == 0 && last == 1) return 1; if (p == 0 && q == 0 && r == 1 && last == 2) return 1; // If this subproblem is already evaluated if (dp[p][q][r][last] != -1) return dp[p][q][r][last]; // if last ball required is P and // the number of ways is the sum // of number of ways to form sequence // with 'p-1' P balls, q Q balss and // r R balls ending with Q and R. if (last == 0) dp[p][q][r][last] = countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2); // Same as above case for 'q' and 'r' else if (last == 1) dp[p][q][r][last] = countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2); //(last==2) else dp[p][q][r][last] = countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1); return dp[p][q][r][last]; } // Returns count of required arrangements static int countUtil(int p, int q, int r) { // Initialize 'dp' array for (int[][][] row : dp) { for (int[][] innerRow : row) { for (int[] innerInnerRow : innerRow) { Arrays.fill(innerInnerRow, -1); } } }; // Three cases arise: return countWays(p, q, r, 0) + // Last required balls is type P countWays(p, q, r, 1) + // Last required balls is type Q countWays(p, q, r, 2); // Last required balls is type R } // Driver code public static void main(String[] args) { int p = 1, q = 1, r = 1; System.out.print(countUtil(p, q, r)); }} // This code is contributed by Anant Agarwal. // C# program to count number// of ways to arrange three// types of balls such that no// two balls of same color// are adjacent to each otherusing System; class GFG{ static int MAX = 101; // table to store to store results of subproblems static int[,,,] dp = new int[MAX, MAX, MAX, 4]; // Returns count of arrangements // where last placed ball is // 'last'. 'last' is 0 for 'p', // 1 for 'q' and 2 for 'r' static int countWays(int p, int q, int r, int last) { // if number of balls of any // color becomes less than 0 // the number of ways arrangements is 0. if (p < 0 || q < 0 || r < 0) return 0; // If last ball required is // of type P and the number // of balls of P type is 1 // while number of balls of // other color is 0 the number // of ways is 1. if (p == 1 && q == 0 && r == 0 && last == 0) return 1; // Same case as above for 'q' and 'r' if (p == 0 && q == 1 && r == 0 && last == 1) return 1; if (p == 0 && q == 0 && r == 1 && last == 2) return 1; // If this subproblem is already evaluated if (dp[p, q, r, last] != -1) return dp[p, q, r, last]; // if last ball required is P and // the number of ways is the sum // of number of ways to form sequence // with 'p-1' P balls, q Q balss and // r R balls ending with Q and R. if (last == 0) dp[p, q, r, last] = countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2); // Same as above case for 'q' and 'r' else if (last == 1) dp[p, q, r, last] = countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2); //(last==2) else dp[p, q, r, last] = countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1); return dp[p, q, r, last]; } // Returns count of required arrangements static int countUtil(int p, int q, int r) { // Initialize 'dp' array for(int i = 0; i < MAX; i++) for(int j = 0; j < MAX; j++) for(int k = 0; k < MAX; k++) for(int l = 0; l < 4; l++) dp[i, j, k, l] = -1; // Three cases arise: return countWays(p, q, r, 0) + // Last required balls is type P countWays(p, q, r, 1) + // Last required balls is type Q countWays(p, q, r, 2); // Last required balls is type R } // Driver code static void Main() { int p = 1, q = 1, r = 1; Console.WriteLine(countUtil(p, q, r)); }} // This code is contributed by mits. # Python3 program to count number of ways to# arrange three types of balls such that no# two balls of same color are adjacent to each otherMAX = 100; # table to store to store results of subproblemsdp = [[[[-1] * 4 for i in range(MAX)] for j in range(MAX)] for k in range(MAX)]; # Returns count of arrangements where last# placed ball is 'last'. 'last' is 0 for 'p',# 1 for 'q' and 2 for 'r'def countWays(p, q, r, last): # if number of balls of any color becomes less # than 0 the number of ways arrangements is 0. if (p < 0 or q < 0 or r < 0): return 0; # If last ball required is of type P and the # number of balls of P type is 1 while number # of balls of other color is 0 the number of # ways is 1. if (p == 1 and q == 0 and r == 0 and last == 0): return 1; # Same case as above for 'q' and 'r' if (p == 0 and q == 1 and r == 0 and last == 1): return 1; if (p == 0 and q == 0 and r == 1 and last == 2): return 1; # If this subproblem is already evaluated if (dp[p][q][r][last] != -1): return dp[p][q][r][last]; # if last ball required is P and the number # of ways is the sum of number of ways to # form sequence with 'p-1' P balls, q Q Balls # and r R balls ending with Q and R. if (last == 0): dp[p][q][r][last] = (countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2)); # Same as above case for 'q' and 'r' elif (last == 1): dp[p][q][r][last] = (countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2)); else: #(last==2) dp[p][q][r][last] = (countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1)); return dp[p][q][r][last]; # Returns count of required arrangementsdef countUtil(p, q, r): # Three cases arise: # Last required balls is type P # Last required balls is type Q # Last required balls is type R return (countWays(p, q, r, 0) + countWays(p, q, r, 1) + countWays(p, q, r, 2)); # Driver Codep, q, r = 1, 1, 1;print(countUtil(p, q, r)); # This code is contributed by mits <?php// PHP program to count number of ways to// arrange three types of balls such that// no two balls of same color are adjacent// to each other$MAX = 100; // table to store to store results of subproblems$dp = array_fill(0, $MAX, array_fill(0, $MAX, array_fill(0, $MAX, array_fill(0, 3, -1)))); // Returns count of arrangements where last// placed ball is 'last'. 'last' is 0 for 'p',// 1 for 'q' and 2 for 'r'function countWays($p, $q, $r, $last){ global $dp; // if number of balls of any color becomes less // than 0 the number of ways arrangements is 0. if ($p < 0 || $q < 0 || $r < 0) return 0; // If last ball required is of type P and the // number of balls of P type is 1 while number // of balls of other color is 0 the number of // ways is 1. if ($p == 1 && $q == 0 && $r == 0 && $last == 0) return 1; // Same case as above for 'q' and 'r' if ($p == 0 && $q == 1 && $r == 0 && $last == 1) return 1; if ($p == 0 && $q == 0 && $r == 1 && $last == 2) return 1; // If this subproblem is already evaluated if ($dp[$p][$q][$r][$last] != -1) return $dp[$p][$q][$r][$last]; // if last ball required is P and the number of // ways is the sum of number of ways to form // sequence with 'p-1' P balls, q Q Balls and r // R balls ending with Q and R. if ($last == 0) $dp[$p][$q][$r][$last] = countWays($p - 1, $q, $r, 1) + countWays($p - 1, $q, $r, 2); // Same as above case for 'q' and 'r' else if ($last == 1) $dp[$p][$q][$r][$last] = countWays($p, $q - 1, $r, 0) + countWays($p, $q - 1, $r, 2); else //(last==2) $dp[$p][$q][$r][$last] = countWays($p, $q, $r - 1, 0) + countWays($p, $q, $r - 1, 1); return $dp[$p][$q][$r][$last];} // Returns count of required arrangementsfunction countUtil($p, $q, $r){ // Three cases arise:return countWays($p, $q, $r, 0) + // Last required balls is type P countWays($p, $q, $r, 1) + // Last required balls is type Q countWays($p, $q, $r, 2); // Last required balls is type R} // Driver code$p = 1;$q = 1;$r = 1;print(countUtil($p, $q, $r)); // This code is contributed by mits?> <script> // javascript program to count number// of ways to arrange three// types of balls such that no// two balls of same color// are adjacent to each other var MAX = 100; // table to store to store results of subproblemsvar dp = Array(MAX).fill(-1).map(x =>Array(MAX).fill(-1).map(x =>Array(MAX).fill(-1).map(x => Array(3).fill(-1)))); // Returns count of arrangements// where last placed ball is// 'last'. 'last' is 0 for 'p',// 1 for 'q' and 2 for 'r'function countWays( p , q , r , last){ // if number of balls of any // color becomes less than 0 // the number of ways arrangements is 0. if (p < 0 || q < 0 || r < 0) return 0; // If last ball required is // of type P and the number // of balls of P type is 1 // while number of balls of // other color is 0 the number // of ways is 1. if (p == 1 && q == 0 && r == 0 && last == 0) return 1; // Same case as above for 'q' and 'r' if (p == 0 && q == 1 && r == 0 && last == 1) return 1; if (p == 0 && q == 0 && r == 1 && last == 2) return 1; // If this subproblem is already evaluated if (dp[p][q][r][last] != -1) return dp[p][q][r][last]; // if last ball required is P and // the number of ways is the sum // of number of ways to form sequence // with 'p-1' P balls, q Q balss and // r R balls ending with Q and R. if (last == 0) dp[p][q][r][last] = countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2); // Same as above case for 'q' and 'r' else if (last == 1) dp[p][q][r][last] = countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2); //(last==2) else dp[p][q][r][last] = countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1); return dp[p][q][r][last];} // Returns count of required arrangementsfunction countUtil(p , q , r){ // Three cases arise: return countWays(p, q, r, 0) + // Last required balls is type P countWays(p, q, r, 1) + // Last required balls is type Q countWays(p, q, r, 2); // Last required balls is type R} // Driver codevar p = 1, q = 1, r = 1;document.write(countUtil(p, q, r)); // This code contributed by Princi Singh</script> Output: 6 Time complexity : O(p*q*r) Auxiliary Space : O(p*q*r*3)This article is contributed by Bhavuk Chawla. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. 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. nitin mittal Mithun Kumar target_2 princi singh Dynamic Programming Mathematical Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Overlapping Subproblems Property in Dynamic Programming | DP-1 Edit Distance | DP-5 Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Program to find GCD or HCF of two numbers
[ { "code": null, "e": 24839, "s": 24811, "text": "\n07 Jul, 2021" }, { "code": null, "e": 25026, "s": 24839, "text": "There are ‘p’ balls of type P, ‘q’ balls of type Q and ‘r’ balls of type R. Using the balls we want to create a straight line such that no two balls of same type are adjacent.Examples : " }, { "code": null, "e": 25324, "s": 25026, "text": "Input : p = 1, q = 1, r = 0\nOutput : 2\nThere are only two arrangements PQ and QP\n\nInput : p = 1, q = 1, r = 1\nOutput : 6\nThere are only six arrangements PQR, QPR,\nQRP, RQP, PRQ and RPQ\n\nInput : p = 2, q = 1, r = 1\nOutput : 6\nThere are only six arrangements PQRP, QPRP,\nPRQP, RPQP, PRPQ and PQPR" }, { "code": null, "e": 25599, "s": 25326, "text": "Naive Solution: The naive solution to this problem is a recursive solution. We recursively call for three cases 1) Last ball to be placed is of type P 2) Last ball to be placed is of type Q 3) Last ball to be placed is of type RBelow is the implementation of above idea. " }, { "code": null, "e": 25603, "s": 25599, "text": "C++" }, { "code": null, "e": 25608, "s": 25603, "text": "Java" }, { "code": null, "e": 25616, "s": 25608, "text": "Python3" }, { "code": null, "e": 25619, "s": 25616, "text": "C#" }, { "code": null, "e": 25623, "s": 25619, "text": "PHP" }, { "code": null, "e": 25634, "s": 25623, "text": "Javascript" }, { "code": "// C++ program to count number of ways to arrange three// types of balls such that no two balls of same color// are adjacent to each other#include<bits/stdc++.h>using namespace std; // Returns count of arrangements where last placed ball is// 'last'. 'last' is 0 for 'p', 1 for 'q' and 2 for 'r'int countWays(int p, int q, int r, int last){ // if number of balls of any color becomes less // than 0 the number of ways arrangements is 0. if (p<0 || q<0 || r<0) return 0; // If last ball required is of type P and the number // of balls of P type is 1 while number of balls of // other color is 0 the number of ways is 1. if (p==1 && q==0 && r==0 && last==0) return 1; // Same case as above for 'q' and 'r' if (p==0 && q==1 && r==0 && last==1) return 1; if (p==0 && q==0 && r==1 && last==2) return 1; // if last ball required is P and the number of ways is // the sum of number of ways to form sequence with 'p-1' P // balls, q Q Balls and r R balls ending with Q and R. if (last==0) return countWays(p-1,q,r,1) + countWays(p-1,q,r,2); // Same as above case for 'q' and 'r' if (last==1) return countWays(p,q-1,r,0) + countWays(p,q-1,r,2); if (last==2) return countWays(p,q,r-1,0) + countWays(p,q,r-1,1);} // Returns count of required arrangementsint countUtil(int p, int q, int r){ // Three cases arise: return countWays(p, q, r, 0) + // Last required balls is type P countWays(p, q, r, 1) + // Last required balls is type Q countWays(p, q, r, 2); // Last required balls is type R} // Driver code to test aboveint main(){ int p = 1, q = 1, r = 1; printf(\"%d\", countUtil(p, q, r)); return 0;}", "e": 27362, "s": 25634, "text": null }, { "code": "// Java program to count number// of ways to arrange three types of// balls such that no two balls of// same color are adjacent to each otherclass GFG { // Returns count of arrangements // where last placed ball is // 'last'. 'last' is 0 for 'p', // 1 for 'q' and 2 for 'r' static int countWays(int p, int q, int r, int last) { // if number of balls of any // color becomes less than 0 // the number of ways arrangements is 0. if (p < 0 || q < 0 || r < 0) return 0; // If last ball required is // of type P and the number // of balls of P type is 1 // while number of balls of // other color is 0 the number // of ways is 1. if (p == 1 && q == 0 && r == 0 && last == 0) return 1; // Same case as above for 'q' and 'r' if (p == 0 && q == 1 && r == 0 && last == 1) return 1; if (p == 0 && q == 0 && r == 1 && last == 2) return 1; // if last ball required is P // and the number of ways is // the sum of number of ways // to form sequence with 'p-1' P // balls, q Q Balls and r R balls // ending with Q and R. if (last == 0) return countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2); // Same as above case for 'q' and 'r' if (last == 1) return countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2); if (last == 2) return countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1); return 0; } // Returns count of required arrangements static int countUtil(int p, int q, int r) { // Three cases arise: return countWays(p, q, r, 0) + // Last required balls is type P countWays(p, q, r, 1) + // Last required balls is type Q countWays(p, q, r, 2); // Last required balls is type R } // Driver code public static void main(String[] args) { int p = 1, q = 1, r = 1; System.out.print(countUtil(p, q, r)); }} // This code is contributed by Anant Agarwal.", "e": 29539, "s": 27362, "text": null }, { "code": "# Python3 program to count# number of ways to arrange# three types of balls such # that no two balls of same# color are adjacent to each# other # Returns count of arrangements# where last placed ball is# 'last'. 'last' is 0 for 'p',# 1 for 'q' and 2 for 'r'def countWays(p, q, r, last): # if number of balls of # any color becomes less # than 0 the number of # ways arrangements is 0. if (p < 0 or q < 0 or r < 0): return 0; # If last ball required is # of type P and the number # of balls of P type is 1 # while number of balls of # other color is 0 the number # of ways is 1. if (p == 1 and q == 0 and r == 0 and last == 0): return 1; # Same case as above # for 'q' and 'r' if (p == 0 and q == 1 and r == 0 and last == 1): return 1; if (p == 0 and q == 0 and r == 1 and last == 2): return 1; # if last ball required is P # and the number of ways is # the sum of number of ways # to form sequence with 'p-1' P # balls, q Q Balls and r R # balls ending with Q and R. if (last == 0): return (countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2)); # Same as above case # for 'q' and 'r' if (last == 1): return (countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2)); if (last == 2): return (countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1)); # Returns count of# required arrangementsdef countUtil(p, q, r): # Three cases arise: # Last required balls is type P # Last required balls is type Q # Last required balls is type R return (countWays(p, q, r, 0) + countWays(p, q, r, 1) + countWays(p, q, r, 2)); # Driver Codep = 1;q = 1;r = 1;print(countUtil(p, q, r)); # This code is contributed by mits", "e": 31400, "s": 29539, "text": null }, { "code": "// C# program to count number// of ways to arrange three types of// balls such that no two balls of// same color are adjacent to each otherusing System; class GFG { // Returns count of arrangements // where last placed ball is // 'last'. 'last' is 0 for 'p', // 1 for 'q' and 2 for 'r' static int countWays(int p, int q, int r, int last) { // if number of balls of any // color becomes less than 0 // the number of ways // arrangements is 0. if (p < 0 || q < 0 || r < 0) return 0; // If last ball required is // of type P and the number // of balls of P type is 1 // while number of balls of // other color is 0 the number // of ways is 1. if (p == 1 && q == 0 && r == 0 && last == 0) return 1; // Same case as above for 'q' and 'r' if (p == 0 && q == 1 && r == 0 && last == 1) return 1; if (p == 0 && q == 0 && r == 1 && last == 2) return 1; // if last ball required is P // and the number of ways is // the sum of number of ways // to form sequence with 'p-1' P // balls, q Q Balls and r R balls // ending with Q and R. if (last == 0) return countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2); // Same as above case for 'q' and 'r' if (last == 1) return countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2); if (last == 2) return countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1); return 0; } // Returns count of required arrangements static int countUtil(int p, int q, int r) { // Three cases arise: // 1. Last required balls is type P // 2. Last required balls is type Q // 3. Last required balls is type R return countWays(p, q, r, 0) + countWays(p, q, r, 1) + countWays(p, q, r, 2); } // Driver code public static void Main() { int p = 1, q = 1, r = 1; Console.Write(countUtil(p, q, r)); }} // This code is contributed by nitin mittal.", "e": 33776, "s": 31400, "text": null }, { "code": "<?php// PHP program to count number// of ways to arrange three// types of balls such that// no two balls of same color// are adjacent to each other // Returns count of arrangements// where last placed ball is// 'last'. 'last' is 0 for 'p',// 1 for 'q' and 2 for 'r'function countWays($p, $q, $r, $last){ // if number of balls of // any color becomes less // than 0 the number of // ways arrangements is 0. if ($p < 0 || $q < 0 || $r < 0) return 0; // If last ball required is // of type P and the number // of balls of P type is 1 // while number of balls of // other color is 0 the number // of ways is 1. if ($p == 1 && $q == 0 && $r == 0 && $last == 0) return 1; // Same case as above // for 'q' and 'r' if ($p == 0 && $q == 1 && $r == 0 && $last == 1) return 1; if ($p == 0 && $q == 0 && $r == 1 && $last == 2) return 1; // if last ball required is P // and the number of ways is // the sum of number of ways // to form sequence with 'p-1' P // balls, q Q Balls and r R // balls ending with Q and R. if ($last == 0) return countWays($p - 1, $q, $r, 1) + countWays($p - 1, $q, $r, 2); // Same as above case // for 'q' and 'r' if ($last == 1) return countWays($p, $q - 1, $r, 0) + countWays($p, $q - 1, $r, 2); if ($last == 2) return countWays($p, $q, $r - 1, 0) + countWays($p, $q, $r - 1, 1);} // Returns count of// required arrangementsfunction countUtil($p, $q, $r){ // Three cases arise: // Last required balls is type P // Last required balls is type Q // Last required balls is type R return countWays($p, $q, $r, 0) + countWays($p, $q, $r, 1) + countWays($p, $q, $r, 2);} // Driver Code $p = 1; $q = 1; $r = 1; echo(countUtil($p, $q, $r)); // This code is contributed by nitin mittal.?>", "e": 35772, "s": 33776, "text": null }, { "code": "<script> // JavaScript program to count number// of ways to arrange three// types of balls such that no// two balls of same color// are adjacent to each other // Returns count of arrangements // where last placed ball is // 'last'. 'last' is 0 for 'p', // 1 for 'q' and 2 for 'r' function countWays(p, q, r, last) { // if number of balls of any // color becomes less than 0 // the number of ways arrangements is 0. if (p < 0 || q < 0 || r < 0) return 0; // If last ball required is // of type P and the number // of balls of P type is 1 // while number of balls of // other color is 0 the number // of ways is 1. if (p == 1 && q == 0 && r == 0 && last == 0) return 1; // Same case as above for 'q' and 'r' if (p == 0 && q == 1 && r == 0 && last == 1) return 1; if (p == 0 && q == 0 && r == 1 && last == 2) return 1; // if last ball required is P // and the number of ways is // the sum of number of ways // to form sequence with 'p-1' P // balls, q Q Balls and r R balls // ending with Q and R. if (last == 0) return countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2); // Same as above case for 'q' and 'r' if (last == 1) return countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2); if (last == 2) return countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1); return 0; } // Returns count of required arrangements function countUtil(p, q, r) { // Three cases arise: return countWays(p, q, r, 0) + // Last required balls is type P countWays(p, q, r, 1) + // Last required balls is type Q countWays(p, q, r, 2); // Last required balls is type R } // Driver Code let p = 1, q = 1, r = 1; document.write(countUtil(p, q, r)); // This code is contributed by target_2.</script>", "e": 37897, "s": 35772, "text": null }, { "code": null, "e": 37906, "s": 37897, "text": "Output: " }, { "code": null, "e": 37908, "s": 37906, "text": "6" }, { "code": null, "e": 38152, "s": 37908, "text": "Time Complexity of this solution is exponential.We can observe that there are many subproblems being solved again and again so the problem can be solved using Dynamic Programming (DP). We can easily make memoization solution to this problem. " }, { "code": null, "e": 38156, "s": 38152, "text": "C++" }, { "code": null, "e": 38161, "s": 38156, "text": "Java" }, { "code": null, "e": 38164, "s": 38161, "text": "C#" }, { "code": null, "e": 38172, "s": 38164, "text": "Python3" }, { "code": null, "e": 38176, "s": 38172, "text": "PHP" }, { "code": null, "e": 38187, "s": 38176, "text": "Javascript" }, { "code": "// C++ program to count number of ways to arrange three// types of balls such that no two balls of same color// are adjacent to each other#include<bits/stdc++.h>using namespace std;#define MAX 100 // table to store to store results of subproblemsint dp[MAX][MAX][MAX][3]; // Returns count of arrangements where last placed ball is// 'last'. 'last' is 0 for 'p', 1 for 'q' and 2 for 'r'int countWays(int p, int q, int r, int last){ // if number of balls of any color becomes less // than 0 the number of ways arrangements is 0. if (p<0 || q<0 || r<0) return 0; // If last ball required is of type P and the number // of balls of P type is 1 while number of balls of // other color is 0 the number of ways is 1. if (p==1 && q==0 && r==0 && last==0) return 1; // Same case as above for 'q' and 'r' if (p==0 && q==1 && r==0 && last==1) return 1; if (p==0 && q==0 && r==1 && last==2) return 1; // If this subproblem is already evaluated if (dp[p][q][r][last] != -1) return dp[p][q][r][last]; // if last ball required is P and the number of ways is // the sum of number of ways to form sequence with 'p-1' P // balls, q Q Balls and r R balls ending with Q and R. if (last==0) dp[p][q][r][last] = countWays(p-1,q,r,1) + countWays(p-1,q,r,2); // Same as above case for 'q' and 'r' else if (last==1) dp[p][q][r][last] = countWays(p,q-1,r,0) + countWays(p,q-1,r,2); else //(last==2) dp[p][q][r][last] = countWays(p,q,r-1,0) + countWays(p,q,r-1,1); return dp[p][q][r][last];} // Returns count of required arrangementsint countUtil(int p, int q, int r){ // Initialize 'dp' array memset(dp, -1, sizeof(dp)); // Three cases arise: return countWays(p, q, r, 0) + // Last required balls is type P countWays(p, q, r, 1) + // Last required balls is type Q countWays(p, q, r, 2); // Last required balls is type R} // Driver code to test aboveint main(){ int p = 1, q = 1, r = 1; printf(\"%d\", countUtil(p, q, r)); return 0;}", "e": 40251, "s": 38187, "text": null }, { "code": "// Java program to count number// of ways to arrange three// types of balls such that no// two balls of same color// are adjacent to each otherimport java.util.Arrays; class GFG{ static final int MAX = 100; // table to store to store results of subproblems static int dp[][][][] = new int[MAX][MAX][MAX][3]; // Returns count of arrangements // where last placed ball is // 'last'. 'last' is 0 for 'p', // 1 for 'q' and 2 for 'r' static int countWays(int p, int q, int r, int last) { // if number of balls of any // color becomes less than 0 // the number of ways arrangements is 0. if (p < 0 || q < 0 || r < 0) return 0; // If last ball required is // of type P and the number // of balls of P type is 1 // while number of balls of // other color is 0 the number // of ways is 1. if (p == 1 && q == 0 && r == 0 && last == 0) return 1; // Same case as above for 'q' and 'r' if (p == 0 && q == 1 && r == 0 && last == 1) return 1; if (p == 0 && q == 0 && r == 1 && last == 2) return 1; // If this subproblem is already evaluated if (dp[p][q][r][last] != -1) return dp[p][q][r][last]; // if last ball required is P and // the number of ways is the sum // of number of ways to form sequence // with 'p-1' P balls, q Q balss and // r R balls ending with Q and R. if (last == 0) dp[p][q][r][last] = countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2); // Same as above case for 'q' and 'r' else if (last == 1) dp[p][q][r][last] = countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2); //(last==2) else dp[p][q][r][last] = countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1); return dp[p][q][r][last]; } // Returns count of required arrangements static int countUtil(int p, int q, int r) { // Initialize 'dp' array for (int[][][] row : dp) { for (int[][] innerRow : row) { for (int[] innerInnerRow : innerRow) { Arrays.fill(innerInnerRow, -1); } } }; // Three cases arise: return countWays(p, q, r, 0) + // Last required balls is type P countWays(p, q, r, 1) + // Last required balls is type Q countWays(p, q, r, 2); // Last required balls is type R } // Driver code public static void main(String[] args) { int p = 1, q = 1, r = 1; System.out.print(countUtil(p, q, r)); }} // This code is contributed by Anant Agarwal.", "e": 43108, "s": 40251, "text": null }, { "code": "// C# program to count number// of ways to arrange three// types of balls such that no// two balls of same color// are adjacent to each otherusing System; class GFG{ static int MAX = 101; // table to store to store results of subproblems static int[,,,] dp = new int[MAX, MAX, MAX, 4]; // Returns count of arrangements // where last placed ball is // 'last'. 'last' is 0 for 'p', // 1 for 'q' and 2 for 'r' static int countWays(int p, int q, int r, int last) { // if number of balls of any // color becomes less than 0 // the number of ways arrangements is 0. if (p < 0 || q < 0 || r < 0) return 0; // If last ball required is // of type P and the number // of balls of P type is 1 // while number of balls of // other color is 0 the number // of ways is 1. if (p == 1 && q == 0 && r == 0 && last == 0) return 1; // Same case as above for 'q' and 'r' if (p == 0 && q == 1 && r == 0 && last == 1) return 1; if (p == 0 && q == 0 && r == 1 && last == 2) return 1; // If this subproblem is already evaluated if (dp[p, q, r, last] != -1) return dp[p, q, r, last]; // if last ball required is P and // the number of ways is the sum // of number of ways to form sequence // with 'p-1' P balls, q Q balss and // r R balls ending with Q and R. if (last == 0) dp[p, q, r, last] = countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2); // Same as above case for 'q' and 'r' else if (last == 1) dp[p, q, r, last] = countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2); //(last==2) else dp[p, q, r, last] = countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1); return dp[p, q, r, last]; } // Returns count of required arrangements static int countUtil(int p, int q, int r) { // Initialize 'dp' array for(int i = 0; i < MAX; i++) for(int j = 0; j < MAX; j++) for(int k = 0; k < MAX; k++) for(int l = 0; l < 4; l++) dp[i, j, k, l] = -1; // Three cases arise: return countWays(p, q, r, 0) + // Last required balls is type P countWays(p, q, r, 1) + // Last required balls is type Q countWays(p, q, r, 2); // Last required balls is type R } // Driver code static void Main() { int p = 1, q = 1, r = 1; Console.WriteLine(countUtil(p, q, r)); }} // This code is contributed by mits.", "e": 45822, "s": 43108, "text": null }, { "code": "# Python3 program to count number of ways to# arrange three types of balls such that no# two balls of same color are adjacent to each otherMAX = 100; # table to store to store results of subproblemsdp = [[[[-1] * 4 for i in range(MAX)] for j in range(MAX)] for k in range(MAX)]; # Returns count of arrangements where last# placed ball is 'last'. 'last' is 0 for 'p',# 1 for 'q' and 2 for 'r'def countWays(p, q, r, last): # if number of balls of any color becomes less # than 0 the number of ways arrangements is 0. if (p < 0 or q < 0 or r < 0): return 0; # If last ball required is of type P and the # number of balls of P type is 1 while number # of balls of other color is 0 the number of # ways is 1. if (p == 1 and q == 0 and r == 0 and last == 0): return 1; # Same case as above for 'q' and 'r' if (p == 0 and q == 1 and r == 0 and last == 1): return 1; if (p == 0 and q == 0 and r == 1 and last == 2): return 1; # If this subproblem is already evaluated if (dp[p][q][r][last] != -1): return dp[p][q][r][last]; # if last ball required is P and the number # of ways is the sum of number of ways to # form sequence with 'p-1' P balls, q Q Balls # and r R balls ending with Q and R. if (last == 0): dp[p][q][r][last] = (countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2)); # Same as above case for 'q' and 'r' elif (last == 1): dp[p][q][r][last] = (countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2)); else: #(last==2) dp[p][q][r][last] = (countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1)); return dp[p][q][r][last]; # Returns count of required arrangementsdef countUtil(p, q, r): # Three cases arise: # Last required balls is type P # Last required balls is type Q # Last required balls is type R return (countWays(p, q, r, 0) + countWays(p, q, r, 1) + countWays(p, q, r, 2)); # Driver Codep, q, r = 1, 1, 1;print(countUtil(p, q, r)); # This code is contributed by mits", "e": 48031, "s": 45822, "text": null }, { "code": "<?php// PHP program to count number of ways to// arrange three types of balls such that// no two balls of same color are adjacent// to each other$MAX = 100; // table to store to store results of subproblems$dp = array_fill(0, $MAX, array_fill(0, $MAX, array_fill(0, $MAX, array_fill(0, 3, -1)))); // Returns count of arrangements where last// placed ball is 'last'. 'last' is 0 for 'p',// 1 for 'q' and 2 for 'r'function countWays($p, $q, $r, $last){ global $dp; // if number of balls of any color becomes less // than 0 the number of ways arrangements is 0. if ($p < 0 || $q < 0 || $r < 0) return 0; // If last ball required is of type P and the // number of balls of P type is 1 while number // of balls of other color is 0 the number of // ways is 1. if ($p == 1 && $q == 0 && $r == 0 && $last == 0) return 1; // Same case as above for 'q' and 'r' if ($p == 0 && $q == 1 && $r == 0 && $last == 1) return 1; if ($p == 0 && $q == 0 && $r == 1 && $last == 2) return 1; // If this subproblem is already evaluated if ($dp[$p][$q][$r][$last] != -1) return $dp[$p][$q][$r][$last]; // if last ball required is P and the number of // ways is the sum of number of ways to form // sequence with 'p-1' P balls, q Q Balls and r // R balls ending with Q and R. if ($last == 0) $dp[$p][$q][$r][$last] = countWays($p - 1, $q, $r, 1) + countWays($p - 1, $q, $r, 2); // Same as above case for 'q' and 'r' else if ($last == 1) $dp[$p][$q][$r][$last] = countWays($p, $q - 1, $r, 0) + countWays($p, $q - 1, $r, 2); else //(last==2) $dp[$p][$q][$r][$last] = countWays($p, $q, $r - 1, 0) + countWays($p, $q, $r - 1, 1); return $dp[$p][$q][$r][$last];} // Returns count of required arrangementsfunction countUtil($p, $q, $r){ // Three cases arise:return countWays($p, $q, $r, 0) + // Last required balls is type P countWays($p, $q, $r, 1) + // Last required balls is type Q countWays($p, $q, $r, 2); // Last required balls is type R} // Driver code$p = 1;$q = 1;$r = 1;print(countUtil($p, $q, $r)); // This code is contributed by mits?>", "e": 50272, "s": 48031, "text": null }, { "code": "<script> // javascript program to count number// of ways to arrange three// types of balls such that no// two balls of same color// are adjacent to each other var MAX = 100; // table to store to store results of subproblemsvar dp = Array(MAX).fill(-1).map(x =>Array(MAX).fill(-1).map(x =>Array(MAX).fill(-1).map(x => Array(3).fill(-1)))); // Returns count of arrangements// where last placed ball is// 'last'. 'last' is 0 for 'p',// 1 for 'q' and 2 for 'r'function countWays( p , q , r , last){ // if number of balls of any // color becomes less than 0 // the number of ways arrangements is 0. if (p < 0 || q < 0 || r < 0) return 0; // If last ball required is // of type P and the number // of balls of P type is 1 // while number of balls of // other color is 0 the number // of ways is 1. if (p == 1 && q == 0 && r == 0 && last == 0) return 1; // Same case as above for 'q' and 'r' if (p == 0 && q == 1 && r == 0 && last == 1) return 1; if (p == 0 && q == 0 && r == 1 && last == 2) return 1; // If this subproblem is already evaluated if (dp[p][q][r][last] != -1) return dp[p][q][r][last]; // if last ball required is P and // the number of ways is the sum // of number of ways to form sequence // with 'p-1' P balls, q Q balss and // r R balls ending with Q and R. if (last == 0) dp[p][q][r][last] = countWays(p - 1, q, r, 1) + countWays(p - 1, q, r, 2); // Same as above case for 'q' and 'r' else if (last == 1) dp[p][q][r][last] = countWays(p, q - 1, r, 0) + countWays(p, q - 1, r, 2); //(last==2) else dp[p][q][r][last] = countWays(p, q, r - 1, 0) + countWays(p, q, r - 1, 1); return dp[p][q][r][last];} // Returns count of required arrangementsfunction countUtil(p , q , r){ // Three cases arise: return countWays(p, q, r, 0) + // Last required balls is type P countWays(p, q, r, 1) + // Last required balls is type Q countWays(p, q, r, 2); // Last required balls is type R} // Driver codevar p = 1, q = 1, r = 1;document.write(countUtil(p, q, r)); // This code contributed by Princi Singh</script>", "e": 52511, "s": 50272, "text": null }, { "code": null, "e": 52520, "s": 52511, "text": "Output: " }, { "code": null, "e": 52522, "s": 52520, "text": "6" }, { "code": null, "e": 52970, "s": 52522, "text": "Time complexity : O(p*q*r) Auxiliary Space : O(p*q*r*3)This article is contributed by Bhavuk Chawla. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. 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": 52983, "s": 52970, "text": "nitin mittal" }, { "code": null, "e": 52996, "s": 52983, "text": "Mithun Kumar" }, { "code": null, "e": 53005, "s": 52996, "text": "target_2" }, { "code": null, "e": 53018, "s": 53005, "text": "princi singh" }, { "code": null, "e": 53038, "s": 53018, "text": "Dynamic Programming" }, { "code": null, "e": 53051, "s": 53038, "text": "Mathematical" }, { "code": null, "e": 53071, "s": 53051, "text": "Dynamic Programming" }, { "code": null, "e": 53084, "s": 53071, "text": "Mathematical" }, { "code": null, "e": 53182, "s": 53084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 53191, "s": 53182, "text": "Comments" }, { "code": null, "e": 53204, "s": 53191, "text": "Old Comments" }, { "code": null, "e": 53235, "s": 53204, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 53268, "s": 53235, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 53336, "s": 53268, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 53399, "s": 53336, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" }, { "code": null, "e": 53420, "s": 53399, "text": "Edit Distance | DP-5" }, { "code": null, "e": 53480, "s": 53420, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 53495, "s": 53480, "text": "C++ Data Types" }, { "code": null, "e": 53538, "s": 53495, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 53562, "s": 53538, "text": "Merge two sorted arrays" } ]
GATE | GATE CS 2020 | Question 49 - GeeksforGeeks
26 May, 2021 Which one of the following predicate formulae is NOT logically valid ? Note that W is a predicate formula without any free occurrence of x.(A) ∀x(p(x) ∨ W) ≡ ∀x(px) ∨ W(B) ∃x(p(x) ∧ W) ≡ ∃xp(x) ∧ W(C) ∀x(p(x) → W) ≡ ∀xp(x) → W(D) ∃x(p(x) → W) ≡ ∀xp(x) → WAnswer: (C)Explanation: ∀x (p(x) → W) ≡ ∀x p(x) → W is wrong. Since ∀x [p(x) → W] ≡ ∀x [¬p(x) ∨ W] ≡ ∀x (¬p(x) ∨ W ≡ ¬(∃x p(x)) ∨ W ≡ ∃x p(x) → W Option (C) is correct.Quiz of this Question GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2001 | Question 23 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2014-(Set-1) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE-CS-2015 (Set 1) | Question 42
[ { "code": null, "e": 24098, "s": 24070, "text": "\n26 May, 2021" }, { "code": null, "e": 24169, "s": 24098, "text": "Which one of the following predicate formulae is NOT logically valid ?" }, { "code": null, "e": 24415, "s": 24169, "text": "Note that W is a predicate formula without any free occurrence of x.(A) ∀x(p(x) ∨ W) ≡ ∀x(px) ∨ W(B) ∃x(p(x) ∧ W) ≡ ∃xp(x) ∧ W(C) ∀x(p(x) → W) ≡ ∀xp(x) → W(D) ∃x(p(x) → W) ≡ ∀xp(x) → WAnswer: (C)Explanation: ∀x (p(x) → W) ≡ ∀x p(x) → W is wrong." }, { "code": null, "e": 24435, "s": 24415, "text": "Since ∀x [p(x) → W]" }, { "code": null, "e": 24500, "s": 24435, "text": "≡ ∀x [¬p(x) ∨ W]\n≡ ∀x (¬p(x) ∨ W\n≡ ¬(∃x p(x)) ∨ W\n≡ ∃x p(x) → W " }, { "code": null, "e": 24544, "s": 24500, "text": "Option (C) is correct.Quiz of this Question" }, { "code": null, "e": 24549, "s": 24544, "text": "GATE" }, { "code": null, "e": 24647, "s": 24549, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24656, "s": 24647, "text": "Comments" }, { "code": null, "e": 24669, "s": 24656, "text": "Old Comments" }, { "code": null, "e": 24711, "s": 24669, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 24753, "s": 24711, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 24787, "s": 24753, "text": "GATE | GATE-CS-2001 | Question 23" }, { "code": null, "e": 24829, "s": 24787, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 24863, "s": 24829, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 24905, "s": 24863, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 24938, "s": 24905, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 24980, "s": 24938, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 25034, "s": 24980, "text": "C++ Program to count Vowels in a string using Pointer" } ]
Add a temporary column with a value in MySQL?
You can add a temporary column with value with the help of the following syntax − select yourColumnName1,yourColumnName2,.....N ,yourTemporaryColumnValue as yourTemporaryColumnName from yourTableName; To add a temporary column with a value, let us create a table. The following is the query − mysql> create table TemporaryColumnWithValueDemo −> ( −> StudentId int, −> StudentName varchar(100) −> ); Query OK, 0 rows affected (0.59 sec) Inserting some records in the table. The query to insert records are as follows − mysql> insert into TemporaryColumnWithValueDemo values(101,'John'); Query OK, 1 row affected (0.13 sec) mysql> insert into TemporaryColumnWithValueDemo values(102,'Johnson'); Query OK, 1 row affected (0.15 sec) mysql> insert into TemporaryColumnWithValueDemo values(103,'Carol'); Query OK, 1 row affected (0.14 sec) mysql> insert into TemporaryColumnWithValueDemo values(104,'Sam'); Query OK, 1 row affected (0.16 sec) Display all records inserted above. The query to display all records is as follows − mysql> select *from TemporaryColumnWithValueDemo; The following is the output − +-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 101 | John | | 102 | Johnson | | 103 | Carol | | 104 | Sam | +-----------+-------------+ 4 rows in set (0.00 sec) Now here is the query to add a column with a t.emporary value. The query is as follows − mysql> select StudentId,StudentName,'M.I.T.' as TempCollegeName from TemporaryColumnWithValueDemo; The following is the output. The temporary column added successfully − +-----------+-------------+-----------------+ | StudentId | StudentName | TempCollegeName | +-----------+-------------+-----------------+ | 101 | John | M.I.T. | | 102 | Johnson | M.I.T. | | 103 | Carol | M.I.T. | | 104 | Sam | M.I.T. | +-----------+-------------+-----------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1144, "s": 1062, "text": "You can add a temporary column with value with the help of the following syntax −" }, { "code": null, "e": 1263, "s": 1144, "text": "select yourColumnName1,yourColumnName2,.....N ,yourTemporaryColumnValue as yourTemporaryColumnName from yourTableName;" }, { "code": null, "e": 1355, "s": 1263, "text": "To add a temporary column with a value, let us create a table. The following is the query −" }, { "code": null, "e": 1516, "s": 1355, "text": "mysql> create table TemporaryColumnWithValueDemo\n −> (\n −> StudentId int,\n −> StudentName varchar(100)\n −> );\nQuery OK, 0 rows affected (0.59 sec)" }, { "code": null, "e": 1598, "s": 1516, "text": "Inserting some records in the table. The query to insert records are as follows −" }, { "code": null, "e": 2020, "s": 1598, "text": "mysql> insert into TemporaryColumnWithValueDemo values(101,'John');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into TemporaryColumnWithValueDemo values(102,'Johnson');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into TemporaryColumnWithValueDemo values(103,'Carol');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into TemporaryColumnWithValueDemo values(104,'Sam');\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2105, "s": 2020, "text": "Display all records inserted above. The query to display all records is as follows −" }, { "code": null, "e": 2155, "s": 2105, "text": "mysql> select *from TemporaryColumnWithValueDemo;" }, { "code": null, "e": 2185, "s": 2155, "text": "The following is the output −" }, { "code": null, "e": 2434, "s": 2185, "text": "+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| 101 | John |\n| 102 | Johnson |\n| 103 | Carol |\n| 104 | Sam |\n+-----------+-------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2523, "s": 2434, "text": "Now here is the query to add a column with a t.emporary value. The query is as follows −" }, { "code": null, "e": 2622, "s": 2523, "text": "mysql> select StudentId,StudentName,'M.I.T.' as TempCollegeName from TemporaryColumnWithValueDemo;" }, { "code": null, "e": 2693, "s": 2622, "text": "The following is the output. The temporary column added successfully −" }, { "code": null, "e": 3086, "s": 2693, "text": "+-----------+-------------+-----------------+\n| StudentId | StudentName | TempCollegeName |\n+-----------+-------------+-----------------+\n| 101 | John | M.I.T. |\n| 102 | Johnson | M.I.T. |\n| 103 | Carol | M.I.T. |\n| 104 | Sam | M.I.T. |\n+-----------+-------------+-----------------+\n4 rows in set (0.00 sec)" } ]
Count array elements whose count of divisors is a prime number - GeeksforGeeks
20 May, 2021 Given an array arr[] consisting of N positive integers, the task is to find the number of array elements whose count of divisors is a prime number. Examples: Input: arr[] = {3, 6, 4}Output: 2Explanation:The count of divisors for each element are: arr[0]( = 3): 3 has 2 divisors i.e., 1 and 3.arr[1]( = 6): 6 has 4 divisors i.e., 1, 2, 3, and 6.arr[2]( = 4): 4 has 3 divisors i.e., 1, 2, and 4. arr[0]( = 3): 3 has 2 divisors i.e., 1 and 3. arr[1]( = 6): 6 has 4 divisors i.e., 1, 2, 3, and 6. arr[2]( = 4): 4 has 3 divisors i.e., 1, 2, and 4. Therefore, there are only 2 array elements, i.e. {3, 4}, whose count of divisors is a prime number. Input: arr[] = {10, 13, 17, 25}Output: 3 Naive Approach: The simplest approach to solve the given problem is to find the number of divisors for each array element and check if the count of divisors is a prime number or not. If found to be true, then increment the count. Otherwise, check for the next element. After checking for all array elements, print the count obtained. Time Complexity: O(N(3/2))Auxiliary Space: O(1) Efficient Approach: The above approach can be optimized by precomputing the Prime Numbers using Sieve of Eratosthenes. Follow the steps below to solve the given problem: Initialize a variable, say count, to store the count of array elements whose count of divisors is a prime number. Store all prime numbers upto the maximum element of the array in a boolean array, say prime[], using Sieve of Eratosthenes. Now find the count of divisors of elements up to the maximum element of the array and store them in an array, say countDivisor[]. Traverse the given array arr[] and for each element arr[i] and if the value of countDivisor[arr[i]] is prime, then increment the count by 1. Otherwise, check for the next element. After completing the above steps, print the value of count as the result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to count the array elements// whose count of divisors is primeint primeDivisors(int arr[], int N){ // Stores the maximum element int K = arr[0]; // Find the maximum element for (int i = 1; i < N; i++) { K = max(K, arr[i]); } // Store if i-th element is // prime(0) or non-prime(1) int prime[K + 1] = { 0 }; // Base Case prime[0] = 1; prime[1] = 1; for (int i = 2; i < K + 1; i++) { // If i is a prime number if (!prime[i]) { // Mark all multiples // of i as non-prime for (int j = 2 * i; j < K + 1; j += i) { prime[j] = 1; } } } // Stores the count of divisors int factor[K + 1] = { 0 }; // Base Case factor[0] = 0; factor[1] = 1; for (int i = 2; i < K + 1; i++) { factor[i] += 1; // Iterate to count factors for (int j = i; j < K + 1; j += i) { factor[j] += 1; } } // Stores the count of array // elements whose count of // divisors is a prime number int count = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // If count of divisors is prime if (prime[factor[arr[i]]] == 0) count++; } // Return the resultant count return count;} // Driver Codeint main(){ int arr[] = { 10, 13, 17, 25 }; int N = sizeof(arr) / sizeof(arr[0]); cout << primeDivisors(arr, N); return 0;} // Java program for the above approachpublic class GFG{ // Function to count the array elements // whose count of divisors is prime public static int primeDivisors(int[] arr, int N) { // Stores the maximum element int K = arr[0]; // Find the maximum element for (int i = 1; i < N; i++) { K = Math.max(K, arr[i]); } // Store if i-th element is // prime(0) or non-prime(1) int[] prime = new int[K + 1]; // Base Case prime[0] = 1; prime[1] = 1; for (int i = 2; i < K + 1; i++) { // If i is a prime number if (prime[i] == 0) { // Mark all multiples // of i as non-prime for (int j = 2 * i; j < K + 1; j += i) { prime[j] = 1; } } } // Stores the count of divisors int[] factor = new int[K + 1]; // Base Case factor[0] = 0; factor[1] = 1; for (int i = 2; i < K + 1; i++) { factor[i] += 1; // Iterate to count factors for (int j = i; j < K + 1; j += i) { factor[j] += 1; } } // Stores the count of array // elements whose count of // divisors is a prime number int count = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // If count of divisors is prime if (prime[factor[arr[i]]] == 0) count++; } // Return the resultant count return count; } // Driver Code public static void main(String args[]) { int[] arr = { 10, 13, 17, 25 }; int N = arr.length; System.out.println(primeDivisors(arr, N)); }} // This code is contributed by SoumikMondal. # Python3 program for the above approach # Function to count the array elements# whose count of divisors is primedef primeDivisors(arr, N): # Stores the maximum element K = arr[0] # Find the maximum element for i in range(1, N): K = max(K, arr[i]) # Store if i-th element is # prime(0) or non-prime(1) prime = [0] * (K + 1) # Base Case prime[0] = 1 prime[1] = 1 for i in range(2, K + 1): # If i is a prime number if (not prime[i]): # Mark all multiples # of i as non-prime for j in range(2 * i, K + 1, i): prime[j] = 1 # Stores the count of divisors factor = [0] * (K + 1) # Base Case factor[0] = 0 factor[1] = 1 for i in range(2, K + 1): factor[i] += 1 # Iterate to count factors for j in range(i, K + 1, i): factor[j] += 1 # Stores the count of array # elements whose count of # divisors is a prime number count = 0 # Traverse the array arr[] for i in range(N): # If count of divisors is prime if (prime[factor[arr[i]]] == 0): count += 1 # Return the resultant count return count # Driver Codeif __name__ == '__main__': arr = [ 10, 13, 17, 25 ] N = len(arr) print (primeDivisors(arr, N)) # This code is contributed by mohit kumar 29 // C# program for the above approachusing System;class GFG{ // Function to count the array elements // whose count of divisors is prime static int primeDivisors(int[] arr, int N) { // Stores the maximum element int K = arr[0]; // Find the maximum element for (int i = 1; i < N; i++) { K = Math.Max(K, arr[i]); } // Store if i-th element is // prime(0) or non-prime(1) int[] prime = new int[K + 1]; // Base Case prime[0] = 1; prime[1] = 1; for (int i = 2; i < K + 1; i++) { // If i is a prime number if (prime[i] == 0) { // Mark all multiples // of i as non-prime for (int j = 2 * i; j < K + 1; j += i) { prime[j] = 1; } } } // Stores the count of divisors int[] factor = new int[K + 1]; // Base Case factor[0] = 0; factor[1] = 1; for (int i = 2; i < K + 1; i++) { factor[i] += 1; // Iterate to count factors for (int j = i; j < K + 1; j += i) { factor[j] += 1; } } // Stores the count of array // elements whose count of // divisors is a prime number int count = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // If count of divisors is prime if (prime[factor[arr[i]]] == 0) count++; } // Return the resultant count return count; } // Driver Code public static void Main() { int[] arr = { 10, 13, 17, 25 }; int N = arr.Length; Console.WriteLine(primeDivisors(arr, N)); }} // This code is contributed by ukasp. <script> // JavaScript program for the above approach // Function to count the array elements// whose count of divisors is primefunction primeDivisors(arr, N){ // Stores the maximum element var K = arr[0]; var i,j; // Find the maximum element for (i = 1; i < N; i++) { K = Math.max(K, arr[i]); } // Store if i-th element is // prime(0) or non-prime(1) var prime = Array(K + 1).fill(0); // Base Case prime[0] = 1; prime[1] = 1; for (i = 2; i < K + 1; i++) { // If i is a prime number if (prime[i]==0) { // Mark all multiples // of i as non-prime for (j = 2 * i; j < K + 1; j += i) { prime[j] = 1; } } } // Stores the count of divisors var factor = Array(K + 1).fill(0); // Base Case factor[0] = 0; factor[1] = 1; for (i = 2; i < K + 1; i++) { factor[i] += 1; // Iterate to count factors for (j = i; j < K + 1; j += i) { factor[j] += 1; } } // Stores the count of array // elements whose count of // divisors is a prime number var count = 0; // Traverse the array arr[] for (i = 0; i < N; i++) { // If count of divisors is prime if (prime[factor[arr[i]]] == 0) count++; } // Return the resultant count return count;} // Driver Code var arr = [10, 13, 17, 25]; var N = arr.length; document.write(primeDivisors(arr, N)); </script> 3 Time Complexity: O(M*log M), where M is the maximum element of the given array. Auxiliary Space: O(M) mohit kumar 29 ukasp SoumikMondal SURENDRA_GANGWAR divisors factor Prime Number sieve Arrays Mathematical Arrays Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Reversal algorithm for array rotation Trapping Rain Water Find duplicates in O(n) time and O(1) extra space | Set 1 Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24716, "s": 24688, "text": "\n20 May, 2021" }, { "code": null, "e": 24864, "s": 24716, "text": "Given an array arr[] consisting of N positive integers, the task is to find the number of array elements whose count of divisors is a prime number." }, { "code": null, "e": 24874, "s": 24864, "text": "Examples:" }, { "code": null, "e": 24963, "s": 24874, "text": "Input: arr[] = {3, 6, 4}Output: 2Explanation:The count of divisors for each element are:" }, { "code": null, "e": 25110, "s": 24963, "text": "arr[0]( = 3): 3 has 2 divisors i.e., 1 and 3.arr[1]( = 6): 6 has 4 divisors i.e., 1, 2, 3, and 6.arr[2]( = 4): 4 has 3 divisors i.e., 1, 2, and 4." }, { "code": null, "e": 25156, "s": 25110, "text": "arr[0]( = 3): 3 has 2 divisors i.e., 1 and 3." }, { "code": null, "e": 25209, "s": 25156, "text": "arr[1]( = 6): 6 has 4 divisors i.e., 1, 2, 3, and 6." }, { "code": null, "e": 25259, "s": 25209, "text": "arr[2]( = 4): 4 has 3 divisors i.e., 1, 2, and 4." }, { "code": null, "e": 25359, "s": 25259, "text": "Therefore, there are only 2 array elements, i.e. {3, 4}, whose count of divisors is a prime number." }, { "code": null, "e": 25400, "s": 25359, "text": "Input: arr[] = {10, 13, 17, 25}Output: 3" }, { "code": null, "e": 25782, "s": 25400, "text": "Naive Approach: The simplest approach to solve the given problem is to find the number of divisors for each array element and check if the count of divisors is a prime number or not. If found to be true, then increment the count. Otherwise, check for the next element. After checking for all array elements, print the count obtained. Time Complexity: O(N(3/2))Auxiliary Space: O(1)" }, { "code": null, "e": 25952, "s": 25782, "text": "Efficient Approach: The above approach can be optimized by precomputing the Prime Numbers using Sieve of Eratosthenes. Follow the steps below to solve the given problem:" }, { "code": null, "e": 26066, "s": 25952, "text": "Initialize a variable, say count, to store the count of array elements whose count of divisors is a prime number." }, { "code": null, "e": 26190, "s": 26066, "text": "Store all prime numbers upto the maximum element of the array in a boolean array, say prime[], using Sieve of Eratosthenes." }, { "code": null, "e": 26320, "s": 26190, "text": "Now find the count of divisors of elements up to the maximum element of the array and store them in an array, say countDivisor[]." }, { "code": null, "e": 26500, "s": 26320, "text": "Traverse the given array arr[] and for each element arr[i] and if the value of countDivisor[arr[i]] is prime, then increment the count by 1. Otherwise, check for the next element." }, { "code": null, "e": 26574, "s": 26500, "text": "After completing the above steps, print the value of count as the result." }, { "code": null, "e": 26625, "s": 26574, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26629, "s": 26625, "text": "C++" }, { "code": null, "e": 26634, "s": 26629, "text": "Java" }, { "code": null, "e": 26642, "s": 26634, "text": "Python3" }, { "code": null, "e": 26645, "s": 26642, "text": "C#" }, { "code": null, "e": 26656, "s": 26645, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to count the array elements// whose count of divisors is primeint primeDivisors(int arr[], int N){ // Stores the maximum element int K = arr[0]; // Find the maximum element for (int i = 1; i < N; i++) { K = max(K, arr[i]); } // Store if i-th element is // prime(0) or non-prime(1) int prime[K + 1] = { 0 }; // Base Case prime[0] = 1; prime[1] = 1; for (int i = 2; i < K + 1; i++) { // If i is a prime number if (!prime[i]) { // Mark all multiples // of i as non-prime for (int j = 2 * i; j < K + 1; j += i) { prime[j] = 1; } } } // Stores the count of divisors int factor[K + 1] = { 0 }; // Base Case factor[0] = 0; factor[1] = 1; for (int i = 2; i < K + 1; i++) { factor[i] += 1; // Iterate to count factors for (int j = i; j < K + 1; j += i) { factor[j] += 1; } } // Stores the count of array // elements whose count of // divisors is a prime number int count = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // If count of divisors is prime if (prime[factor[arr[i]]] == 0) count++; } // Return the resultant count return count;} // Driver Codeint main(){ int arr[] = { 10, 13, 17, 25 }; int N = sizeof(arr) / sizeof(arr[0]); cout << primeDivisors(arr, N); return 0;}", "e": 28231, "s": 26656, "text": null }, { "code": "// Java program for the above approachpublic class GFG{ // Function to count the array elements // whose count of divisors is prime public static int primeDivisors(int[] arr, int N) { // Stores the maximum element int K = arr[0]; // Find the maximum element for (int i = 1; i < N; i++) { K = Math.max(K, arr[i]); } // Store if i-th element is // prime(0) or non-prime(1) int[] prime = new int[K + 1]; // Base Case prime[0] = 1; prime[1] = 1; for (int i = 2; i < K + 1; i++) { // If i is a prime number if (prime[i] == 0) { // Mark all multiples // of i as non-prime for (int j = 2 * i; j < K + 1; j += i) { prime[j] = 1; } } } // Stores the count of divisors int[] factor = new int[K + 1]; // Base Case factor[0] = 0; factor[1] = 1; for (int i = 2; i < K + 1; i++) { factor[i] += 1; // Iterate to count factors for (int j = i; j < K + 1; j += i) { factor[j] += 1; } } // Stores the count of array // elements whose count of // divisors is a prime number int count = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // If count of divisors is prime if (prime[factor[arr[i]]] == 0) count++; } // Return the resultant count return count; } // Driver Code public static void main(String args[]) { int[] arr = { 10, 13, 17, 25 }; int N = arr.length; System.out.println(primeDivisors(arr, N)); }} // This code is contributed by SoumikMondal.", "e": 30072, "s": 28231, "text": null }, { "code": "# Python3 program for the above approach # Function to count the array elements# whose count of divisors is primedef primeDivisors(arr, N): # Stores the maximum element K = arr[0] # Find the maximum element for i in range(1, N): K = max(K, arr[i]) # Store if i-th element is # prime(0) or non-prime(1) prime = [0] * (K + 1) # Base Case prime[0] = 1 prime[1] = 1 for i in range(2, K + 1): # If i is a prime number if (not prime[i]): # Mark all multiples # of i as non-prime for j in range(2 * i, K + 1, i): prime[j] = 1 # Stores the count of divisors factor = [0] * (K + 1) # Base Case factor[0] = 0 factor[1] = 1 for i in range(2, K + 1): factor[i] += 1 # Iterate to count factors for j in range(i, K + 1, i): factor[j] += 1 # Stores the count of array # elements whose count of # divisors is a prime number count = 0 # Traverse the array arr[] for i in range(N): # If count of divisors is prime if (prime[factor[arr[i]]] == 0): count += 1 # Return the resultant count return count # Driver Codeif __name__ == '__main__': arr = [ 10, 13, 17, 25 ] N = len(arr) print (primeDivisors(arr, N)) # This code is contributed by mohit kumar 29", "e": 31482, "s": 30072, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to count the array elements // whose count of divisors is prime static int primeDivisors(int[] arr, int N) { // Stores the maximum element int K = arr[0]; // Find the maximum element for (int i = 1; i < N; i++) { K = Math.Max(K, arr[i]); } // Store if i-th element is // prime(0) or non-prime(1) int[] prime = new int[K + 1]; // Base Case prime[0] = 1; prime[1] = 1; for (int i = 2; i < K + 1; i++) { // If i is a prime number if (prime[i] == 0) { // Mark all multiples // of i as non-prime for (int j = 2 * i; j < K + 1; j += i) { prime[j] = 1; } } } // Stores the count of divisors int[] factor = new int[K + 1]; // Base Case factor[0] = 0; factor[1] = 1; for (int i = 2; i < K + 1; i++) { factor[i] += 1; // Iterate to count factors for (int j = i; j < K + 1; j += i) { factor[j] += 1; } } // Stores the count of array // elements whose count of // divisors is a prime number int count = 0; // Traverse the array arr[] for (int i = 0; i < N; i++) { // If count of divisors is prime if (prime[factor[arr[i]]] == 0) count++; } // Return the resultant count return count; } // Driver Code public static void Main() { int[] arr = { 10, 13, 17, 25 }; int N = arr.Length; Console.WriteLine(primeDivisors(arr, N)); }} // This code is contributed by ukasp.", "e": 33304, "s": 31482, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to count the array elements// whose count of divisors is primefunction primeDivisors(arr, N){ // Stores the maximum element var K = arr[0]; var i,j; // Find the maximum element for (i = 1; i < N; i++) { K = Math.max(K, arr[i]); } // Store if i-th element is // prime(0) or non-prime(1) var prime = Array(K + 1).fill(0); // Base Case prime[0] = 1; prime[1] = 1; for (i = 2; i < K + 1; i++) { // If i is a prime number if (prime[i]==0) { // Mark all multiples // of i as non-prime for (j = 2 * i; j < K + 1; j += i) { prime[j] = 1; } } } // Stores the count of divisors var factor = Array(K + 1).fill(0); // Base Case factor[0] = 0; factor[1] = 1; for (i = 2; i < K + 1; i++) { factor[i] += 1; // Iterate to count factors for (j = i; j < K + 1; j += i) { factor[j] += 1; } } // Stores the count of array // elements whose count of // divisors is a prime number var count = 0; // Traverse the array arr[] for (i = 0; i < N; i++) { // If count of divisors is prime if (prime[factor[arr[i]]] == 0) count++; } // Return the resultant count return count;} // Driver Code var arr = [10, 13, 17, 25]; var N = arr.length; document.write(primeDivisors(arr, N)); </script>", "e": 34833, "s": 33304, "text": null }, { "code": null, "e": 34835, "s": 34833, "text": "3" }, { "code": null, "e": 34939, "s": 34837, "text": "Time Complexity: O(M*log M), where M is the maximum element of the given array. Auxiliary Space: O(M)" }, { "code": null, "e": 34954, "s": 34939, "text": "mohit kumar 29" }, { "code": null, "e": 34960, "s": 34954, "text": "ukasp" }, { "code": null, "e": 34973, "s": 34960, "text": "SoumikMondal" }, { "code": null, "e": 34990, "s": 34973, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 34999, "s": 34990, "text": "divisors" }, { "code": null, "e": 35006, "s": 34999, "text": "factor" }, { "code": null, "e": 35019, "s": 35006, "text": "Prime Number" }, { "code": null, "e": 35025, "s": 35019, "text": "sieve" }, { "code": null, "e": 35032, "s": 35025, "text": "Arrays" }, { "code": null, "e": 35045, "s": 35032, "text": "Mathematical" }, { "code": null, "e": 35052, "s": 35045, "text": "Arrays" }, { "code": null, "e": 35065, "s": 35052, "text": "Mathematical" }, { "code": null, "e": 35078, "s": 35065, "text": "Prime Number" }, { "code": null, "e": 35084, "s": 35078, "text": "sieve" }, { "code": null, "e": 35182, "s": 35084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35191, "s": 35182, "text": "Comments" }, { "code": null, "e": 35204, "s": 35191, "text": "Old Comments" }, { "code": null, "e": 35229, "s": 35204, "text": "Window Sliding Technique" }, { "code": null, "e": 35278, "s": 35229, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 35316, "s": 35278, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 35336, "s": 35316, "text": "Trapping Rain Water" }, { "code": null, "e": 35394, "s": 35336, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 35424, "s": 35394, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35439, "s": 35424, "text": "C++ Data Types" }, { "code": null, "e": 35499, "s": 35439, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 35542, "s": 35499, "text": "Set in C++ Standard Template Library (STL)" } ]
How to convert categorical data to binary data in Python? - GeeksforGeeks
17 Jan, 2022 Categorical Data is data that corresponds to the Categorical Variable. A Categorical Variable is a variable that takes fixed, a limited set of possible values. For example Gender, Blood group, a person having country residential or not, etc. Characteristics of Categorical Data : This is mostly used in Statistics. Numerical Operation like Addition, Subtraction etc. on this type of Data is not possible. All the values of Categorical Data are in Categories. It usually uses the Array Data Structure. Example : Categorical Data A Binary Data is a Data which uses two possible states or values i.e. 0 and 1.Binary data is mostly used in various fields like in Computer Science we use it as under name Bit(Binary Digit), in Digital Electronic and mathematics we use it as under name Truth Values, and we use name Binary Variable in Statistics. Characteristics : The (0 and 1) also referred to as (true and false), (success and failure), (yes and no) etc. Binary Data is a discrete Data and also used in statistics. Example : Binary Data Our task is to convert Categorical data into Binary Data as shown below in python : Step-by-step Approach: Step 1) In order to convert Categorical Data into Binary Data we use some function which is available in Pandas Framework. That’s why Pandas framework is imported Python3 # import required moduleimport pandas as pd Step2) After that a list is created and data is entered as shown below. Python3 # import required modulesimport pandas as pd # assign datadata = [["Jagroop", "Male"], ["Praveen", "Male"], ["Harjot", "Female"], ["Pooja", "Female"], ["Mohit", "Male"]] Step 3) After that Dataframe is created using pd.DataFrame() and here we add extra line i.e. print(data_frame) in order to show the Categorical Data Output as shown below: Python3 # import required modulesimport pandas as pd # assign datadata = [["Jagroop", "Male"], ["Praveen", "Male"], ["Harjot", "Female"], ["Pooja", "Female"], ["Mohit", "Male"]] # display categorical outputdata_frame = pd.DataFrame(data, columns=["Name", "Gender"])print(data_frame) Output: Categorical Data Step 4) Till step 3 we get Categorical Data now we will convert it into Binary Data. So for that, we have to the inbuilt function of Pandas i.e. get_dummies() as shown: Here we use get_dummies() for only Gender column because here we want to convert Categorical Data to Binary data only for Gender Column. Python3 # import required modulesimport pandas as pd # assign datadata = [["Jagroop", "Male"], ["Praveen", "Male"], ["Harjot", "Female"], ["Pooja", "Female"], ["Mohit", "Male"]] # display categorical outputdata_frame = pd.DataFrame(data, columns=["Name", "Gender"])print(data_frame) # converting to binary datadf_one = pd.get_dummies(data_frame["Gender"])print(df_one) output of step 4 Here we get output in binary code for Gender Column only. Here we have two options to use it wisely: Add above output to Dataframe -> Remove Gender Column -> Remove Female column(if we want Male =1 and Female =0) -> Rename Male = Gender -> Show Output of Conversion.Add above output to Dataframe -> Remove Gender Column -> Remove Male column( if we want Male =0 and Female =1) -> Rename Female = Gender -> Show Output of Conversion. Add above output to Dataframe -> Remove Gender Column -> Remove Female column(if we want Male =1 and Female =0) -> Rename Male = Gender -> Show Output of Conversion. Add above output to Dataframe -> Remove Gender Column -> Remove Male column( if we want Male =0 and Female =1) -> Rename Female = Gender -> Show Output of Conversion. In the below program we used the first option and Write code accordingly as shown below: Python3 # import required modulesimport pandas as pd # assign datadata = [["Jagroop", "Male"], ["Praveen", "Male"], ["Harjot", "Female"], ["Pooja", "Female"], ["Mohit", "Male"]] # display categorical outputdata_frame = pd.DataFrame(data, columns=["Name", "Gender"])# print(data_frame) # converting to binary datadf_one = pd.get_dummies(data_frame["Gender"])# print(df_one) # display resultdf_two = pd.concat((df_one, data_frame), axis=1)df_two = df_two.drop(["Gender"], axis=1)df_two = df_two.drop(["Male"], axis=1)result = df_two.rename(columns={"Female": "Gender"})print(result) Output: Output Below is the complete program based on the above approach: Python3 # Pandas is imported in order to use various inbuilt# Functions available in Pandas frameworkimport pandas as pd # Data is initialized heredata = [["Jagroop", "Male"], ["Parveen", "Male"], ["Harjot", "Female"], ["Pooja", "Female"], ["Mohit", "Male"]] # Data frame is created under column name Name and Genderdata_frame = pd.DataFrame(data, columns=["Name", "Gender"]) # Data of Gender is converted into Binary Datadf_one = pd.get_dummies(data_frame["Gender"]) # Binary Data is Concatenated into Dataframedf_two = pd.concat((df_one, data_frame), axis=1) # Gendercolumn is droppeddf_two = df_two.drop(["Gender"], axis=1) # We want Male =0 and Female =1 So we drop Male column heredf_two = df_two.drop(["Male"], axis=1) # Rename the Columnresult = df_two.rename(columns={"Female": "Gender"}) # Print the Resultprint(result) Output: Output anikakapoor saurabh1990aror Picked Python-pandas Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n17 Jan, 2022" }, { "code": null, "e": 24143, "s": 23901, "text": "Categorical Data is data that corresponds to the Categorical Variable. A Categorical Variable is a variable that takes fixed, a limited set of possible values. For example Gender, Blood group, a person having country residential or not, etc." }, { "code": null, "e": 24181, "s": 24143, "text": "Characteristics of Categorical Data :" }, { "code": null, "e": 24216, "s": 24181, "text": "This is mostly used in Statistics." }, { "code": null, "e": 24306, "s": 24216, "text": "Numerical Operation like Addition, Subtraction etc. on this type of Data is not possible." }, { "code": null, "e": 24360, "s": 24306, "text": "All the values of Categorical Data are in Categories." }, { "code": null, "e": 24402, "s": 24360, "text": "It usually uses the Array Data Structure." }, { "code": null, "e": 24412, "s": 24402, "text": "Example :" }, { "code": null, "e": 24429, "s": 24412, "text": "Categorical Data" }, { "code": null, "e": 24743, "s": 24429, "text": "A Binary Data is a Data which uses two possible states or values i.e. 0 and 1.Binary data is mostly used in various fields like in Computer Science we use it as under name Bit(Binary Digit), in Digital Electronic and mathematics we use it as under name Truth Values, and we use name Binary Variable in Statistics." }, { "code": null, "e": 24761, "s": 24743, "text": "Characteristics :" }, { "code": null, "e": 24854, "s": 24761, "text": "The (0 and 1) also referred to as (true and false), (success and failure), (yes and no) etc." }, { "code": null, "e": 24914, "s": 24854, "text": "Binary Data is a discrete Data and also used in statistics." }, { "code": null, "e": 24924, "s": 24914, "text": "Example :" }, { "code": null, "e": 24936, "s": 24924, "text": "Binary Data" }, { "code": null, "e": 25020, "s": 24936, "text": "Our task is to convert Categorical data into Binary Data as shown below in python :" }, { "code": null, "e": 25043, "s": 25020, "text": "Step-by-step Approach:" }, { "code": null, "e": 25206, "s": 25043, "text": "Step 1) In order to convert Categorical Data into Binary Data we use some function which is available in Pandas Framework. That’s why Pandas framework is imported" }, { "code": null, "e": 25214, "s": 25206, "text": "Python3" }, { "code": "# import required moduleimport pandas as pd", "e": 25258, "s": 25214, "text": null }, { "code": null, "e": 25330, "s": 25258, "text": "Step2) After that a list is created and data is entered as shown below." }, { "code": null, "e": 25338, "s": 25330, "text": "Python3" }, { "code": "# import required modulesimport pandas as pd # assign datadata = [[\"Jagroop\", \"Male\"], [\"Praveen\", \"Male\"], [\"Harjot\", \"Female\"], [\"Pooja\", \"Female\"], [\"Mohit\", \"Male\"]]", "e": 25522, "s": 25338, "text": null }, { "code": null, "e": 25694, "s": 25522, "text": "Step 3) After that Dataframe is created using pd.DataFrame() and here we add extra line i.e. print(data_frame) in order to show the Categorical Data Output as shown below:" }, { "code": null, "e": 25702, "s": 25694, "text": "Python3" }, { "code": "# import required modulesimport pandas as pd # assign datadata = [[\"Jagroop\", \"Male\"], [\"Praveen\", \"Male\"], [\"Harjot\", \"Female\"], [\"Pooja\", \"Female\"], [\"Mohit\", \"Male\"]] # display categorical outputdata_frame = pd.DataFrame(data, columns=[\"Name\", \"Gender\"])print(data_frame)", "e": 25991, "s": 25702, "text": null }, { "code": null, "e": 25999, "s": 25991, "text": "Output:" }, { "code": null, "e": 26016, "s": 25999, "text": "Categorical Data" }, { "code": null, "e": 26185, "s": 26016, "text": "Step 4) Till step 3 we get Categorical Data now we will convert it into Binary Data. So for that, we have to the inbuilt function of Pandas i.e. get_dummies() as shown:" }, { "code": null, "e": 26322, "s": 26185, "text": "Here we use get_dummies() for only Gender column because here we want to convert Categorical Data to Binary data only for Gender Column." }, { "code": null, "e": 26330, "s": 26322, "text": "Python3" }, { "code": "# import required modulesimport pandas as pd # assign datadata = [[\"Jagroop\", \"Male\"], [\"Praveen\", \"Male\"], [\"Harjot\", \"Female\"], [\"Pooja\", \"Female\"], [\"Mohit\", \"Male\"]] # display categorical outputdata_frame = pd.DataFrame(data, columns=[\"Name\", \"Gender\"])print(data_frame) # converting to binary datadf_one = pd.get_dummies(data_frame[\"Gender\"])print(df_one)", "e": 26705, "s": 26330, "text": null }, { "code": null, "e": 26722, "s": 26705, "text": "output of step 4" }, { "code": null, "e": 26823, "s": 26722, "text": "Here we get output in binary code for Gender Column only. Here we have two options to use it wisely:" }, { "code": null, "e": 27155, "s": 26823, "text": "Add above output to Dataframe -> Remove Gender Column -> Remove Female column(if we want Male =1 and Female =0) -> Rename Male = Gender -> Show Output of Conversion.Add above output to Dataframe -> Remove Gender Column -> Remove Male column( if we want Male =0 and Female =1) -> Rename Female = Gender -> Show Output of Conversion." }, { "code": null, "e": 27321, "s": 27155, "text": "Add above output to Dataframe -> Remove Gender Column -> Remove Female column(if we want Male =1 and Female =0) -> Rename Male = Gender -> Show Output of Conversion." }, { "code": null, "e": 27488, "s": 27321, "text": "Add above output to Dataframe -> Remove Gender Column -> Remove Male column( if we want Male =0 and Female =1) -> Rename Female = Gender -> Show Output of Conversion." }, { "code": null, "e": 27577, "s": 27488, "text": "In the below program we used the first option and Write code accordingly as shown below:" }, { "code": null, "e": 27585, "s": 27577, "text": "Python3" }, { "code": "# import required modulesimport pandas as pd # assign datadata = [[\"Jagroop\", \"Male\"], [\"Praveen\", \"Male\"], [\"Harjot\", \"Female\"], [\"Pooja\", \"Female\"], [\"Mohit\", \"Male\"]] # display categorical outputdata_frame = pd.DataFrame(data, columns=[\"Name\", \"Gender\"])# print(data_frame) # converting to binary datadf_one = pd.get_dummies(data_frame[\"Gender\"])# print(df_one) # display resultdf_two = pd.concat((df_one, data_frame), axis=1)df_two = df_two.drop([\"Gender\"], axis=1)df_two = df_two.drop([\"Male\"], axis=1)result = df_two.rename(columns={\"Female\": \"Gender\"})print(result)", "e": 28172, "s": 27585, "text": null }, { "code": null, "e": 28180, "s": 28172, "text": "Output:" }, { "code": null, "e": 28187, "s": 28180, "text": "Output" }, { "code": null, "e": 28246, "s": 28187, "text": "Below is the complete program based on the above approach:" }, { "code": null, "e": 28254, "s": 28246, "text": "Python3" }, { "code": "# Pandas is imported in order to use various inbuilt# Functions available in Pandas frameworkimport pandas as pd # Data is initialized heredata = [[\"Jagroop\", \"Male\"], [\"Parveen\", \"Male\"], [\"Harjot\", \"Female\"], [\"Pooja\", \"Female\"], [\"Mohit\", \"Male\"]] # Data frame is created under column name Name and Genderdata_frame = pd.DataFrame(data, columns=[\"Name\", \"Gender\"]) # Data of Gender is converted into Binary Datadf_one = pd.get_dummies(data_frame[\"Gender\"]) # Binary Data is Concatenated into Dataframedf_two = pd.concat((df_one, data_frame), axis=1) # Gendercolumn is droppeddf_two = df_two.drop([\"Gender\"], axis=1) # We want Male =0 and Female =1 So we drop Male column heredf_two = df_two.drop([\"Male\"], axis=1) # Rename the Columnresult = df_two.rename(columns={\"Female\": \"Gender\"}) # Print the Resultprint(result)", "e": 29089, "s": 28254, "text": null }, { "code": null, "e": 29097, "s": 29089, "text": "Output:" }, { "code": null, "e": 29104, "s": 29097, "text": "Output" }, { "code": null, "e": 29116, "s": 29104, "text": "anikakapoor" }, { "code": null, "e": 29132, "s": 29116, "text": "saurabh1990aror" }, { "code": null, "e": 29139, "s": 29132, "text": "Picked" }, { "code": null, "e": 29153, "s": 29139, "text": "Python-pandas" }, { "code": null, "e": 29177, "s": 29153, "text": "Technical Scripter 2020" }, { "code": null, "e": 29184, "s": 29177, "text": "Python" }, { "code": null, "e": 29203, "s": 29184, "text": "Technical Scripter" }, { "code": null, "e": 29301, "s": 29203, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29310, "s": 29301, "text": "Comments" }, { "code": null, "e": 29323, "s": 29310, "text": "Old Comments" }, { "code": null, "e": 29355, "s": 29323, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29411, "s": 29355, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29453, "s": 29411, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29495, "s": 29453, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29531, "s": 29495, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 29553, "s": 29531, "text": "Defaultdict in Python" }, { "code": null, "e": 29592, "s": 29553, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29619, "s": 29592, "text": "Python Classes and Objects" }, { "code": null, "e": 29650, "s": 29619, "text": "Python | os.path.join() method" } ]
Python - Convert 1D list to 2D list of variable length
A list in python is normally a 1D list where the elements are listed one after another. But in a 2D list we have list nested inside the outer list. In this article we will see how to create a 2D list from a given 1D list. We also supply the values for the number of elements inside the 2D list to the program. In this approach we will create a for loop to loop through each element in the 2D list and use it as an index for the new list to be created. We keep incrementing the index value by starting it at zero and adding it to the the element we receive from the 2D list. # Given list listA = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] # Length of 2D lists needed len_2d = [ 2, 4] #Declare empty new list res = [] def convert(listA, len_2d): idx = 0 for var_len in len_2d: res.append(listA[idx: idx + var_len]) idx += var_len convert(listA, len_2d) print("The new 2D lis is: \n",res) Running the above code gives us the following result − The new 2D lis is: [[1, 2], [3, 4, 5, 6]] The islice function can be used to slice a given list with certain number of elements as required by the 2D list. So here week looked through each element of the 2D list and use that value 2 slice the original list. We need itertools package to use the islice function. from itertools import islice # Given list listA = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] # Length of 2D lists needed len_2d = [ 3, 2] # Use islice def convert(listA, len_2d): res = iter(listA) return [list(islice(res,i)) for i in len_2d] res = [convert(listA, len_2d)] print("The new 2D lis is: \n",res) Running the above code gives us the following result − The new 2D lis is: [[['Sun', 'Mon', 'Tue'], ['Wed', 'Thu']]]
[ { "code": null, "e": 1497, "s": 1187, "text": "A list in python is normally a 1D list where the elements are listed one after another. But in a 2D list we have list nested inside the outer list. In this article we will see how to create a 2D list from a given 1D list. We also supply the values for the number of elements inside the 2D list to the program." }, { "code": null, "e": 1761, "s": 1497, "text": "In this approach we will create a for loop to loop through each element in the 2D list and use it as an index for the new list to be created. We keep incrementing the index value by starting it at zero and adding it to the the element we receive from the 2D list." }, { "code": null, "e": 2094, "s": 1761, "text": "# Given list\nlistA = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']\n\n# Length of 2D lists needed\nlen_2d = [ 2, 4]\n\n#Declare empty new list\nres = []\ndef convert(listA, len_2d):\n idx = 0\n for var_len in len_2d:\n res.append(listA[idx: idx + var_len])\n idx += var_len\nconvert(listA, len_2d)\nprint(\"The new 2D lis is: \\n\",res)" }, { "code": null, "e": 2149, "s": 2094, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2191, "s": 2149, "text": "The new 2D lis is:\n[[1, 2], [3, 4, 5, 6]]" }, { "code": null, "e": 2461, "s": 2191, "text": "The islice function can be used to slice a given list with certain number of elements as required by the 2D list. So here week looked through each element of the 2D list and use that value 2 slice the original list. We need itertools package to use the islice function." }, { "code": null, "e": 2778, "s": 2461, "text": "from itertools import islice\n# Given list\nlistA = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']\n\n# Length of 2D lists needed\nlen_2d = [ 3, 2]\n\n# Use islice\ndef convert(listA, len_2d):\n res = iter(listA)\n return [list(islice(res,i)) for i in len_2d]\nres = [convert(listA, len_2d)]\nprint(\"The new 2D lis is: \\n\",res)" }, { "code": null, "e": 2833, "s": 2778, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2894, "s": 2833, "text": "The new 2D lis is:\n[[['Sun', 'Mon', 'Tue'], ['Wed', 'Thu']]]" } ]
How to measure time taken by a function in java ?
08 Jan, 2018 We can measure the time taken by a function in Java with the help of java.lang.System.currentTimeMillis() method. This method returns the current time in millisecond. We can call this method at the beginning and at the end of function and by the difference we measure the time taken by the function. import java.io.*; public class Time { public static void main(String[] args) { // starting time long start = System.currentTimeMillis(); // start of function count_function(10000000); // end of function // ending time long end = System.currentTimeMillis(); System.out.println("Counting to 10000000 takes " + (end - start) + "ms"); } // A dummy function that runs a loop x times public static void count_function(long x) { System.out.println("Loop starts"); for (long i = 0; i < x; i++) ; System.out.println("Loop ends"); }} Output: Loop starts Loop ends Counting to 10000000 takes 8ms How to measure time taken by a program in C? java-puzzle 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 Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jan, 2018" }, { "code": null, "e": 353, "s": 53, "text": "We can measure the time taken by a function in Java with the help of java.lang.System.currentTimeMillis() method. This method returns the current time in millisecond. We can call this method at the beginning and at the end of function and by the difference we measure the time taken by the function." }, { "code": "import java.io.*; public class Time { public static void main(String[] args) { // starting time long start = System.currentTimeMillis(); // start of function count_function(10000000); // end of function // ending time long end = System.currentTimeMillis(); System.out.println(\"Counting to 10000000 takes \" + (end - start) + \"ms\"); } // A dummy function that runs a loop x times public static void count_function(long x) { System.out.println(\"Loop starts\"); for (long i = 0; i < x; i++) ; System.out.println(\"Loop ends\"); }}", "e": 1037, "s": 353, "text": null }, { "code": null, "e": 1045, "s": 1037, "text": "Output:" }, { "code": null, "e": 1099, "s": 1045, "text": "Loop starts\nLoop ends\nCounting to 10000000 takes 8ms\n" }, { "code": null, "e": 1144, "s": 1099, "text": "How to measure time taken by a program in C?" }, { "code": null, "e": 1156, "s": 1144, "text": "java-puzzle" }, { "code": null, "e": 1161, "s": 1156, "text": "Java" }, { "code": null, "e": 1166, "s": 1161, "text": "Java" }, { "code": null, "e": 1264, "s": 1166, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1279, "s": 1264, "text": "Stream In Java" }, { "code": null, "e": 1300, "s": 1279, "text": "Introduction to Java" }, { "code": null, "e": 1321, "s": 1300, "text": "Constructors in Java" }, { "code": null, "e": 1340, "s": 1321, "text": "Exceptions in Java" }, { "code": null, "e": 1357, "s": 1340, "text": "Generics in Java" }, { "code": null, "e": 1387, "s": 1357, "text": "Functional Interfaces in Java" }, { "code": null, "e": 1413, "s": 1387, "text": "Java Programming Examples" }, { "code": null, "e": 1429, "s": 1413, "text": "Strings in Java" }, { "code": null, "e": 1466, "s": 1429, "text": "Differences between JDK, JRE and JVM" } ]
Fill an empty matrix in R
21 Apr, 2021 In this article, we will discuss how to fill the empty matrix with values in R Programming Language. First, let’s create an empty matrix. Syntax: matrix_name[row,column]=value. Where, row and column are the numbers in which the value is occupied. Example: R # create empty matrix.a<-matrix(nrow=4,ncol=4) # display matrixprint(a) # filling empty matrix with value at # 2nd row and 4 th columna[2,4]=4print(a) # create empty matrix.a<-matrix(nrow=4,ncol=4) # filling empty matrix with value at # 4th columna[,4]=4print(a) # create empty matrix.a<-matrix(nrow=4,ncol=4) # filling empty matrix with value at # 4th rowa[4,]=4print(a) Output: We can replace with same value for all empty value in a matrix, by using [,]. Example R # create empty matrix.a<-matrix(nrow=4,ncol=4) # display matrixprint(a) # replace empty matrix with 5 valuea[,]=5print(a) Output: Even a range can be inserted. Example R # create empty matrix.a<-matrix(nrow=4,ncol=4) # display matrixprint(a) # replace empty matrix with # 1 to 16 valuesa[,]=1:16print(a) Output: Picked R Matrix-Programs R-Matrix R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2021" }, { "code": null, "e": 166, "s": 28, "text": "In this article, we will discuss how to fill the empty matrix with values in R Programming Language. First, let’s create an empty matrix." }, { "code": null, "e": 174, "s": 166, "text": "Syntax:" }, { "code": null, "e": 205, "s": 174, "text": "matrix_name[row,column]=value." }, { "code": null, "e": 275, "s": 205, "text": "Where, row and column are the numbers in which the value is occupied." }, { "code": null, "e": 284, "s": 275, "text": "Example:" }, { "code": null, "e": 286, "s": 284, "text": "R" }, { "code": "# create empty matrix.a<-matrix(nrow=4,ncol=4) # display matrixprint(a) # filling empty matrix with value at # 2nd row and 4 th columna[2,4]=4print(a) # create empty matrix.a<-matrix(nrow=4,ncol=4) # filling empty matrix with value at # 4th columna[,4]=4print(a) # create empty matrix.a<-matrix(nrow=4,ncol=4) # filling empty matrix with value at # 4th rowa[4,]=4print(a)", "e": 664, "s": 286, "text": null }, { "code": null, "e": 672, "s": 664, "text": "Output:" }, { "code": null, "e": 750, "s": 672, "text": "We can replace with same value for all empty value in a matrix, by using [,]." }, { "code": null, "e": 758, "s": 750, "text": "Example" }, { "code": null, "e": 760, "s": 758, "text": "R" }, { "code": "# create empty matrix.a<-matrix(nrow=4,ncol=4) # display matrixprint(a) # replace empty matrix with 5 valuea[,]=5print(a)", "e": 884, "s": 760, "text": null }, { "code": null, "e": 892, "s": 884, "text": "Output:" }, { "code": null, "e": 922, "s": 892, "text": "Even a range can be inserted." }, { "code": null, "e": 930, "s": 922, "text": "Example" }, { "code": null, "e": 932, "s": 930, "text": "R" }, { "code": "# create empty matrix.a<-matrix(nrow=4,ncol=4) # display matrixprint(a) # replace empty matrix with # 1 to 16 valuesa[,]=1:16print(a)", "e": 1069, "s": 932, "text": null }, { "code": null, "e": 1077, "s": 1069, "text": "Output:" }, { "code": null, "e": 1084, "s": 1077, "text": "Picked" }, { "code": null, "e": 1102, "s": 1084, "text": "R Matrix-Programs" }, { "code": null, "e": 1111, "s": 1102, "text": "R-Matrix" }, { "code": null, "e": 1122, "s": 1111, "text": "R Language" }, { "code": null, "e": 1133, "s": 1122, "text": "R Programs" } ]
What is .editorconfig ?
21 Sep, 2021 EditorConfig is a simple configuration file that contains a list of rules which can be applied to any IDE’s or code editors for proper formatting of code. But why use EditorConfig? Consider a scenario where your team is working on a project but the individual members of the team use a different IDE or code editor, these differences might result in inconsistent formatting applied to the code as each IDE/editor has its own configurations. EditorConfig solves this problem by having a single config file that is readable by all IDE’s and code editors with the help of some plugins/extensions. This tool is used extensively in many big projects including Angular, Bootstrap, Django, Nodejs, React, Vuejs, and a lot more. You can have a common indentation-style (Tabs/Spaces) & indentation-sizeEditorConfig will help in configuring character encoding and line-endings (lf/crlf)It can also enforce the editor to have a new line at end of each file and many more. You can have a common indentation-style (Tabs/Spaces) & indentation-size EditorConfig will help in configuring character encoding and line-endings (lf/crlf) It can also enforce the editor to have a new line at end of each file and many more. To set up EditorConfig, you need to install the plugin/extension respective to your IDE/editor.Following editors doesn’t need any plugins as they come with native support for EditorConfig: IntelliJ Pycharm Visual Studio Github / Gitlab / Gitbucket If you use the Editors listed below then you should install the plugin through their respective links: VS Code Atom Eclipse CodeBlocks Netbeans Sublime Text Once the respective plugin/extension is installed create a file named `.editorconfig` in the root of your project directory If you are using VS Code you can generate a new editorconfig file via the Explorer sidebar’s context menu by right-clicking in the folder where you’d like it to be and selecting Generate .editorconfig. A new .editorconfig file was generated with help of EditorConfig Extension in VS-Code root = true : Whenever you open your Editor, the EditorConfig plugin will look for a file named `.editorconfig` in the directory of opened files and in every parent directory, but this search can be stopped if it reaches the root file path which can be specified with root=true. Comments : Comments in `.editorconfig` starts with ‘#’ or ‘;’. Section Headers : They start with ‘[‘ and end with ‘]’, they are used to select the specific files and apply rules to them. For example ‘[*.js]’ will apply all the rules to any file which has `.js` as an extension. Key-Value pairs : These key-value pairs are the rules(supported properties) that are located under Section Headers. For example ‘indent_size = 4` will set size of indentation to 4 space/tabs. You may find all the supported properties on their wiki page. # EditorConfig is awesome: https://EditorConfig.org # top-most EditorConfig file root = true [*] charset = utf-8 end_of_line = lf indent_size = 4 indent_style = space insert_final_newline = true max_line_length = 80 trim_trailing_whitespace = true [*.md] max_line_length = 0 trim_trailing_whitespace = false Here the root=true specify to the editor that it is the top-most EditorConfig file, any rules specified under this section header- [*] will be applied to all the files including your *.js, *.css, etc. You can have specific rules for specific files for example [*.md] section header has the rules which should be applied on only files having .md as an extension. Blogathon-2021 Blogathon Installation Guide TechTips Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Import JSON Data into SQL Server? SQL Query to Convert Datetime to Date Python program to convert XML to Dictionary Scrape LinkedIn Using Selenium And Beautiful Soup in Python How to toggle password visibility in forms using Bootstrap-icons ? How to Install PIP on Windows ? Installation of Node.js on Linux How to install Jupyter Notebook on Windows? How to Install FFmpeg on Windows? How to Install OpenCV for Python on Windows?
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Sep, 2021" }, { "code": null, "e": 773, "s": 52, "text": "EditorConfig is a simple configuration file that contains a list of rules which can be applied to any IDE’s or code editors for proper formatting of code. But why use EditorConfig? Consider a scenario where your team is working on a project but the individual members of the team use a different IDE or code editor, these differences might result in inconsistent formatting applied to the code as each IDE/editor has its own configurations. EditorConfig solves this problem by having a single config file that is readable by all IDE’s and code editors with the help of some plugins/extensions. This tool is used extensively in many big projects including Angular, Bootstrap, Django, Nodejs, React, Vuejs, and a lot more." }, { "code": null, "e": 1013, "s": 773, "text": "You can have a common indentation-style (Tabs/Spaces) & indentation-sizeEditorConfig will help in configuring character encoding and line-endings (lf/crlf)It can also enforce the editor to have a new line at end of each file and many more." }, { "code": null, "e": 1086, "s": 1013, "text": "You can have a common indentation-style (Tabs/Spaces) & indentation-size" }, { "code": null, "e": 1170, "s": 1086, "text": "EditorConfig will help in configuring character encoding and line-endings (lf/crlf)" }, { "code": null, "e": 1255, "s": 1170, "text": "It can also enforce the editor to have a new line at end of each file and many more." }, { "code": null, "e": 1444, "s": 1255, "text": "To set up EditorConfig, you need to install the plugin/extension respective to your IDE/editor.Following editors doesn’t need any plugins as they come with native support for EditorConfig:" }, { "code": null, "e": 1453, "s": 1444, "text": "IntelliJ" }, { "code": null, "e": 1461, "s": 1453, "text": "Pycharm" }, { "code": null, "e": 1475, "s": 1461, "text": "Visual Studio" }, { "code": null, "e": 1503, "s": 1475, "text": "Github / Gitlab / Gitbucket" }, { "code": null, "e": 1606, "s": 1503, "text": "If you use the Editors listed below then you should install the plugin through their respective links:" }, { "code": null, "e": 1614, "s": 1606, "text": "VS Code" }, { "code": null, "e": 1619, "s": 1614, "text": "Atom" }, { "code": null, "e": 1627, "s": 1619, "text": "Eclipse" }, { "code": null, "e": 1638, "s": 1627, "text": "CodeBlocks" }, { "code": null, "e": 1647, "s": 1638, "text": "Netbeans" }, { "code": null, "e": 1660, "s": 1647, "text": "Sublime Text" }, { "code": null, "e": 1784, "s": 1660, "text": "Once the respective plugin/extension is installed create a file named `.editorconfig` in the root of your project directory" }, { "code": null, "e": 1986, "s": 1784, "text": "If you are using VS Code you can generate a new editorconfig file via the Explorer sidebar’s context menu by right-clicking in the folder where you’d like it to be and selecting Generate .editorconfig." }, { "code": null, "e": 2072, "s": 1986, "text": "A new .editorconfig file was generated with help of EditorConfig Extension in VS-Code" }, { "code": null, "e": 2351, "s": 2072, "text": "root = true : Whenever you open your Editor, the EditorConfig plugin will look for a file named `.editorconfig` in the directory of opened files and in every parent directory, but this search can be stopped if it reaches the root file path which can be specified with root=true." }, { "code": null, "e": 2414, "s": 2351, "text": "Comments : Comments in `.editorconfig` starts with ‘#’ or ‘;’." }, { "code": null, "e": 2629, "s": 2414, "text": "Section Headers : They start with ‘[‘ and end with ‘]’, they are used to select the specific files and apply rules to them. For example ‘[*.js]’ will apply all the rules to any file which has `.js` as an extension." }, { "code": null, "e": 2883, "s": 2629, "text": "Key-Value pairs : These key-value pairs are the rules(supported properties) that are located under Section Headers. For example ‘indent_size = 4` will set size of indentation to 4 space/tabs. You may find all the supported properties on their wiki page." }, { "code": null, "e": 3195, "s": 2883, "text": "# EditorConfig is awesome: https://EditorConfig.org\n\n# top-most EditorConfig file\nroot = true\n\n[*]\ncharset = utf-8\nend_of_line = lf\nindent_size = 4\nindent_style = space\ninsert_final_newline = true\nmax_line_length = 80\ntrim_trailing_whitespace = true\n\n[*.md]\nmax_line_length = 0\ntrim_trailing_whitespace = false " }, { "code": null, "e": 3557, "s": 3195, "text": "Here the root=true specify to the editor that it is the top-most EditorConfig file, any rules specified under this section header- [*] will be applied to all the files including your *.js, *.css, etc. You can have specific rules for specific files for example [*.md] section header has the rules which should be applied on only files having .md as an extension." }, { "code": null, "e": 3572, "s": 3557, "text": "Blogathon-2021" }, { "code": null, "e": 3582, "s": 3572, "text": "Blogathon" }, { "code": null, "e": 3601, "s": 3582, "text": "Installation Guide" }, { "code": null, "e": 3610, "s": 3601, "text": "TechTips" }, { "code": null, "e": 3627, "s": 3610, "text": "Web Technologies" }, { "code": null, "e": 3725, "s": 3627, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3766, "s": 3725, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 3804, "s": 3766, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 3848, "s": 3804, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 3908, "s": 3848, "text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python" }, { "code": null, "e": 3975, "s": 3908, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 4007, "s": 3975, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4040, "s": 4007, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4084, "s": 4040, "text": "How to install Jupyter Notebook on Windows?" }, { "code": null, "e": 4118, "s": 4084, "text": "How to Install FFmpeg on Windows?" } ]
How to make a word count in textarea using JavaScript ?
13 Oct, 2021 This article describes the approach to calculate the number of words in a given text input. This may be useful in scenarios where the user is recommended to enter a certain number of words and the word counter can keep track of the same. There are two approaches that are discussed below: Approach 1: Calculating the number of spaces present in the text This method relies on the number of spaces present in the input string to count the number of words as every word in a sentence is separated by a space. The function countWord() is defined which takes the text present in the textarea and counts the number of spaces present in it. The input text in the textarea is selected by using the getElementById() method. The drawback of this method is that multiple spaces between words would be counted as multiple words, hence it may cause the word count to be unreliable. Example: HTML <!DOCTYPE html><html> <body style="text-align: center;"> <h1 style="color: green"> GeeksforGeeks </h1> <p> Type in the textbox and click on the button to count the words </p> <textarea id="inputField" rows=10 cols="60"> </textarea> <br><br> <button onclick="countWords()"> Count Words </button> <br><br> <p> Word Count: <span id="show">0</span> </p> <script> function countWords() { // Get the input text value var text = document .getElementById("inputField").value; // Initialize the word counter var numWords = 0; // Loop through the text // and count spaces in it for (var i = 0; i < text.length; i++) { var currentCharacter = text[i]; // Check if the character is a space if (currentCharacter == " ") { numWords += 1; } } // Add 1 to make the count equal to // the number of words // (count of words = count of spaces + 1) numWords += 1; // Display it as output document.getElementById("show") .innerHTML = numWords; } </script></body> </html> Output: Approach 2: Separating the words based on spaces and then counting the number of words In this approach, we improve the drawback of the previous approach by splitting the words on the basis of the space character and then checking that each split is not only a space character. The countWord() function is called every time the user types in something into the text area using the oninput event handler on the text area. Example: HTML <!DOCTYPE html><html> <body style="text-align: center;"> <h1 style="color: green"> GeeksforGeeks </h1> <p> Type in the textbox to automatically count the words </p> <textarea id="word" oninput="countWord()" rows="10" cols="60"> </textarea> <br><br> <p> Word Count: <span id="show">0</span> </p> <script> function countWord() { // Get the input text value var words = document .getElementById("word").value; // Initialize the word counter var count = 0; // Split the words on each // space character var split = words.split(' '); // Loop through the words and // increase the counter when // each split word is not empty for (var i = 0; i < split.length; i++) { if (split[i] != "") { count += 1; } } // Display it as output document.getElementById("show") .innerHTML = count; } </script></body> </html> Output: Approach 3: Since the above two approaches were only able to count words when written in continuation giving spaces, but it was not able to count numbers when each word starts with a new line. So this approach will be able to count the words starting from the new line. Example: HTML <!DOCTYPE html><html> <body style="text-align: center"> <h1 style="color: green">GeeksforGeeks</h1> <p>Type in the textbox to automatically count the words</p> <textarea id="word" rows="10" cols="60"> </textarea> <br /><br /> <p> Word Count: <span id="show">0</span> </p> <script> document .querySelector("#word") .addEventListener("input", function countWord() { let res = []; let str = this.value.replace(/[\t\n\r\.\?\!]/gm, " ").split(" "); str.map((s) => { let trimStr = s.trim(); if (trimStr.length > 0) { res.push(trimStr); } }); document.querySelector("#show").innerText = res.length; }); </script> </body></html> Output: ghoshsuman0129 ayushkr07 javascript-functions JavaScript-Questions Picked Technical Scripter 2020 CSS HTML Technical Scripter Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Oct, 2021" }, { "code": null, "e": 343, "s": 54, "text": "This article describes the approach to calculate the number of words in a given text input. This may be useful in scenarios where the user is recommended to enter a certain number of words and the word counter can keep track of the same. There are two approaches that are discussed below:" }, { "code": null, "e": 409, "s": 343, "text": "Approach 1: Calculating the number of spaces present in the text " }, { "code": null, "e": 771, "s": 409, "text": "This method relies on the number of spaces present in the input string to count the number of words as every word in a sentence is separated by a space. The function countWord() is defined which takes the text present in the textarea and counts the number of spaces present in it. The input text in the textarea is selected by using the getElementById() method." }, { "code": null, "e": 925, "s": 771, "text": "The drawback of this method is that multiple spaces between words would be counted as multiple words, hence it may cause the word count to be unreliable." }, { "code": null, "e": 934, "s": 925, "text": "Example:" }, { "code": null, "e": 939, "s": 934, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align: center;\"> <h1 style=\"color: green\"> GeeksforGeeks </h1> <p> Type in the textbox and click on the button to count the words </p> <textarea id=\"inputField\" rows=10 cols=\"60\"> </textarea> <br><br> <button onclick=\"countWords()\"> Count Words </button> <br><br> <p> Word Count: <span id=\"show\">0</span> </p> <script> function countWords() { // Get the input text value var text = document .getElementById(\"inputField\").value; // Initialize the word counter var numWords = 0; // Loop through the text // and count spaces in it for (var i = 0; i < text.length; i++) { var currentCharacter = text[i]; // Check if the character is a space if (currentCharacter == \" \") { numWords += 1; } } // Add 1 to make the count equal to // the number of words // (count of words = count of spaces + 1) numWords += 1; // Display it as output document.getElementById(\"show\") .innerHTML = numWords; } </script></body> </html>", "e": 2260, "s": 939, "text": null }, { "code": null, "e": 2268, "s": 2260, "text": "Output:" }, { "code": null, "e": 2355, "s": 2268, "text": "Approach 2: Separating the words based on spaces and then counting the number of words" }, { "code": null, "e": 2689, "s": 2355, "text": "In this approach, we improve the drawback of the previous approach by splitting the words on the basis of the space character and then checking that each split is not only a space character. The countWord() function is called every time the user types in something into the text area using the oninput event handler on the text area." }, { "code": null, "e": 2698, "s": 2689, "text": "Example:" }, { "code": null, "e": 2703, "s": 2698, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align: center;\"> <h1 style=\"color: green\"> GeeksforGeeks </h1> <p> Type in the textbox to automatically count the words </p> <textarea id=\"word\" oninput=\"countWord()\" rows=\"10\" cols=\"60\"> </textarea> <br><br> <p> Word Count: <span id=\"show\">0</span> </p> <script> function countWord() { // Get the input text value var words = document .getElementById(\"word\").value; // Initialize the word counter var count = 0; // Split the words on each // space character var split = words.split(' '); // Loop through the words and // increase the counter when // each split word is not empty for (var i = 0; i < split.length; i++) { if (split[i] != \"\") { count += 1; } } // Display it as output document.getElementById(\"show\") .innerHTML = count; } </script></body> </html>", "e": 3835, "s": 2703, "text": null }, { "code": null, "e": 3843, "s": 3835, "text": "Output:" }, { "code": null, "e": 4113, "s": 3843, "text": "Approach 3: Since the above two approaches were only able to count words when written in continuation giving spaces, but it was not able to count numbers when each word starts with a new line. So this approach will be able to count the words starting from the new line." }, { "code": null, "e": 4122, "s": 4113, "text": "Example:" }, { "code": null, "e": 4127, "s": 4122, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align: center\"> <h1 style=\"color: green\">GeeksforGeeks</h1> <p>Type in the textbox to automatically count the words</p> <textarea id=\"word\" rows=\"10\" cols=\"60\"> </textarea> <br /><br /> <p> Word Count: <span id=\"show\">0</span> </p> <script> document .querySelector(\"#word\") .addEventListener(\"input\", function countWord() { let res = []; let str = this.value.replace(/[\\t\\n\\r\\.\\?\\!]/gm, \" \").split(\" \"); str.map((s) => { let trimStr = s.trim(); if (trimStr.length > 0) { res.push(trimStr); } }); document.querySelector(\"#show\").innerText = res.length; }); </script> </body></html>", "e": 4912, "s": 4127, "text": null }, { "code": null, "e": 4920, "s": 4912, "text": "Output:" }, { "code": null, "e": 4935, "s": 4920, "text": "ghoshsuman0129" }, { "code": null, "e": 4945, "s": 4935, "text": "ayushkr07" }, { "code": null, "e": 4966, "s": 4945, "text": "javascript-functions" }, { "code": null, "e": 4987, "s": 4966, "text": "JavaScript-Questions" }, { "code": null, "e": 4994, "s": 4987, "text": "Picked" }, { "code": null, "e": 5018, "s": 4994, "text": "Technical Scripter 2020" }, { "code": null, "e": 5022, "s": 5018, "text": "CSS" }, { "code": null, "e": 5027, "s": 5022, "text": "HTML" }, { "code": null, "e": 5046, "s": 5027, "text": "Technical Scripter" }, { "code": null, "e": 5063, "s": 5046, "text": "Web Technologies" }, { "code": null, "e": 5090, "s": 5063, "text": "Web technologies Questions" }, { "code": null, "e": 5095, "s": 5090, "text": "HTML" } ]
How to Find Duplicates Values Across Multiple Columns in SQL?
19 Nov, 2021 In SQL, sometimes we need to find duplicate entries across multiple columns in a table in a single query. We will use the GROUP BY and COUNT keywords to achieve this. For this, we use a specific kind of query shown in the below demonstration. For this article, we will be using the Microsoft SQL Server as our database and Select keyword. Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks. Query: CREATE DATABASE GeeksForGeeks Output: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Step 2: Use the GeeksForGeeks database. For this use the below command. Query: USE GeeksForGeeks Output: Step 3: Create a table of POSTINGS inside the database GeeksForGeeks. This table has 4 columns namely POSTING_ID, OFFICER_NAME, TEAM_SIZE and POSTING_LOCATION containing the id, the name of the officer, the size of the team and locations of the postings of Foreign Services in different countries. Query: CREATE TABLE POSTINGS( POSTING_ID INT, OFFICER_NAME VARCHAR(10), TEAM_SIZE INT, POSTING_LOCATION VARCHAR(10)); Output: Step 4: Describe the structure of the table POSTINGS. Query: EXEC SP_COLUMNS POSTINGS; Output: Step 5: Insert 5 rows into the POSTINGS table. Query: INSERT INTO POSTINGS VALUES(1,'RYAN',10,'GERMANY'); INSERT INTO POSTINGS VALUES(2,'JACK',6,'ROMANIA'); INSERT INTO POSTINGS VALUES(3,'JANE',4,'HAWAII'); INSERT INTO POSTINGS VALUES(4,'JIM',10,'GERMANY'); INSERT INTO POSTINGS VALUES(5,'TIM',10,'GERMANY'); INSERT INTO POSTINGS VALUES(6,'RYAN',11,'GERMANY'); INSERT INTO POSTINGS VALUES(7,'RYAN',10,'GERMANY'); INSERT INTO POSTINGS VALUES(8,'RYAN',10,'GERMANY'); INSERT INTO POSTINGS VALUES(9,'JACK',6,'CUBA'); INSERT INTO POSTINGS VALUES(10,'JACK',6,'HAITI'); Output: Step 6: Display all the rows of the POSTINGS table. Query: SELECT * FROM POSTINGS; Output: Step 7: Find duplicates in 3(multiple) columns i.e. in OFFICER_NAME, TEAM_SIZE and POSTING_LOCATION in the table POSTINGS. To achieve the, we need to group the records by these three columns and display those which have the count greater than 1 i.e. have matching values. Use the keywords GROUP BY and COUNT. Syntax: SELECT COLUMN_NAME1, COLUMN_NAME2, COLUMN_NAME3, COUNT(*) AS ALIAS FROM TABLE_NAME GROUP BY COLUMN_NAME1, COLUMN_NAME2, COLUMN_NAME3 HAVING COUNT(*)>1; Query: SELECT OFFICER_NAME, TEAM_SIZE, POSTING_LOCATION, COUNT(*) AS QTY FROM POSTINGS GROUP BY OFFICER_NAME, TEAM_SIZE, POSTING_LOCATION HAVING COUNT(*)>1; Output: Step 8: Find duplicates in 2(multiple) columns i.e. in TEAM_SIZE and POSTING_LOCATION in the table POSTINGS. Query: SELECT TEAM_SIZE, POSTING_LOCATION, COUNT(*) AS QTY FROM POSTINGS GROUP BY TEAM_SIZE, POSTING_LOCATION HAVING COUNT(*)>1; Output: Step 9: Find duplicates in 2(multiple) columns i.e. in OFFICER_NAME and TEAM_SIZE in the table POSTINGS. Query: SELECT OFFICER_NAME, TEAM_SIZE, COUNT(*) AS QTY FROM POSTINGS GROUP BY OFFICER_NAME, TEAM_SIZE HAVING COUNT(*)>1; Output: Picked SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Nov, 2021" }, { "code": null, "e": 393, "s": 54, "text": "In SQL, sometimes we need to find duplicate entries across multiple columns in a table in a single query. We will use the GROUP BY and COUNT keywords to achieve this. For this, we use a specific kind of query shown in the below demonstration. For this article, we will be using the Microsoft SQL Server as our database and Select keyword." }, { "code": null, "e": 493, "s": 393, "text": "Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks." }, { "code": null, "e": 500, "s": 493, "text": "Query:" }, { "code": null, "e": 530, "s": 500, "text": "CREATE DATABASE GeeksForGeeks" }, { "code": null, "e": 538, "s": 530, "text": "Output:" }, { "code": null, "e": 547, "s": 538, "text": "Chapters" }, { "code": null, "e": 574, "s": 547, "text": "descriptions off, selected" }, { "code": null, "e": 624, "s": 574, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 647, "s": 624, "text": "captions off, selected" }, { "code": null, "e": 655, "s": 647, "text": "English" }, { "code": null, "e": 679, "s": 655, "text": "This is a modal window." }, { "code": null, "e": 748, "s": 679, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 770, "s": 748, "text": "End of dialog window." }, { "code": null, "e": 842, "s": 770, "text": "Step 2: Use the GeeksForGeeks database. For this use the below command." }, { "code": null, "e": 849, "s": 842, "text": "Query:" }, { "code": null, "e": 867, "s": 849, "text": "USE GeeksForGeeks" }, { "code": null, "e": 875, "s": 867, "text": "Output:" }, { "code": null, "e": 1173, "s": 875, "text": "Step 3: Create a table of POSTINGS inside the database GeeksForGeeks. This table has 4 columns namely POSTING_ID, OFFICER_NAME, TEAM_SIZE and POSTING_LOCATION containing the id, the name of the officer, the size of the team and locations of the postings of Foreign Services in different countries." }, { "code": null, "e": 1180, "s": 1173, "text": "Query:" }, { "code": null, "e": 1291, "s": 1180, "text": "CREATE TABLE POSTINGS(\nPOSTING_ID INT,\nOFFICER_NAME VARCHAR(10),\nTEAM_SIZE INT,\nPOSTING_LOCATION VARCHAR(10));" }, { "code": null, "e": 1299, "s": 1291, "text": "Output:" }, { "code": null, "e": 1353, "s": 1299, "text": "Step 4: Describe the structure of the table POSTINGS." }, { "code": null, "e": 1360, "s": 1353, "text": "Query:" }, { "code": null, "e": 1386, "s": 1360, "text": "EXEC SP_COLUMNS POSTINGS;" }, { "code": null, "e": 1394, "s": 1386, "text": "Output:" }, { "code": null, "e": 1441, "s": 1394, "text": "Step 5: Insert 5 rows into the POSTINGS table." }, { "code": null, "e": 1448, "s": 1441, "text": "Query:" }, { "code": null, "e": 1957, "s": 1448, "text": "INSERT INTO POSTINGS VALUES(1,'RYAN',10,'GERMANY');\nINSERT INTO POSTINGS VALUES(2,'JACK',6,'ROMANIA');\nINSERT INTO POSTINGS VALUES(3,'JANE',4,'HAWAII');\nINSERT INTO POSTINGS VALUES(4,'JIM',10,'GERMANY');\nINSERT INTO POSTINGS VALUES(5,'TIM',10,'GERMANY');\nINSERT INTO POSTINGS VALUES(6,'RYAN',11,'GERMANY');\nINSERT INTO POSTINGS VALUES(7,'RYAN',10,'GERMANY');\nINSERT INTO POSTINGS VALUES(8,'RYAN',10,'GERMANY');\nINSERT INTO POSTINGS VALUES(9,'JACK',6,'CUBA');\nINSERT INTO POSTINGS VALUES(10,'JACK',6,'HAITI');" }, { "code": null, "e": 1965, "s": 1957, "text": "Output:" }, { "code": null, "e": 2017, "s": 1965, "text": "Step 6: Display all the rows of the POSTINGS table." }, { "code": null, "e": 2024, "s": 2017, "text": "Query:" }, { "code": null, "e": 2048, "s": 2024, "text": "SELECT * FROM POSTINGS;" }, { "code": null, "e": 2056, "s": 2048, "text": "Output:" }, { "code": null, "e": 2365, "s": 2056, "text": "Step 7: Find duplicates in 3(multiple) columns i.e. in OFFICER_NAME, TEAM_SIZE and POSTING_LOCATION in the table POSTINGS. To achieve the, we need to group the records by these three columns and display those which have the count greater than 1 i.e. have matching values. Use the keywords GROUP BY and COUNT." }, { "code": null, "e": 2373, "s": 2365, "text": "Syntax:" }, { "code": null, "e": 2526, "s": 2373, "text": "SELECT COLUMN_NAME1, COLUMN_NAME2, \nCOLUMN_NAME3, COUNT(*) AS ALIAS\nFROM TABLE_NAME\nGROUP BY COLUMN_NAME1, COLUMN_NAME2,\nCOLUMN_NAME3 HAVING COUNT(*)>1;" }, { "code": null, "e": 2533, "s": 2526, "text": "Query:" }, { "code": null, "e": 2683, "s": 2533, "text": "SELECT OFFICER_NAME, TEAM_SIZE,\nPOSTING_LOCATION, COUNT(*) AS QTY\nFROM POSTINGS\nGROUP BY OFFICER_NAME, TEAM_SIZE,\nPOSTING_LOCATION HAVING COUNT(*)>1;" }, { "code": null, "e": 2691, "s": 2683, "text": "Output:" }, { "code": null, "e": 2800, "s": 2691, "text": "Step 8: Find duplicates in 2(multiple) columns i.e. in TEAM_SIZE and POSTING_LOCATION in the table POSTINGS." }, { "code": null, "e": 2807, "s": 2800, "text": "Query:" }, { "code": null, "e": 2931, "s": 2807, "text": "SELECT TEAM_SIZE, POSTING_LOCATION, \nCOUNT(*) AS QTY\nFROM POSTINGS\nGROUP BY TEAM_SIZE, POSTING_LOCATION\n HAVING COUNT(*)>1;" }, { "code": null, "e": 2939, "s": 2931, "text": "Output:" }, { "code": null, "e": 3044, "s": 2939, "text": "Step 9: Find duplicates in 2(multiple) columns i.e. in OFFICER_NAME and TEAM_SIZE in the table POSTINGS." }, { "code": null, "e": 3051, "s": 3044, "text": "Query:" }, { "code": null, "e": 3167, "s": 3051, "text": "SELECT OFFICER_NAME, TEAM_SIZE, \nCOUNT(*) AS QTY\nFROM POSTINGS\nGROUP BY OFFICER_NAME, \nTEAM_SIZE HAVING COUNT(*)>1;" }, { "code": null, "e": 3175, "s": 3167, "text": "Output:" }, { "code": null, "e": 3182, "s": 3175, "text": "Picked" }, { "code": null, "e": 3193, "s": 3182, "text": "SQL-Server" }, { "code": null, "e": 3197, "s": 3193, "text": "SQL" }, { "code": null, "e": 3201, "s": 3197, "text": "SQL" } ]
In-place replace multiple occurrences of a pattern
01 Jul, 2022 Given a string and a pattern, replace multiple occurrences of a pattern by character ‘X’. The conversion should be in-place and the solution should replace multiple consecutive (and non-overlapping) occurrences of a pattern by a single ‘X’. String – GeeksForGeeks Pattern – Geeks Output: XforX String – GeeksGeeks Pattern – Geeks Output: X String – aaaa Pattern – aa Output: X String – aaaaa Pattern – aa Output: Xa The idea is to maintain two index i and j for in-place replacement. Index i always points to next character in the output string. Index j traverses the string and searches for one or more pattern match. If a match is found, we put character ‘X’ at index i and increment index i by 1 and index j by length of the pattern. Index i is increment only once if we find multiple consecutive occurrences of the pattern. If the pattern is not found, we copy current character at index j to index i and increment both i and j by 1. Since pattern length is always more than equal to 1 and replacement is only 1 character long, we would never overwrite unprocessed characters i.e j >= i is invariant. Implementation: C++ Python3 Javascript // C++ program to in-place replace multiple// occurrences of a pattern by character ‘X’#include <bits/stdc++.h>using namespace std; // returns true if pattern is prefix of strbool compare(char* str, char* pattern){ for (int i = 0; pattern[i]; i++) if (str[i] != pattern[i]) return false; return true;} // Function to in-place replace multiple// occurrences of a pattern by character ‘X’void replacePattern(char* str, char* pattern){ // If pattern is null or empty string, // nothing needs to be done if (pattern == NULL) return; int len = strlen(pattern); if (len == 0) return; int i = 0, j = 0; int count; // for each character while (str[j]) { count = 0; // compare str[j..j+len] with pattern while (compare(str + j, pattern)) { // increment j by length of pattern j = j + len; count++; } // If single or multiple occurrences of pattern // is found, replace it by character 'X' if (count > 0) str[i++] = 'X'; // copy character at current position j // to position i and increment i and j if (str[j]) str[i++] = str[j++]; } // add a null character to terminate string str[i] = '\0';} // Driver codeint main(){ char str[] = "GeeksforGeeks"; char pattern[] = "Geeks"; replacePattern(str, pattern); cout << str; return 0;} # Python3 program to in-place replace multiple# occurrences of a pattern by character ‘X’ # returns true if pattern is prefix of Strdef compare(Str, pattern): if(len(Str) != len(pattern)): return False for i in range(len(pattern)): if (Str[i] != pattern[i]): return False return True # Function to in-place replace multiple# occurrences of a pattern by character ‘X’def replacePattern(Str,pattern): # If pattern is null or empty String, # nothing needs to be done if (pattern == ""): return Len = len(pattern) if (Len == 0): return i, j = 0, 0 # for each character while (j < len(Str)): count = 0 # compare Str[j..j+len] with pattern while (compare(Str[j:j+Len], pattern)): # increment j by length of pattern j = j + Len count += 1 # If single or multiple occurrences of pattern # is found, replace it by character 'X' if (count > 0): Str = Str[0:i] + 'X' + Str[i+1:] i += 1 # copy character at current position j # to position i and increment i and j if (j<len(Str)): Str = Str[0:i] + Str[j] + Str[i+1:] i += 1 j += 1 # add a null character to terminate String Str = Str[0:i] return Str # Driver codeStr = "GeeksforGeeks"pattern = "Geeks" Str = replacePattern(Str, pattern)print(Str) # This code is contributed by shinjanpatra <script> // JavaScript program to in-place replace multiple// occurrences of a pattern by character ‘X’ // returns true if pattern is prefix of strfunction compare(str, pattern){ for (let i = 0; i<pattern.length; i++) if (str[i] != pattern[i]) return false; return true;} // Function to in-place replace multiple// occurrences of a pattern by character ‘X’function replacePattern(str,pattern){ // If pattern is null or empty string, // nothing needs to be done if (pattern == "") return; let len = pattern.length; if (len == 0) return; let i = 0, j = 0; let count; // for each character while (j<str.length) { count = 0; // compare str[j..j+len] with pattern while (compare(str.substring(j,j+len), pattern)) { // increment j by length of pattern j = j + len; count++; } // If single or multiple occurrences of pattern // is found, replace it by character 'X' if (count > 0){ str = str.substring(0,i) + 'X' + str.substring(i+1,) i++ } // copy character at current position j // to position i and increment i and j if (j<str.length){ str = str.substring(0,i) + str[j] + str.substring(i+1,) i++;j++ } } // add a null character to terminate string str = str.substring(0,i); return str;} // Driver codelet str = "GeeksforGeeks";let pattern = "Geeks"; str = replacePattern(str, pattern);document.write(str,"</br>"); // This code is contributed by shinjanpatra </script> XforX Time complexity: O(n*m) where n is length of string and m is length of the pattern. Auxiliary Space: O(1) Implementation using STL The idea of this implementation is to use the STL in-built functions to search for pattern string in main string and then erasing it from the main string C++ // C++ program to in-place replace multiple// occurrences of a pattern by character ‘X’#include <bits/stdc++.h>using namespace std; // Function to in-place replace multiple// occurrences of a pattern by character ‘X’void replacePattern(string str, string pattern){ // making an iterator for string str string::iterator it = str.begin(); // run this loop until iterator reaches end of string while (it != str.end()) { // searching the first index in string str where // the first occurrence of string pattern occurs it = search(str.begin(), str.end(), pattern.begin(), pattern.end()); // checking if iterator is not pointing to end of the // string str if (it != str.end()) { // erasing the full pattern string from that iterator // position in string str str.erase(it, it + pattern.size()); // inserting 'X' at that iterator position str.insert(it, 'X'); } } // this loop removes consecutive 'X' in string s // Example: GeeksGeeksforGeeks was changed to 'XXforX' // running this loop will change it to 'XforX' for (int i = 0; i < str.size() - 1; i++) { if (str[i] == 'X' && str[i + 1] == 'X') { // removing 'X' at position i in string str str.erase(str.begin() + i); i--; // i-- because one character was deleted // so repositioning i } } cout << str;} // Driver codeint main(){ string str = "GeeksforGeeks"; string pattern = "Geeks"; replacePattern(str, pattern); return 0;} XforX Time Complexity: O(n*m)Auxiliary Space: O(1) This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. md1844 surindertarika1234 geekygirl2001 shinjanpatra hardikkoriintern Amazon FactSet Searching Strings Amazon FactSet Searching Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Jul, 2022" }, { "code": null, "e": 295, "s": 54, "text": "Given a string and a pattern, replace multiple occurrences of a pattern by character ‘X’. The conversion should be in-place and the solution should replace multiple consecutive (and non-overlapping) occurrences of a pattern by a single ‘X’." }, { "code": null, "e": 474, "s": 295, "text": "String – GeeksForGeeks\nPattern – Geeks\nOutput: XforX\n \nString – GeeksGeeks\nPattern – Geeks\nOutput: X\n\nString – aaaa\nPattern – aa\nOutput: X\n\nString – aaaaa\nPattern – aa\nOutput: Xa" }, { "code": null, "e": 1163, "s": 474, "text": "The idea is to maintain two index i and j for in-place replacement. Index i always points to next character in the output string. Index j traverses the string and searches for one or more pattern match. If a match is found, we put character ‘X’ at index i and increment index i by 1 and index j by length of the pattern. Index i is increment only once if we find multiple consecutive occurrences of the pattern. If the pattern is not found, we copy current character at index j to index i and increment both i and j by 1. Since pattern length is always more than equal to 1 and replacement is only 1 character long, we would never overwrite unprocessed characters i.e j >= i is invariant." }, { "code": null, "e": 1179, "s": 1163, "text": "Implementation:" }, { "code": null, "e": 1183, "s": 1179, "text": "C++" }, { "code": null, "e": 1191, "s": 1183, "text": "Python3" }, { "code": null, "e": 1202, "s": 1191, "text": "Javascript" }, { "code": "// C++ program to in-place replace multiple// occurrences of a pattern by character ‘X’#include <bits/stdc++.h>using namespace std; // returns true if pattern is prefix of strbool compare(char* str, char* pattern){ for (int i = 0; pattern[i]; i++) if (str[i] != pattern[i]) return false; return true;} // Function to in-place replace multiple// occurrences of a pattern by character ‘X’void replacePattern(char* str, char* pattern){ // If pattern is null or empty string, // nothing needs to be done if (pattern == NULL) return; int len = strlen(pattern); if (len == 0) return; int i = 0, j = 0; int count; // for each character while (str[j]) { count = 0; // compare str[j..j+len] with pattern while (compare(str + j, pattern)) { // increment j by length of pattern j = j + len; count++; } // If single or multiple occurrences of pattern // is found, replace it by character 'X' if (count > 0) str[i++] = 'X'; // copy character at current position j // to position i and increment i and j if (str[j]) str[i++] = str[j++]; } // add a null character to terminate string str[i] = '\\0';} // Driver codeint main(){ char str[] = \"GeeksforGeeks\"; char pattern[] = \"Geeks\"; replacePattern(str, pattern); cout << str; return 0;}", "e": 2646, "s": 1202, "text": null }, { "code": "# Python3 program to in-place replace multiple# occurrences of a pattern by character ‘X’ # returns true if pattern is prefix of Strdef compare(Str, pattern): if(len(Str) != len(pattern)): return False for i in range(len(pattern)): if (Str[i] != pattern[i]): return False return True # Function to in-place replace multiple# occurrences of a pattern by character ‘X’def replacePattern(Str,pattern): # If pattern is null or empty String, # nothing needs to be done if (pattern == \"\"): return Len = len(pattern) if (Len == 0): return i, j = 0, 0 # for each character while (j < len(Str)): count = 0 # compare Str[j..j+len] with pattern while (compare(Str[j:j+Len], pattern)): # increment j by length of pattern j = j + Len count += 1 # If single or multiple occurrences of pattern # is found, replace it by character 'X' if (count > 0): Str = Str[0:i] + 'X' + Str[i+1:] i += 1 # copy character at current position j # to position i and increment i and j if (j<len(Str)): Str = Str[0:i] + Str[j] + Str[i+1:] i += 1 j += 1 # add a null character to terminate String Str = Str[0:i] return Str # Driver codeStr = \"GeeksforGeeks\"pattern = \"Geeks\" Str = replacePattern(Str, pattern)print(Str) # This code is contributed by shinjanpatra", "e": 4136, "s": 2646, "text": null }, { "code": "<script> // JavaScript program to in-place replace multiple// occurrences of a pattern by character ‘X’ // returns true if pattern is prefix of strfunction compare(str, pattern){ for (let i = 0; i<pattern.length; i++) if (str[i] != pattern[i]) return false; return true;} // Function to in-place replace multiple// occurrences of a pattern by character ‘X’function replacePattern(str,pattern){ // If pattern is null or empty string, // nothing needs to be done if (pattern == \"\") return; let len = pattern.length; if (len == 0) return; let i = 0, j = 0; let count; // for each character while (j<str.length) { count = 0; // compare str[j..j+len] with pattern while (compare(str.substring(j,j+len), pattern)) { // increment j by length of pattern j = j + len; count++; } // If single or multiple occurrences of pattern // is found, replace it by character 'X' if (count > 0){ str = str.substring(0,i) + 'X' + str.substring(i+1,) i++ } // copy character at current position j // to position i and increment i and j if (j<str.length){ str = str.substring(0,i) + str[j] + str.substring(i+1,) i++;j++ } } // add a null character to terminate string str = str.substring(0,i); return str;} // Driver codelet str = \"GeeksforGeeks\";let pattern = \"Geeks\"; str = replacePattern(str, pattern);document.write(str,\"</br>\"); // This code is contributed by shinjanpatra </script>", "e": 5746, "s": 4136, "text": null }, { "code": null, "e": 5752, "s": 5746, "text": "XforX" }, { "code": null, "e": 5836, "s": 5752, "text": "Time complexity: O(n*m) where n is length of string and m is length of the pattern." }, { "code": null, "e": 5859, "s": 5836, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 5884, "s": 5859, "text": "Implementation using STL" }, { "code": null, "e": 6040, "s": 5884, "text": "The idea of this implementation is to use the STL in-built functions \nto search for pattern string in main string and then erasing it \nfrom the main string" }, { "code": null, "e": 6044, "s": 6040, "text": "C++" }, { "code": "// C++ program to in-place replace multiple// occurrences of a pattern by character ‘X’#include <bits/stdc++.h>using namespace std; // Function to in-place replace multiple// occurrences of a pattern by character ‘X’void replacePattern(string str, string pattern){ // making an iterator for string str string::iterator it = str.begin(); // run this loop until iterator reaches end of string while (it != str.end()) { // searching the first index in string str where // the first occurrence of string pattern occurs it = search(str.begin(), str.end(), pattern.begin(), pattern.end()); // checking if iterator is not pointing to end of the // string str if (it != str.end()) { // erasing the full pattern string from that iterator // position in string str str.erase(it, it + pattern.size()); // inserting 'X' at that iterator position str.insert(it, 'X'); } } // this loop removes consecutive 'X' in string s // Example: GeeksGeeksforGeeks was changed to 'XXforX' // running this loop will change it to 'XforX' for (int i = 0; i < str.size() - 1; i++) { if (str[i] == 'X' && str[i + 1] == 'X') { // removing 'X' at position i in string str str.erase(str.begin() + i); i--; // i-- because one character was deleted // so repositioning i } } cout << str;} // Driver codeint main(){ string str = \"GeeksforGeeks\"; string pattern = \"Geeks\"; replacePattern(str, pattern); return 0;}", "e": 7631, "s": 6044, "text": null }, { "code": null, "e": 7637, "s": 7631, "text": "XforX" }, { "code": null, "e": 7682, "s": 7637, "text": "Time Complexity: O(n*m)Auxiliary Space: O(1)" }, { "code": null, "e": 7948, "s": 7682, "text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 7955, "s": 7948, "text": "md1844" }, { "code": null, "e": 7974, "s": 7955, "text": "surindertarika1234" }, { "code": null, "e": 7988, "s": 7974, "text": "geekygirl2001" }, { "code": null, "e": 8001, "s": 7988, "text": "shinjanpatra" }, { "code": null, "e": 8018, "s": 8001, "text": "hardikkoriintern" }, { "code": null, "e": 8025, "s": 8018, "text": "Amazon" }, { "code": null, "e": 8033, "s": 8025, "text": "FactSet" }, { "code": null, "e": 8043, "s": 8033, "text": "Searching" }, { "code": null, "e": 8051, "s": 8043, "text": "Strings" }, { "code": null, "e": 8058, "s": 8051, "text": "Amazon" }, { "code": null, "e": 8066, "s": 8058, "text": "FactSet" }, { "code": null, "e": 8076, "s": 8066, "text": "Searching" }, { "code": null, "e": 8084, "s": 8076, "text": "Strings" } ]
Python | Get total keys in dictionary
02 Aug, 2019 Sometimes, while working with Python dictionaries, one can come in a problem in which one needs to get the exact number of keys that are present in whole of dictionaries including ones that are nested. Let’s discuss certain ways in which this task can be performed. Method #1 : Using recursion + items() + sum() + len()This task can be performed using the combination of above functions. In this, we check if a nested is a dictionary of not and then extract it’s keys using items() and then sum of find length of it using respective functions. # Python3 code to demonstrate working of# Get total keys in dictionary# Using recursion + items() + sum() + len() # Utility function to perform task def total_keys(test_dict): return (0 if not isinstance(test_dict, dict) else len(test_dict) + sum(total_keys(val) for val in test_dict.values())) # Initialize dictionarytest_dict = { 'gfg' : { 'is' : 1, 'best' : { 'for' : {'geeks' :4}}}} # Printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Using recursion + items() + sum() + len()# Get total keys in dictionaryres = total_keys(test_dict) # printing result print("Number of keys in dictionary is : " + str(res)) The original dictionary is : {‘gfg’: {‘best’: {‘for’: {‘geeks’: 4}}, ‘is’: 1}}Number of keys in dictionary is : 5 Method #2 : Using yield() + recursionThis task can also be performed using the combination of above functions. This is just another way to perform this task. The intermediate result is returned, and hence this is a more efficient method of the 2. # Python3 code to demonstrate working of# Get total keys in dictionaryfrom collections import Mapping # Utility function to perform taskdef total_keys(test_dict): for key, value in test_dict.items(): if isinstance(value, Mapping): yield from total_keys(value) yield len(test_dict) # Initialize dictionarytest_dict = { 'gfg' : { 'is' : 1, 'best' : { 'for' : {'geeks' :4}}}} # Printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Using yield() + recursion# Get total keys in dictionaryres = sum(total_keys(test_dict)) # printing result print("Number of keys in dictionary is : " + str(res)) The original dictionary is : {‘gfg’: {‘best’: {‘for’: {‘geeks’: 4}}, ‘is’: 1}}Number of keys in dictionary is : 5 Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Aug, 2019" }, { "code": null, "e": 294, "s": 28, "text": "Sometimes, while working with Python dictionaries, one can come in a problem in which one needs to get the exact number of keys that are present in whole of dictionaries including ones that are nested. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 572, "s": 294, "text": "Method #1 : Using recursion + items() + sum() + len()This task can be performed using the combination of above functions. In this, we check if a nested is a dictionary of not and then extract it’s keys using items() and then sum of find length of it using respective functions." }, { "code": "# Python3 code to demonstrate working of# Get total keys in dictionary# Using recursion + items() + sum() + len() # Utility function to perform task def total_keys(test_dict): return (0 if not isinstance(test_dict, dict) else len(test_dict) + sum(total_keys(val) for val in test_dict.values())) # Initialize dictionarytest_dict = { 'gfg' : { 'is' : 1, 'best' : { 'for' : {'geeks' :4}}}} # Printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Using recursion + items() + sum() + len()# Get total keys in dictionaryres = total_keys(test_dict) # printing result print(\"Number of keys in dictionary is : \" + str(res))", "e": 1232, "s": 572, "text": null }, { "code": null, "e": 1346, "s": 1232, "text": "The original dictionary is : {‘gfg’: {‘best’: {‘for’: {‘geeks’: 4}}, ‘is’: 1}}Number of keys in dictionary is : 5" }, { "code": null, "e": 1595, "s": 1348, "text": "Method #2 : Using yield() + recursionThis task can also be performed using the combination of above functions. This is just another way to perform this task. The intermediate result is returned, and hence this is a more efficient method of the 2." }, { "code": "# Python3 code to demonstrate working of# Get total keys in dictionaryfrom collections import Mapping # Utility function to perform taskdef total_keys(test_dict): for key, value in test_dict.items(): if isinstance(value, Mapping): yield from total_keys(value) yield len(test_dict) # Initialize dictionarytest_dict = { 'gfg' : { 'is' : 1, 'best' : { 'for' : {'geeks' :4}}}} # Printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Using yield() + recursion# Get total keys in dictionaryres = sum(total_keys(test_dict)) # printing result print(\"Number of keys in dictionary is : \" + str(res))", "e": 2251, "s": 1595, "text": null }, { "code": null, "e": 2365, "s": 2251, "text": "The original dictionary is : {‘gfg’: {‘best’: {‘for’: {‘geeks’: 4}}, ‘is’: 1}}Number of keys in dictionary is : 5" }, { "code": null, "e": 2392, "s": 2365, "text": "Python dictionary-programs" }, { "code": null, "e": 2399, "s": 2392, "text": "Python" }, { "code": null, "e": 2415, "s": 2399, "text": "Python Programs" } ]
jQuery | dblclick() with Examples
12 Feb, 2019 The dblclick() is an inbuilt method in jQuery which is used to trigger the double-click event to occur. This method occurs when the selected element will be double clicked.Syntax: $(selector).dblclick(args); Here “selector” is the selected element.Parameter: It accepts an optional parameter “args” which specifies a function that do a specific task after double clicking.Return Value: It returns some function when the selected element is double-clicked. <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script> <!-- jQuery code to show dbclick method --> $(document).ready(function() { $("div").click(function() { $("div").dblclick(); }); </script> <style> div { display: block; width: 370px; padding: 10px; font-size: 25px; border: 2px solid green; } </style></head> <body> <!-- click on this div and a pop will appear --> <div ondblclick="alert('dblclick event has been triggered') ">Click me to trigger dblclick event</div></body> </html> Output:Before double clicking the “Click me to trigger dblclick event” button-After double clicking the “Click me to trigger dblclick event” button- Code #2:In the below code, function is passed to dblclick() method. <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script> <!-- jQuery code to show dbclick method --> $(document).ready(function() { $("button").dblclick(function() { $("p").fadeOut(); }); }); </script> <style> p { display: block; padding: 20px; color: gree; width: 300px; border: 2px solid green; font-size: 25px; } </style></head> <body> <p>Welcome to GeeksforGeeks !</p> <!-- click on this button and above paragraph will disappear --> <button> Click Me! </button></body> </html> Output:Before double clicking the “Click Me” button- After double clicking the “Click Me” button- jQuery-Events JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Feb, 2019" }, { "code": null, "e": 208, "s": 28, "text": "The dblclick() is an inbuilt method in jQuery which is used to trigger the double-click event to occur. This method occurs when the selected element will be double clicked.Syntax:" }, { "code": null, "e": 237, "s": 208, "text": "$(selector).dblclick(args);\n" }, { "code": null, "e": 485, "s": 237, "text": "Here “selector” is the selected element.Parameter: It accepts an optional parameter “args” which specifies a function that do a specific task after double clicking.Return Value: It returns some function when the selected element is double-clicked." }, { "code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <script> <!-- jQuery code to show dbclick method --> $(document).ready(function() { $(\"div\").click(function() { $(\"div\").dblclick(); }); </script> <style> div { display: block; width: 370px; padding: 10px; font-size: 25px; border: 2px solid green; } </style></head> <body> <!-- click on this div and a pop will appear --> <div ondblclick=\"alert('dblclick event has been triggered') \">Click me to trigger dblclick event</div></body> </html>", "e": 1230, "s": 485, "text": null }, { "code": null, "e": 1379, "s": 1230, "text": "Output:Before double clicking the “Click me to trigger dblclick event” button-After double clicking the “Click me to trigger dblclick event” button-" }, { "code": null, "e": 1447, "s": 1379, "text": "Code #2:In the below code, function is passed to dblclick() method." }, { "code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <script> <!-- jQuery code to show dbclick method --> $(document).ready(function() { $(\"button\").dblclick(function() { $(\"p\").fadeOut(); }); }); </script> <style> p { display: block; padding: 20px; color: gree; width: 300px; border: 2px solid green; font-size: 25px; } </style></head> <body> <p>Welcome to GeeksforGeeks !</p> <!-- click on this button and above paragraph will disappear --> <button> Click Me! </button></body> </html>", "e": 2165, "s": 1447, "text": null }, { "code": null, "e": 2218, "s": 2165, "text": "Output:Before double clicking the “Click Me” button-" }, { "code": null, "e": 2263, "s": 2218, "text": "After double clicking the “Click Me” button-" }, { "code": null, "e": 2277, "s": 2263, "text": "jQuery-Events" }, { "code": null, "e": 2288, "s": 2277, "text": "JavaScript" }, { "code": null, "e": 2295, "s": 2288, "text": "JQuery" } ]
How to move an image with the mouse in PyGame?
26 Nov, 2021 Pygame is a Python library that is used to create cross-platform video games. The games created by Pygame can be easily run through any of the input devices such as a mouse, keyboard, and joystick. Do you want to make a game that runs through mouse controls? Don’t you know how to move the image with the mouse in it? Don’t worry, what you need to do is to declare the two values, i.e., running and moving. Once declared values, set what your app should do when it is in running state. Read the article given below to know more in detail. Step 1: First, import the library pygame. import pygame from pygame.locals import * Step 2: Now, take the colors as input that we want to use in the game. color_1 = #RGB value of color 1 color_2 = #RGB value of color 2 color_n = #RGB value of color n Step 3: Then, construct a GUI game. pygame.init() Step 4: Further, set the dimensions of your GUI game. w, h = #Width dimension, #Height dimension screen = pygame.display.set_mode((w, h)) Step 5: Next, take the image as input which you want to move with the mouse img = pygame.image.load('#Enter the image') img.convert() Step 6: Moreover, you can make your image look attractive by adding rectangle borders around it. rect = img.get_rect() rect.center = w//2, h//2 Step 7: Later on, set the running value for running the game and moving value for moving the image. running = True moving = False Step 8: Set the things which you want your app to do when in running state. while running: for event in pygame.event.get(): Step 8.1: Once the app is in a running state, make it quit if the user wants to quit. if event.type == QUIT: running = False Step 8.2: In case, the user doesn’t want to quit, move your image around the dimensions of the GUI app. elif event.type == MOUSEBUTTONDOWN: if rect.collidepoint(event.pos): moving = True Step 8.3: Next, set the moving value as False if you want to move the image only with the mouse click else set moving as True if you want to move the image without the mouse click. elif event.type == MOUSEBUTTONUP: moving = False Step 8.4: Further, set your image in a moving state if it has been once moved. elif event.type == MOUSEMOTION and moving: rect.move_ip(event.rel) Step 9: Next, you need to set the screen color and image on the screen. screen.fill(YELLOW) screen.blit(img, rect) Step 10: Further, make your image look attractive by constructing the border to the image. pygame.draw.rect(screen, BLUE, rect, 2) Step 11: Furthermore, update the changes done in the GUI game. pygame.display.update() Step 12: Finally, quit the GUI game. pygame.quit() Below is the implementation. Python # Python program to move the image# with the mouse # Import the library pygameimport pygamefrom pygame.locals import * # Take colors inputYELLOW = (255, 255, 0)BLUE = (0, 0, 255) # Construct the GUI gamepygame.init() # Set dimensions of game GUIw, h = 640, 350screen = pygame.display.set_mode((w, h)) # Take image as inputimg = pygame.image.load('geek.jpg')img.convert() # Draw rectangle around the imagerect = img.get_rect()rect.center = w//2, h//2 # Set running and moving valuesrunning = Truemoving = False # Setting what happens when game# is in running statewhile running: for event in pygame.event.get(): # Close if the user quits the # game if event.type == QUIT: running = False # Making the image move elif event.type == MOUSEBUTTONDOWN: if rect.collidepoint(event.pos): moving = True # Set moving as False if you want # to move the image only with the # mouse click # Set moving as True if you want # to move the image without the # mouse click elif event.type == MOUSEBUTTONUP: moving = False # Make your image move continuously elif event.type == MOUSEMOTION and moving: rect.move_ip(event.rel) # Set screen color and image on screen screen.fill(YELLOW) screen.blit(img, rect) # Construct the border to the image pygame.draw.rect(screen, BLUE, rect, 2) # Update the GUI pygame pygame.display.update() # Quit the GUI gamepygame.quit() Output: kalrap615 Picked Python-PyGame 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 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": "\n26 Nov, 2021" }, { "code": null, "e": 567, "s": 28, "text": "Pygame is a Python library that is used to create cross-platform video games. The games created by Pygame can be easily run through any of the input devices such as a mouse, keyboard, and joystick. Do you want to make a game that runs through mouse controls? Don’t you know how to move the image with the mouse in it? Don’t worry, what you need to do is to declare the two values, i.e., running and moving. Once declared values, set what your app should do when it is in running state. Read the article given below to know more in detail." }, { "code": null, "e": 609, "s": 567, "text": "Step 1: First, import the library pygame." }, { "code": null, "e": 651, "s": 609, "text": "import pygame\nfrom pygame.locals import *" }, { "code": null, "e": 722, "s": 651, "text": "Step 2: Now, take the colors as input that we want to use in the game." }, { "code": null, "e": 818, "s": 722, "text": "color_1 = #RGB value of color 1\ncolor_2 = #RGB value of color 2\ncolor_n = #RGB value of color n" }, { "code": null, "e": 854, "s": 818, "text": "Step 3: Then, construct a GUI game." }, { "code": null, "e": 868, "s": 854, "text": "pygame.init()" }, { "code": null, "e": 923, "s": 868, "text": "Step 4: Further, set the dimensions of your GUI game. " }, { "code": null, "e": 1007, "s": 923, "text": "w, h = #Width dimension, #Height dimension\nscreen = pygame.display.set_mode((w, h))" }, { "code": null, "e": 1083, "s": 1007, "text": "Step 5: Next, take the image as input which you want to move with the mouse" }, { "code": null, "e": 1141, "s": 1083, "text": "img = pygame.image.load('#Enter the image')\nimg.convert()" }, { "code": null, "e": 1238, "s": 1141, "text": "Step 6: Moreover, you can make your image look attractive by adding rectangle borders around it." }, { "code": null, "e": 1285, "s": 1238, "text": "rect = img.get_rect()\nrect.center = w//2, h//2" }, { "code": null, "e": 1385, "s": 1285, "text": "Step 7: Later on, set the running value for running the game and moving value for moving the image." }, { "code": null, "e": 1415, "s": 1385, "text": "running = True\nmoving = False" }, { "code": null, "e": 1491, "s": 1415, "text": "Step 8: Set the things which you want your app to do when in running state." }, { "code": null, "e": 1542, "s": 1491, "text": "while running:\n for event in pygame.event.get():" }, { "code": null, "e": 1628, "s": 1542, "text": "Step 8.1: Once the app is in a running state, make it quit if the user wants to quit." }, { "code": null, "e": 1685, "s": 1628, "text": " if event.type == QUIT:\n running = False" }, { "code": null, "e": 1789, "s": 1685, "text": "Step 8.2: In case, the user doesn’t want to quit, move your image around the dimensions of the GUI app." }, { "code": null, "e": 1905, "s": 1789, "text": " elif event.type == MOUSEBUTTONDOWN:\n if rect.collidepoint(event.pos):\n moving = True " }, { "code": null, "e": 2086, "s": 1905, "text": "Step 8.3: Next, set the moving value as False if you want to move the image only with the mouse click else set moving as True if you want to move the image without the mouse click." }, { "code": null, "e": 2163, "s": 2086, "text": " elif event.type == MOUSEBUTTONUP: \n moving = False" }, { "code": null, "e": 2242, "s": 2163, "text": "Step 8.4: Further, set your image in a moving state if it has been once moved." }, { "code": null, "e": 2329, "s": 2242, "text": " elif event.type == MOUSEMOTION and moving:\n rect.move_ip(event.rel) " }, { "code": null, "e": 2401, "s": 2329, "text": "Step 9: Next, you need to set the screen color and image on the screen." }, { "code": null, "e": 2450, "s": 2401, "text": " screen.fill(YELLOW)\n screen.blit(img, rect)" }, { "code": null, "e": 2541, "s": 2450, "text": "Step 10: Further, make your image look attractive by constructing the border to the image." }, { "code": null, "e": 2584, "s": 2541, "text": " pygame.draw.rect(screen, BLUE, rect, 2)" }, { "code": null, "e": 2647, "s": 2584, "text": "Step 11: Furthermore, update the changes done in the GUI game." }, { "code": null, "e": 2674, "s": 2647, "text": " pygame.display.update()" }, { "code": null, "e": 2711, "s": 2674, "text": "Step 12: Finally, quit the GUI game." }, { "code": null, "e": 2725, "s": 2711, "text": "pygame.quit()" }, { "code": null, "e": 2754, "s": 2725, "text": "Below is the implementation." }, { "code": null, "e": 2761, "s": 2754, "text": "Python" }, { "code": "# Python program to move the image# with the mouse # Import the library pygameimport pygamefrom pygame.locals import * # Take colors inputYELLOW = (255, 255, 0)BLUE = (0, 0, 255) # Construct the GUI gamepygame.init() # Set dimensions of game GUIw, h = 640, 350screen = pygame.display.set_mode((w, h)) # Take image as inputimg = pygame.image.load('geek.jpg')img.convert() # Draw rectangle around the imagerect = img.get_rect()rect.center = w//2, h//2 # Set running and moving valuesrunning = Truemoving = False # Setting what happens when game# is in running statewhile running: for event in pygame.event.get(): # Close if the user quits the # game if event.type == QUIT: running = False # Making the image move elif event.type == MOUSEBUTTONDOWN: if rect.collidepoint(event.pos): moving = True # Set moving as False if you want # to move the image only with the # mouse click # Set moving as True if you want # to move the image without the # mouse click elif event.type == MOUSEBUTTONUP: moving = False # Make your image move continuously elif event.type == MOUSEMOTION and moving: rect.move_ip(event.rel) # Set screen color and image on screen screen.fill(YELLOW) screen.blit(img, rect) # Construct the border to the image pygame.draw.rect(screen, BLUE, rect, 2) # Update the GUI pygame pygame.display.update() # Quit the GUI gamepygame.quit()", "e": 4300, "s": 2761, "text": null }, { "code": null, "e": 4308, "s": 4300, "text": "Output:" }, { "code": null, "e": 4318, "s": 4308, "text": "kalrap615" }, { "code": null, "e": 4325, "s": 4318, "text": "Picked" }, { "code": null, "e": 4339, "s": 4325, "text": "Python-PyGame" }, { "code": null, "e": 4346, "s": 4339, "text": "Python" }, { "code": null, "e": 4444, "s": 4346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4476, "s": 4444, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4503, "s": 4476, "text": "Python Classes and Objects" }, { "code": null, "e": 4524, "s": 4503, "text": "Python OOPs Concepts" }, { "code": null, "e": 4547, "s": 4524, "text": "Introduction To PYTHON" }, { "code": null, "e": 4603, "s": 4547, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4634, "s": 4603, "text": "Python | os.path.join() method" }, { "code": null, "e": 4676, "s": 4634, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4718, "s": 4676, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4757, "s": 4718, "text": "Python | Get unique values from a list" } ]
Difference between alert box and confirmation box in JavaScript
11 Apr, 2022 Both the boxes appear as a pop-up or you can call them pop-up box. There are three types of pop-up box, you can have basic knowledge by reading What are the types of Popup box available in JavaScript ? and JavaScript | Dialogue Boxes article. Alert BoxConfirmation BoxPrompt Box Alert Box Confirmation Box Prompt Box All of these popups open a modal window, meaning that the user cannot interact with the rest of the components of the web page without responding to this window first. In this article, we will discuss between the most two confusing pop-up box Alert and Confirmation box. Alert Box: An alert box is used to inform/alert the user about an event. This type of popup box has only one button, named ‘OK’, and has no return value. Alert Box can be called using the function alert(“message”). Confirmation Box: A Confirmation Box is used to provide user with a choice about an event. This type of popup box has two buttons, named ‘OK’ and ‘Cancel’, and return ‘true’ and ‘false’ when respective buttons are clicked. Confirmation Box can be called using the function confirm(“message”). Below example illustrates the differences between alert Box and confirmation Box. Example: html <!DOCTYPE HTML><html> <head> <title> Alert Box vs Confirmation Box </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksforGeeks </h1> <button onclick="alertBox()"> Show Alert Box </button> <button onclick="confirmationBox()"> Show Confirmation Box </button> <script> function alertBox(){ alert("GeeksforGeeks: This" + " is an Alert Box."); } function confirmationBox(){ confirm("GeeksforGeeks: This" + " is a Confirmation Box."); } </script></body> </html> Output: Action-based on Confirmation Box returns different values. But alert box return only agreed value that user have- When ‘OK’ button is pressed in Confirmation Box, the function confirm() returns ‘true’, when ‘Cancel’ is pressed it returns ‘false’. Below is a simple If-Else statement to check the return type. We achieve this by modifying the function ‘confirmationBox()’ in the above code snippet. javascript function confirmationBox(){ if(confirm("GeeksForGeeks: This is a Confirmation Box")){ console.log("'OK' button was pressed."); }else{ console.log("'Cancel' button was pressed."); }} Output : Output in browser console when ‘OK’ and later ‘Cancel’ buttons are pressed. Let us see the differences in a tabular form -: Its syntax is -: window.alert(“sometext”); Its syntax is -: window.confirm(“sometext”); mayank007rawa JavaScript-Misc Picked HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Types of CSS (Cascading Style Sheet) HTTP headers | Content-Type Design a Tribute Page using HTML & CSS How to Insert Form Data into Database using PHP ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Apr, 2022" }, { "code": null, "e": 271, "s": 28, "text": "Both the boxes appear as a pop-up or you can call them pop-up box. There are three types of pop-up box, you can have basic knowledge by reading What are the types of Popup box available in JavaScript ? and JavaScript | Dialogue Boxes article." }, { "code": null, "e": 307, "s": 271, "text": "Alert BoxConfirmation BoxPrompt Box" }, { "code": null, "e": 317, "s": 307, "text": "Alert Box" }, { "code": null, "e": 334, "s": 317, "text": "Confirmation Box" }, { "code": null, "e": 345, "s": 334, "text": "Prompt Box" }, { "code": null, "e": 617, "s": 345, "text": "All of these popups open a modal window, meaning that the user cannot interact with the rest of the components of the web page without responding to this window first. In this article, we will discuss between the most two confusing pop-up box Alert and Confirmation box. " }, { "code": null, "e": 628, "s": 617, "text": "Alert Box:" }, { "code": null, "e": 690, "s": 628, "text": "An alert box is used to inform/alert the user about an event." }, { "code": null, "e": 771, "s": 690, "text": "This type of popup box has only one button, named ‘OK’, and has no return value." }, { "code": null, "e": 832, "s": 771, "text": "Alert Box can be called using the function alert(“message”)." }, { "code": null, "e": 850, "s": 832, "text": "Confirmation Box:" }, { "code": null, "e": 923, "s": 850, "text": "A Confirmation Box is used to provide user with a choice about an event." }, { "code": null, "e": 1055, "s": 923, "text": "This type of popup box has two buttons, named ‘OK’ and ‘Cancel’, and return ‘true’ and ‘false’ when respective buttons are clicked." }, { "code": null, "e": 1125, "s": 1055, "text": "Confirmation Box can be called using the function confirm(“message”)." }, { "code": null, "e": 1217, "s": 1125, "text": "Below example illustrates the differences between alert Box and confirmation Box. Example: " }, { "code": null, "e": 1222, "s": 1217, "text": "html" }, { "code": "<!DOCTYPE HTML><html> <head> <title> Alert Box vs Confirmation Box </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <button onclick=\"alertBox()\"> Show Alert Box </button> <button onclick=\"confirmationBox()\"> Show Confirmation Box </button> <script> function alertBox(){ alert(\"GeeksforGeeks: This\" + \" is an Alert Box.\"); } function confirmationBox(){ confirm(\"GeeksforGeeks: This\" + \" is a Confirmation Box.\"); } </script></body> </html> ", "e": 1895, "s": 1222, "text": null }, { "code": null, "e": 1903, "s": 1895, "text": "Output:" }, { "code": null, "e": 2020, "s": 1906, "text": "Action-based on Confirmation Box returns different values. But alert box return only agreed value that user have-" }, { "code": null, "e": 2153, "s": 2020, "text": "When ‘OK’ button is pressed in Confirmation Box, the function confirm() returns ‘true’, when ‘Cancel’ is pressed it returns ‘false’." }, { "code": null, "e": 2215, "s": 2153, "text": "Below is a simple If-Else statement to check the return type." }, { "code": null, "e": 2304, "s": 2215, "text": "We achieve this by modifying the function ‘confirmationBox()’ in the above code snippet." }, { "code": null, "e": 2315, "s": 2304, "text": "javascript" }, { "code": "function confirmationBox(){ if(confirm(\"GeeksForGeeks: This is a Confirmation Box\")){ console.log(\"'OK' button was pressed.\"); }else{ console.log(\"'Cancel' button was pressed.\"); }}", "e": 2520, "s": 2315, "text": null }, { "code": null, "e": 2606, "s": 2520, "text": "Output : Output in browser console when ‘OK’ and later ‘Cancel’ buttons are pressed. " }, { "code": null, "e": 2654, "s": 2606, "text": "Let us see the differences in a tabular form -:" }, { "code": null, "e": 2671, "s": 2654, "text": "Its syntax is -:" }, { "code": null, "e": 2697, "s": 2671, "text": "window.alert(“sometext”);" }, { "code": null, "e": 2714, "s": 2697, "text": "Its syntax is -:" }, { "code": null, "e": 2742, "s": 2714, "text": "window.confirm(“sometext”);" }, { "code": null, "e": 2756, "s": 2742, "text": "mayank007rawa" }, { "code": null, "e": 2772, "s": 2756, "text": "JavaScript-Misc" }, { "code": null, "e": 2779, "s": 2772, "text": "Picked" }, { "code": null, "e": 2784, "s": 2779, "text": "HTML" }, { "code": null, "e": 2795, "s": 2784, "text": "JavaScript" }, { "code": null, "e": 2812, "s": 2795, "text": "Web Technologies" }, { "code": null, "e": 2839, "s": 2812, "text": "Web technologies Questions" }, { "code": null, "e": 2844, "s": 2839, "text": "HTML" }, { "code": null, "e": 2942, "s": 2844, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2966, "s": 2942, "text": "REST API (Introduction)" }, { "code": null, "e": 3003, "s": 2966, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 3031, "s": 3003, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 3070, "s": 3031, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3120, "s": 3070, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 3181, "s": 3120, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3253, "s": 3181, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3293, "s": 3253, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3335, "s": 3293, "text": "Roadmap to Learn JavaScript For Beginners" } ]
How to convert epoch Date to meaningful JavaScript date?
Dates in JavaScript take milliseconds since epoch. If the epoch in milliseconds is 1514789449605, then let us convert it into a meaningful JavaScript date. Live Demo <html> <head> <title>JavaScript Dates</title> </head> <body> <script> var val ="/Date(1514789449605)/"; var myDate = new Date( parseFloat( val.substr(6 ))); document.write("Converted Date:"+ (myDate.getMonth() + 1) + "/" + myDate.getDate() + "/" + myDate.getFullYear() + " " + myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds() ); </script> </body> </html> Converted Date:1/1/2018 12:20:49
[ { "code": null, "e": 1218, "s": 1062, "text": "Dates in JavaScript take milliseconds since epoch. If the epoch in milliseconds is 1514789449605, then let us convert it into a meaningful JavaScript date." }, { "code": null, "e": 1228, "s": 1218, "text": "Live Demo" }, { "code": null, "e": 1740, "s": 1228, "text": "<html>\n <head>\n <title>JavaScript Dates</title>\n </head>\n <body>\n <script>\n var val =\"/Date(1514789449605)/\";\n var myDate = new Date( parseFloat( val.substr(6 )));\n document.write(\"Converted Date:\"+ (myDate.getMonth() + 1) + \"/\" +\n myDate.getDate() + \"/\" + myDate.getFullYear() + \" \" +\n myDate.getHours() + \":\" + myDate.getMinutes() + \":\" +\n myDate.getSeconds()\n );\n </script>\n </body>\n</html>" }, { "code": null, "e": 1773, "s": 1740, "text": "Converted Date:1/1/2018 12:20:49" } ]
Boost Forecasting With Multiprocessing | Towards Data Science
When forecasting time series data, sometimes you need both speed and accuracy. When working from a laptop with Python, try multiprocessing to get the best of both worlds. You are trying to optimize a multiprocessing problem in Python on your local machine You are forecasting time series data with Statsmodels ARIMA, Facebook Prophet, or PyTorch LSTM You are trying to decide whether multiprocessing is an optimal configuration with PyTorch LSTM if you don’t have access to a GPU Most of the time you have plenty of data. Some of the time, you have plenty of time to analyze the data, but most of the time, you need to produce something in no time at all. But, as the quantity of data increases, you need bigger and better models to produce useful information. Whether you need to speed things up to debug code or present something for prime time, big data and deep models will to chew up valuable time you cannot afford to lose. Can I do deep learning faster on my MacBook without a GPU? Forecasting performance of Facebook Prophet with and without multiprocessing enabled. Data comprises simulated stock data with a size of 60 batches x 28 chunks x 15 data points per chunk (approx 25,000). Training model on a window size of 15 and predicting the next 15 prices in sequence. To forecast an accurate trend and predict future data points, you need lots of data, a great model, or a mix of both. But debugging can be challenging. It might take 5, 10, or 20 minutes to know that a single line of code does not work correctly because that’s how long a model takes to run. To cut down the amount of time you need to cycle through changes, a faster machine, a GPU, or some kind of cloud solution will do the trick — but what if you have none of the above? What you want to make sure your model functions correctly before spending money on a cloud-based job? Or, what if this is what you are going to deploy in an app? In any case, we want more speed! In this article, I share the results of a few experiments that might help you architect your own multiprocessing solution for a speed boost. Forecasting performance of Statsmodels ARIMA with and without multiprocessing enabled. Data comprises simulated stock data with a size of 60 batches x 28 chunks x 15 data points per chunk (approx 25,000). Training model on a window size of 15 and predicting the next 15 prices in sequence. First, a caveat. I am just a guy with a laptop that ran some experiments — your results may vary and my findings and code should be scrutinized. Caveats aside, I think these findings are worth sharing and can save you some time or, at least, make you think about some interesting problems. It is possible to implement multiprocessing in python with ARIMA, Facebook Prophet, and PyTorchFor Facebook Prophet, 8x pooled processes on an 8-core machine seems to produce optimal results — to the tune of a 70% decrease in clock time for the same data and same computation.For statsmodels ARIMA, 6x pooled processes produced the most optimal results but the difference between 6 and 8 processors was negligible — a 50% decrease in clock time.For a single-layer LSTM built with PyTorch, there were two interesting findings. First, the standard configuration (no multiprocessing) outperformed all other configurations with pooled processes and the clock time to complete jobs got progressively worse with pooled processes. Second, the error, as measured by mean absolute percentage error (MAPE) appeared to steadily decrease as the number of processes increased. It is possible to implement multiprocessing in python with ARIMA, Facebook Prophet, and PyTorch For Facebook Prophet, 8x pooled processes on an 8-core machine seems to produce optimal results — to the tune of a 70% decrease in clock time for the same data and same computation. For statsmodels ARIMA, 6x pooled processes produced the most optimal results but the difference between 6 and 8 processors was negligible — a 50% decrease in clock time. For a single-layer LSTM built with PyTorch, there were two interesting findings. First, the standard configuration (no multiprocessing) outperformed all other configurations with pooled processes and the clock time to complete jobs got progressively worse with pooled processes. Second, the error, as measured by mean absolute percentage error (MAPE) appeared to steadily decrease as the number of processes increased. Note about clock time, etc: I averaged the results of three runs per configuration and took clock time as the difference between start time and end time with time.time(). Forecasting performance of PyTorch LSTM neural network with and without multiprocessing enabled. Data comprises simulated stock data with a window size of 15, step size of 1 across a dataset comprising prices per minute from 9 am to 4 pm for 60 days. Training on every 15 data points to predict the next in sequence. LR=0.001, epochs=5, batch size=16, n layers=1. Faster results? Sounds great, but how? In the next few sections I step through key pointers on how to modify ARIMA, Prophet, and LSTM models to implement multiprocessing. With Autoregressive Integrated Moving Average module, or “ARIMA” for short, you might be interested in forecasting a trend that has some kind of seasonality. Since ARIMA fundamentals are well covered here and here among many other articles, I will go directly to demonstrating a set up with multiprocessing. A Basic Setup for ARIMA # import dependenciesfrom statsmodels.tsa.arima.model import ARIMA# some data...x_i = [4.1, 3.1, 2.5, 4.0]# a simple model on the datam = ARIMA(x_i, order=(0,1,0))# fit the model m_fit = m.fit()# forecast/predict the next n stepsyhat = m_fit.forecast(steps=1)# then, compare yhat predictions to y targets... Prepare Data for Forecasting Since ARIMA is best at forecasting a few steps after the training set, I modified a data chunking script that works on a dataframe having a datetime column and a data column. In my experiment, the data are the scaled prices of a stock for each minute of the trading day starting at 9 am and ending at 4 pm. # dataframe examplecolumns -> 'ds', 'y''ds' data -> 2019-01-01 09:00:00, ...'y' data -> 1.4, ... The functions that follow in data_chunker.py, return a list of tuples of dataframes where each pair is a chunk of 15 minute data. Given some chunked data, we can iterate through the list of dataframes to compute a forecast for each chunk with a function wrapper for ARIMA. Prepare ARIMA for Forecasting Given some chunked data and a function wrapper for ARIMA as outlined above, we can call the run_arima() function by iterating over the chunked data which is just a list of dataframes. This step of organizing data into an iterable object and applying arima as a function to that object is very important because it sets up how to implement multiprocessing. If you get this part right, multiprocessing becomes a simple task. # from main.py, run arima as list comprehensionmodel = run_arimaresults = [model(i) for i in chunked_data]# from main, iterate through a list of data and with arima function# within arima function, iterate through the list of chunked data# return a forecast of each 15 minute period Import PyTorch Multiprocessor Since we are working with Facebook APIs (PyTorch and Facebook Prophet), I imported the PyTorch multiprocessor library which provides coverage over the base multiprocessor library. import torch.multiprocessing as mp# the torch mp is basically the same as# import multiprocessing as mp# get number of available processesprocess_count = mp.cpu_count() Making Sense of cpu_count() The cpu_count() method returns a total count of available processes. From what I can gather, on a MacBook Pro with 8 cores, cpu_count() returns a value of 16 — I believe this means 2 hyper-threaded CPU processes per core. During performance testing, as mentioned above, pooling 8x processes performed better than just 2x processes and better than 14x processes. My brief conclusion is that 2x processes are not taking full advantage of the potential compute resources while 14x processes is relatively worse because the processes are fighting for resources on each core. Implement Multiprocessing for ARIMA Now that we have chunked data, the arima function wrapper and a method to iterate the arima function, time to implement multiprocessing. # this needs to be run from main.py or something similar# import dependencies as required here# import helper functions and arima wrapper here# functions must be guarded in thisif __name__ == '__main__': model = run_arima # set a pool of 8 p = mp.Pool(8) # iterate run_arima over chunked data results = list(p.imap(model, chunked_data)) # close and join pools per the docs p.close() p.join() The code snip above presents a simplified case but the next code gist shows how to manage sending the function parameters while multiprocessing and also, how to add the tqdm progress bar. Based on the above ARIMA example, we have a template for multiprocessing. Organize data into chunks as an iterable object like a list of dataframes Apply the forecasting model to the chunked object The steps for Facebook Prophet are very similar. The main exception is the actual code for Prophet which expects to consume dataframes and has certain requirements for column names to be ‘ds’ for timestamps and ‘y’ for data. Similarly to ARIMA, we can just assign the run_prophet function to a model object and iterate with pooling over the model and data. Here, the framework is not exactly the same with LSTM as it is with ARIMA or Prophet — but that’s okay — they are vastly different models. How is an LSTM different? Whereas ARIMA and Facebook Prophet learn a model and predict the sequences that immediately follow, we can use the LSTM to predict sequences that are far outside the training window. As a simple example, ARIMA and Prophet might be good at training on a week of data and predicting the next week, but they might do poorly at predicting over the next several months — this is where the LSTM can do well. I adapted the example code from PyTorch to create a multiprocessing version of the LSTM. Given a function that creates the LSTM model and a function that implements training iterations, the following application of multiprocessing can work. # given a model of LSTM# given a dict of params# given a function called train_modelmodel.share_memory()processes = []# assign processesfor rank in tqdm(range(8)): # pool data for train_scaled to function train_model p = mp.Process(target=train_model, kwargs=params) p.start() processes.append(p)# join processes after computefor p in tqdm(processes): p.join() The key insight that I got from the PyTorch example is that the train_model() function should iterate through the model and data loader objects, while calling a separate function to execute training in each epoch. Consider that without multiprocessing, the above call to train_model() can be as simple as calling the function and passing the data and parameters as a dictionary. # given a dictionary of paramstrain_model(**params) I think this highlights an interesting difference between pooling resources for a neural network like LSTM and simpler models such as ARIMA, but I need to learn more about how computations work within each process — perhaps the topic of a future post. Without going too deep into how to actually construct an LSTM (a whole other subject on its own), here are three tips for configuring the architecture assuming you have some familiarity with the topic: In train_model(), call the PyTorch DataLoader object, loss function, and initialize the optimizer, then loop through n epochs. Within each epoch, call another function train_epoch().In train_epoch(), enumerate through the DataLoader object and apply the LSTM model there.From main.py, to pass all your arguments for the LSTM, i.e. number of layers, and batch size, etc, create a dictionary and pass it to the process function as kwargs=params. Then, within the function signature for train_model, make sure to have a **kwargs parameter to receive the dictionary values. In train_model(), call the PyTorch DataLoader object, loss function, and initialize the optimizer, then loop through n epochs. Within each epoch, call another function train_epoch(). In train_epoch(), enumerate through the DataLoader object and apply the LSTM model there. From main.py, to pass all your arguments for the LSTM, i.e. number of layers, and batch size, etc, create a dictionary and pass it to the process function as kwargs=params. Then, within the function signature for train_model, make sure to have a **kwargs parameter to receive the dictionary values. It is worth mentioning that, in at least my project’s implementation, while this method of pooling ‘worked’ it performed relatively worse in terms of speed as compared to not pooling. On that front alone, it might not be worth the time to implement. On the other hand, I may have missed an important step to make it work more efficiently since I have some implicitly nested for-loops. In addition, there is also the curious case of why error seems to improve when we have many processes running in parallel — a topic of interest to explore some other time. The full implementation here: https://github.com/justinhchae/stocks and also, a production credit to my project partner (knowledgewithin) for configuring the LSTM model. In this article, I demonstrated how it is possible to adapt a multiprocessing framework to forecasting models from ARIMA and Facebook Prophet on the same dataset. In both cases, multiprocessing resulted in between 70% to 50% time decreases by increasing the iterations per second. In addition, I demonstrated how to apply the PyTorch Hogwild example to get multiprocessing with an LSTM to work. However, unlike ARIMA and Prophet, the LSTM did not improve in terms of speed and, in fact, degraded with more processes. Strangely though, the LSTM error improved as the number of parallel processes increased — a subject that might be worth further investigation. I skimmed over a few relatively trivial steps to provide an overview of how to apply the multiprocessing concept, but they are still important. To get an idea of the specifics from data processing to model setup, see my GitHub repository. I initially set out to see if I could improve deep learning on my laptop without a GPU, i.e. learn the LSTM faster by pooling CPUs on my MacBook. Unfortunately, it seems that the pooled CPUs do not offer speed advantages for the LSTM and better hardware may ultimately be necessary in this scenario. As for next steps, it should be worthwhile to migrate this code to something like Google Colab and see how it performs with a GPU. Edit: If you are looking for a deeper dive to get started with multiprocessing in Python from the ground up, check out a companion post that I wrote to cover all the basics. python.plainenglish.io Project Repository Statsmodels ARIMA, documentation Applied Forecasting Article by TDS Source for Prophet Multiprocessing Framework by Spike Data Chunker Script PyTorch Multiprocessing Best Practices Facebook Prophet API About Multiprocessing by Contentsquare Engine About LSTM, by TDS
[ { "code": null, "e": 343, "s": 172, "text": "When forecasting time series data, sometimes you need both speed and accuracy. When working from a laptop with Python, try multiprocessing to get the best of both worlds." }, { "code": null, "e": 428, "s": 343, "text": "You are trying to optimize a multiprocessing problem in Python on your local machine" }, { "code": null, "e": 523, "s": 428, "text": "You are forecasting time series data with Statsmodels ARIMA, Facebook Prophet, or PyTorch LSTM" }, { "code": null, "e": 652, "s": 523, "text": "You are trying to decide whether multiprocessing is an optimal configuration with PyTorch LSTM if you don’t have access to a GPU" }, { "code": null, "e": 1102, "s": 652, "text": "Most of the time you have plenty of data. Some of the time, you have plenty of time to analyze the data, but most of the time, you need to produce something in no time at all. But, as the quantity of data increases, you need bigger and better models to produce useful information. Whether you need to speed things up to debug code or present something for prime time, big data and deep models will to chew up valuable time you cannot afford to lose." }, { "code": null, "e": 1161, "s": 1102, "text": "Can I do deep learning faster on my MacBook without a GPU?" }, { "code": null, "e": 1454, "s": 1161, "text": " Forecasting performance of Facebook Prophet with and without multiprocessing enabled. Data comprises simulated stock data with a size of 60 batches x 28 chunks x 15 data points per chunk (approx 25,000). Training model on a window size of 15 and predicting the next 15 prices in sequence. " }, { "code": null, "e": 1746, "s": 1454, "text": "To forecast an accurate trend and predict future data points, you need lots of data, a great model, or a mix of both. But debugging can be challenging. It might take 5, 10, or 20 minutes to know that a single line of code does not work correctly because that’s how long a model takes to run." }, { "code": null, "e": 2123, "s": 1746, "text": "To cut down the amount of time you need to cycle through changes, a faster machine, a GPU, or some kind of cloud solution will do the trick — but what if you have none of the above? What you want to make sure your model functions correctly before spending money on a cloud-based job? Or, what if this is what you are going to deploy in an app? In any case, we want more speed!" }, { "code": null, "e": 2264, "s": 2123, "text": "In this article, I share the results of a few experiments that might help you architect your own multiprocessing solution for a speed boost." }, { "code": null, "e": 2558, "s": 2264, "text": " Forecasting performance of Statsmodels ARIMA with and without multiprocessing enabled. Data comprises simulated stock data with a size of 60 batches x 28 chunks x 15 data points per chunk (approx 25,000). Training model on a window size of 15 and predicting the next 15 prices in sequence. " }, { "code": null, "e": 2848, "s": 2558, "text": "First, a caveat. I am just a guy with a laptop that ran some experiments — your results may vary and my findings and code should be scrutinized. Caveats aside, I think these findings are worth sharing and can save you some time or, at least, make you think about some interesting problems." }, { "code": null, "e": 3712, "s": 2848, "text": "It is possible to implement multiprocessing in python with ARIMA, Facebook Prophet, and PyTorchFor Facebook Prophet, 8x pooled processes on an 8-core machine seems to produce optimal results — to the tune of a 70% decrease in clock time for the same data and same computation.For statsmodels ARIMA, 6x pooled processes produced the most optimal results but the difference between 6 and 8 processors was negligible — a 50% decrease in clock time.For a single-layer LSTM built with PyTorch, there were two interesting findings. First, the standard configuration (no multiprocessing) outperformed all other configurations with pooled processes and the clock time to complete jobs got progressively worse with pooled processes. Second, the error, as measured by mean absolute percentage error (MAPE) appeared to steadily decrease as the number of processes increased." }, { "code": null, "e": 3808, "s": 3712, "text": "It is possible to implement multiprocessing in python with ARIMA, Facebook Prophet, and PyTorch" }, { "code": null, "e": 3990, "s": 3808, "text": "For Facebook Prophet, 8x pooled processes on an 8-core machine seems to produce optimal results — to the tune of a 70% decrease in clock time for the same data and same computation." }, { "code": null, "e": 4160, "s": 3990, "text": "For statsmodels ARIMA, 6x pooled processes produced the most optimal results but the difference between 6 and 8 processors was negligible — a 50% decrease in clock time." }, { "code": null, "e": 4579, "s": 4160, "text": "For a single-layer LSTM built with PyTorch, there were two interesting findings. First, the standard configuration (no multiprocessing) outperformed all other configurations with pooled processes and the clock time to complete jobs got progressively worse with pooled processes. Second, the error, as measured by mean absolute percentage error (MAPE) appeared to steadily decrease as the number of processes increased." }, { "code": null, "e": 4750, "s": 4579, "text": "Note about clock time, etc: I averaged the results of three runs per configuration and took clock time as the difference between start time and end time with time.time()." }, { "code": null, "e": 5118, "s": 4750, "text": " Forecasting performance of PyTorch LSTM neural network with and without multiprocessing enabled. Data comprises simulated stock data with a window size of 15, step size of 1 across a dataset comprising prices per minute from 9 am to 4 pm for 60 days. Training on every 15 data points to predict the next in sequence. LR=0.001, epochs=5, batch size=16, n layers=1. " }, { "code": null, "e": 5289, "s": 5118, "text": "Faster results? Sounds great, but how? In the next few sections I step through key pointers on how to modify ARIMA, Prophet, and LSTM models to implement multiprocessing." }, { "code": null, "e": 5597, "s": 5289, "text": "With Autoregressive Integrated Moving Average module, or “ARIMA” for short, you might be interested in forecasting a trend that has some kind of seasonality. Since ARIMA fundamentals are well covered here and here among many other articles, I will go directly to demonstrating a set up with multiprocessing." }, { "code": null, "e": 5621, "s": 5597, "text": "A Basic Setup for ARIMA" }, { "code": null, "e": 5929, "s": 5621, "text": "# import dependenciesfrom statsmodels.tsa.arima.model import ARIMA# some data...x_i = [4.1, 3.1, 2.5, 4.0]# a simple model on the datam = ARIMA(x_i, order=(0,1,0))# fit the model m_fit = m.fit()# forecast/predict the next n stepsyhat = m_fit.forecast(steps=1)# then, compare yhat predictions to y targets..." }, { "code": null, "e": 5958, "s": 5929, "text": "Prepare Data for Forecasting" }, { "code": null, "e": 6265, "s": 5958, "text": "Since ARIMA is best at forecasting a few steps after the training set, I modified a data chunking script that works on a dataframe having a datetime column and a data column. In my experiment, the data are the scaled prices of a stock for each minute of the trading day starting at 9 am and ending at 4 pm." }, { "code": null, "e": 6362, "s": 6265, "text": "# dataframe examplecolumns -> 'ds', 'y''ds' data -> 2019-01-01 09:00:00, ...'y' data -> 1.4, ..." }, { "code": null, "e": 6492, "s": 6362, "text": "The functions that follow in data_chunker.py, return a list of tuples of dataframes where each pair is a chunk of 15 minute data." }, { "code": null, "e": 6635, "s": 6492, "text": "Given some chunked data, we can iterate through the list of dataframes to compute a forecast for each chunk with a function wrapper for ARIMA." }, { "code": null, "e": 6665, "s": 6635, "text": "Prepare ARIMA for Forecasting" }, { "code": null, "e": 6849, "s": 6665, "text": "Given some chunked data and a function wrapper for ARIMA as outlined above, we can call the run_arima() function by iterating over the chunked data which is just a list of dataframes." }, { "code": null, "e": 7088, "s": 6849, "text": "This step of organizing data into an iterable object and applying arima as a function to that object is very important because it sets up how to implement multiprocessing. If you get this part right, multiprocessing becomes a simple task." }, { "code": null, "e": 7371, "s": 7088, "text": "# from main.py, run arima as list comprehensionmodel = run_arimaresults = [model(i) for i in chunked_data]# from main, iterate through a list of data and with arima function# within arima function, iterate through the list of chunked data# return a forecast of each 15 minute period" }, { "code": null, "e": 7401, "s": 7371, "text": "Import PyTorch Multiprocessor" }, { "code": null, "e": 7581, "s": 7401, "text": "Since we are working with Facebook APIs (PyTorch and Facebook Prophet), I imported the PyTorch multiprocessor library which provides coverage over the base multiprocessor library." }, { "code": null, "e": 7750, "s": 7581, "text": "import torch.multiprocessing as mp# the torch mp is basically the same as# import multiprocessing as mp# get number of available processesprocess_count = mp.cpu_count()" }, { "code": null, "e": 7778, "s": 7750, "text": "Making Sense of cpu_count()" }, { "code": null, "e": 8349, "s": 7778, "text": "The cpu_count() method returns a total count of available processes. From what I can gather, on a MacBook Pro with 8 cores, cpu_count() returns a value of 16 — I believe this means 2 hyper-threaded CPU processes per core. During performance testing, as mentioned above, pooling 8x processes performed better than just 2x processes and better than 14x processes. My brief conclusion is that 2x processes are not taking full advantage of the potential compute resources while 14x processes is relatively worse because the processes are fighting for resources on each core." }, { "code": null, "e": 8385, "s": 8349, "text": "Implement Multiprocessing for ARIMA" }, { "code": null, "e": 8522, "s": 8385, "text": "Now that we have chunked data, the arima function wrapper and a method to iterate the arima function, time to implement multiprocessing." }, { "code": null, "e": 8924, "s": 8522, "text": "# this needs to be run from main.py or something similar# import dependencies as required here# import helper functions and arima wrapper here# functions must be guarded in thisif __name__ == '__main__': model = run_arima # set a pool of 8 p = mp.Pool(8) # iterate run_arima over chunked data results = list(p.imap(model, chunked_data)) # close and join pools per the docs p.close() p.join()" }, { "code": null, "e": 9112, "s": 8924, "text": "The code snip above presents a simplified case but the next code gist shows how to manage sending the function parameters while multiprocessing and also, how to add the tqdm progress bar." }, { "code": null, "e": 9186, "s": 9112, "text": "Based on the above ARIMA example, we have a template for multiprocessing." }, { "code": null, "e": 9260, "s": 9186, "text": "Organize data into chunks as an iterable object like a list of dataframes" }, { "code": null, "e": 9310, "s": 9260, "text": "Apply the forecasting model to the chunked object" }, { "code": null, "e": 9535, "s": 9310, "text": "The steps for Facebook Prophet are very similar. The main exception is the actual code for Prophet which expects to consume dataframes and has certain requirements for column names to be ‘ds’ for timestamps and ‘y’ for data." }, { "code": null, "e": 9667, "s": 9535, "text": "Similarly to ARIMA, we can just assign the run_prophet function to a model object and iterate with pooling over the model and data." }, { "code": null, "e": 10234, "s": 9667, "text": "Here, the framework is not exactly the same with LSTM as it is with ARIMA or Prophet — but that’s okay — they are vastly different models. How is an LSTM different? Whereas ARIMA and Facebook Prophet learn a model and predict the sequences that immediately follow, we can use the LSTM to predict sequences that are far outside the training window. As a simple example, ARIMA and Prophet might be good at training on a week of data and predicting the next week, but they might do poorly at predicting over the next several months — this is where the LSTM can do well." }, { "code": null, "e": 10475, "s": 10234, "text": "I adapted the example code from PyTorch to create a multiprocessing version of the LSTM. Given a function that creates the LSTM model and a function that implements training iterations, the following application of multiprocessing can work." }, { "code": null, "e": 10851, "s": 10475, "text": "# given a model of LSTM# given a dict of params# given a function called train_modelmodel.share_memory()processes = []# assign processesfor rank in tqdm(range(8)): # pool data for train_scaled to function train_model p = mp.Process(target=train_model, kwargs=params) p.start() processes.append(p)# join processes after computefor p in tqdm(processes): p.join()" }, { "code": null, "e": 11230, "s": 10851, "text": "The key insight that I got from the PyTorch example is that the train_model() function should iterate through the model and data loader objects, while calling a separate function to execute training in each epoch. Consider that without multiprocessing, the above call to train_model() can be as simple as calling the function and passing the data and parameters as a dictionary." }, { "code": null, "e": 11282, "s": 11230, "text": "# given a dictionary of paramstrain_model(**params)" }, { "code": null, "e": 11534, "s": 11282, "text": "I think this highlights an interesting difference between pooling resources for a neural network like LSTM and simpler models such as ARIMA, but I need to learn more about how computations work within each process — perhaps the topic of a future post." }, { "code": null, "e": 11736, "s": 11534, "text": "Without going too deep into how to actually construct an LSTM (a whole other subject on its own), here are three tips for configuring the architecture assuming you have some familiarity with the topic:" }, { "code": null, "e": 12306, "s": 11736, "text": "In train_model(), call the PyTorch DataLoader object, loss function, and initialize the optimizer, then loop through n epochs. Within each epoch, call another function train_epoch().In train_epoch(), enumerate through the DataLoader object and apply the LSTM model there.From main.py, to pass all your arguments for the LSTM, i.e. number of layers, and batch size, etc, create a dictionary and pass it to the process function as kwargs=params. Then, within the function signature for train_model, make sure to have a **kwargs parameter to receive the dictionary values." }, { "code": null, "e": 12489, "s": 12306, "text": "In train_model(), call the PyTorch DataLoader object, loss function, and initialize the optimizer, then loop through n epochs. Within each epoch, call another function train_epoch()." }, { "code": null, "e": 12579, "s": 12489, "text": "In train_epoch(), enumerate through the DataLoader object and apply the LSTM model there." }, { "code": null, "e": 12878, "s": 12579, "text": "From main.py, to pass all your arguments for the LSTM, i.e. number of layers, and batch size, etc, create a dictionary and pass it to the process function as kwargs=params. Then, within the function signature for train_model, make sure to have a **kwargs parameter to receive the dictionary values." }, { "code": null, "e": 13435, "s": 12878, "text": "It is worth mentioning that, in at least my project’s implementation, while this method of pooling ‘worked’ it performed relatively worse in terms of speed as compared to not pooling. On that front alone, it might not be worth the time to implement. On the other hand, I may have missed an important step to make it work more efficiently since I have some implicitly nested for-loops. In addition, there is also the curious case of why error seems to improve when we have many processes running in parallel — a topic of interest to explore some other time." }, { "code": null, "e": 13605, "s": 13435, "text": "The full implementation here: https://github.com/justinhchae/stocks and also, a production credit to my project partner (knowledgewithin) for configuring the LSTM model." }, { "code": null, "e": 14265, "s": 13605, "text": "In this article, I demonstrated how it is possible to adapt a multiprocessing framework to forecasting models from ARIMA and Facebook Prophet on the same dataset. In both cases, multiprocessing resulted in between 70% to 50% time decreases by increasing the iterations per second. In addition, I demonstrated how to apply the PyTorch Hogwild example to get multiprocessing with an LSTM to work. However, unlike ARIMA and Prophet, the LSTM did not improve in terms of speed and, in fact, degraded with more processes. Strangely though, the LSTM error improved as the number of parallel processes increased — a subject that might be worth further investigation." }, { "code": null, "e": 14504, "s": 14265, "text": "I skimmed over a few relatively trivial steps to provide an overview of how to apply the multiprocessing concept, but they are still important. To get an idea of the specifics from data processing to model setup, see my GitHub repository." }, { "code": null, "e": 14804, "s": 14504, "text": "I initially set out to see if I could improve deep learning on my laptop without a GPU, i.e. learn the LSTM faster by pooling CPUs on my MacBook. Unfortunately, it seems that the pooled CPUs do not offer speed advantages for the LSTM and better hardware may ultimately be necessary in this scenario." }, { "code": null, "e": 14935, "s": 14804, "text": "As for next steps, it should be worthwhile to migrate this code to something like Google Colab and see how it performs with a GPU." }, { "code": null, "e": 15109, "s": 14935, "text": "Edit: If you are looking for a deeper dive to get started with multiprocessing in Python from the ground up, check out a companion post that I wrote to cover all the basics." }, { "code": null, "e": 15132, "s": 15109, "text": "python.plainenglish.io" }, { "code": null, "e": 15151, "s": 15132, "text": "Project Repository" }, { "code": null, "e": 15184, "s": 15151, "text": "Statsmodels ARIMA, documentation" }, { "code": null, "e": 15219, "s": 15184, "text": "Applied Forecasting Article by TDS" }, { "code": null, "e": 15273, "s": 15219, "text": "Source for Prophet Multiprocessing Framework by Spike" }, { "code": null, "e": 15293, "s": 15273, "text": "Data Chunker Script" }, { "code": null, "e": 15332, "s": 15293, "text": "PyTorch Multiprocessing Best Practices" }, { "code": null, "e": 15353, "s": 15332, "text": "Facebook Prophet API" }, { "code": null, "e": 15399, "s": 15353, "text": "About Multiprocessing by Contentsquare Engine" } ]
Java single line comments.
// is used for single line comments. Live Demo public class MyFirstJavaProgram { public static void main(String[] args) { // This is a single line comment. System.out.println("Hello World"); } }
[ { "code": null, "e": 1099, "s": 1062, "text": "// is used for single line comments." }, { "code": null, "e": 1109, "s": 1099, "text": "Live Demo" }, { "code": null, "e": 1275, "s": 1109, "text": "public class MyFirstJavaProgram {\n public static void main(String[] args) {\n // This is a single line comment.\n System.out.println(\"Hello World\");\n }\n}" } ]
Array.GetValue() Method in C# with Examples | Set – 4 - GeeksforGeeks
17 May, 2020 Array.GetValue() Method in C# is used to gets the value of the specified element in the current Array. There are total 8 methods in the overload list of this method which are as follows: Array.GetValue(Int32, Int32) Array.GetValue(Int64, Int64) Array.GetValue(Int32) Array.GetValue(Int64) Array.GetValue(Int32, Int32, Int32) Array.GetValue(Int64, Int64, Int64) Array.GetValue(Int32[]) Array.GetValue(Int64[]) In this article we are explaining Array.GetValue(Int32[]) and Array.GetValue(Int64[]) method. Array.GetValue(Int32[]) method is used to get the value at the specified position in the multidimensional-dimensional Array. The indexes are passed to this method by a 1D array, that means the 1D array which is passed that contains the specified index as array element of 1D array, and the element is to be searched that is at that index which is in the 1D array. The indexes are specified as 32-bit integers. Syntax: public object GetValue (int[] index); Here “index” is a 1D array of 32-bit integers that represent the index specifying the position of the element to be searched. searched. Returns: This method returns the element at the specified index define by the passed 1D array to the GetValue method. The value is a 32-bit integer value. Exceptions: ArgumentException: If the number of dimensions in the current array is not equal to the number of elements in index array which is passed to GetValue method. IndexOutOfRangeException: If the elements in index array defines a range which is outside the range of valid indexes for the corresponding dimension of the current array . ArgumentNullException: if the index array is null then it throws. Array.GetValue(Int64[]) method is used to get the value at the specified position in the multidimensional-dimensional Array. The indexes are passed to this method by a 1D array, that means the 1D array which is passed that contains the specified index as array element of 1D array, and the element is to be searched that is at that index which is in the 1D array. The indexes are specified as 64-bit integers. Syntax: public object GetValue (long[] index); Here, “index[]” is a 1D array of 64-bit integers that represent the index specifying the position of the element to be searched. Returns: This method returns the element at the specified index define by the passed 1D array to the GetValue method. The value is a 32-bit integer value. Exceptions: ArgumentException: If the number of dimensions in the current array is not equal to the number of elements in index array which is passed to GetValue method. ArgumentOutOfRangeException: If the elements in index array defines a range which is outside the range of valid indexes for the corresponding dimension of the current array . ArgumentNullException: if the index array is null then it throws. Example 1: C# // C# program to demonstrate the// Array.GetValue(Int32[]) and// Array.GetValue(Int64[]) methodusing System;public class GFG { public static void Main() { // declare a character // array of size 1x2x2x3 // it has 2 3D array // which have 2 row and 3 column each char[, , , ] arr = new char[1, 2, 2, 3]{ { {// array 1 {'A', 'B', 'C'}, {'D', 'E', 'F'} }, {// array 2 {'G', 'H', 'I'}, {'J', 'K', 'L'}} } /*Array look like |----------------------------------| | -------------------------------- | | |A| |B| |C| | | |D| |E| |F| | | -------------------------------- | | -------------------------------- | | |G| |H| |I| | | |J| |K| |L| | | -------------------------------- | |__________________________________| */ }; // initialize a integer array // contains the index of the element // index of 'L' int[] indx = new int[4]{0, 1, 1, 2}; // "indx" array is passing // to GetValue(Int32[]) method Console.WriteLine("Element at index [0, 1, 1, 2] is : {0}", arr.GetValue(indx)); }} Element at index [0, 1, 1, 2] is : L Example 2: C# // C# program to demonstrate the// Array.GetValue(Int32[]) and// Array.GetValue(Int64[]) methodusing System; class GFG { public static void Main() { // declare a character // array of size 1x2x2x3 // it has 2 3D array // which have 2 row and // 3 column each string[, , , ] arr = new string[1, 2, 2, 3]; /*Array look like|------------------------------------|| ---------------------------------- || |C++| |Java| |C#| || |Perl| |python| |PHP| || ---------------------------------- || ---------------------------------- || |Ruby| |F#| |Julia| || |SQL| |Kotlin| |GO| || ---------------------------------- ||____________________________________|*/ arr.SetValue("C++", 0, 0, 0, 0); arr.SetValue("Java", 0, 0, 0, 1); arr.SetValue("C#", 0, 0, 0, 2); arr.SetValue("Perl", 0, 0, 1, 0); arr.SetValue("Python", 0, 0, 1, 1); arr.SetValue("PHP", 0, 0, 1, 2); arr.SetValue("Ruby", 0, 1, 0, 1); arr.SetValue("F#", 0, 1, 0, 1); arr.SetValue("Julia", 0, 1, 0, 2); arr.SetValue("SQL", 0, 1, 1, 0); arr.SetValue("kotlin", 0, 1, 1, 1); arr.SetValue("GO", 0, 1, 1, 2); // initialize a integer array // contains the index of the element // index of 'C#' int[] indx = new int[4]{0, 1, 1, 2}; // "indx" array is passing // to GetValue(Int32[]) method Console.WriteLine("Element at index [0, 1, 1, 2] is : {0}", arr.GetValue(indx)); }} Element at index [0, 1, 1, 2] is : GO Note: For online compiler it is not possible to use 32-bit or 64-bit integer. Use offline compiler for 32 or 64-bit integer. CSharp-Arrays CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 C# Interview Questions & Answers Extension Method in C# HashSet in C# with Examples Partial Classes in C# C# | Inheritance Convert String to Character Array in C# Linked List Implementation in C# C# | How to insert an element in an Array? C# | List Class Difference between Hashtable and Dictionary in C#
[ { "code": null, "e": 23911, "s": 23883, "text": "\n17 May, 2020" }, { "code": null, "e": 24098, "s": 23911, "text": "Array.GetValue() Method in C# is used to gets the value of the specified element in the current Array. There are total 8 methods in the overload list of this method which are as follows:" }, { "code": null, "e": 24127, "s": 24098, "text": "Array.GetValue(Int32, Int32)" }, { "code": null, "e": 24156, "s": 24127, "text": "Array.GetValue(Int64, Int64)" }, { "code": null, "e": 24178, "s": 24156, "text": "Array.GetValue(Int32)" }, { "code": null, "e": 24200, "s": 24178, "text": "Array.GetValue(Int64)" }, { "code": null, "e": 24236, "s": 24200, "text": "Array.GetValue(Int32, Int32, Int32)" }, { "code": null, "e": 24272, "s": 24236, "text": "Array.GetValue(Int64, Int64, Int64)" }, { "code": null, "e": 24296, "s": 24272, "text": "Array.GetValue(Int32[])" }, { "code": null, "e": 24320, "s": 24296, "text": "Array.GetValue(Int64[])" }, { "code": null, "e": 24414, "s": 24320, "text": "In this article we are explaining Array.GetValue(Int32[]) and Array.GetValue(Int64[]) method." }, { "code": null, "e": 24825, "s": 24414, "text": "Array.GetValue(Int32[]) method is used to get the value at the specified position in the multidimensional-dimensional Array. The indexes are passed to this method by a 1D array, that means the 1D array which is passed that contains the specified index as array element of 1D array, and the element is to be searched that is at that index which is in the 1D array. The indexes are specified as 32-bit integers. " }, { "code": null, "e": 24835, "s": 24825, "text": "Syntax: " }, { "code": null, "e": 24874, "s": 24835, "text": "public object GetValue (int[] index);\n" }, { "code": null, "e": 25010, "s": 24874, "text": "Here “index” is a 1D array of 32-bit integers that represent the index specifying the position of the element to be searched. searched." }, { "code": null, "e": 25165, "s": 25010, "text": "Returns: This method returns the element at the specified index define by the passed 1D array to the GetValue method. The value is a 32-bit integer value." }, { "code": null, "e": 25177, "s": 25165, "text": "Exceptions:" }, { "code": null, "e": 25335, "s": 25177, "text": "ArgumentException: If the number of dimensions in the current array is not equal to the number of elements in index array which is passed to GetValue method." }, { "code": null, "e": 25507, "s": 25335, "text": "IndexOutOfRangeException: If the elements in index array defines a range which is outside the range of valid indexes for the corresponding dimension of the current array ." }, { "code": null, "e": 25573, "s": 25507, "text": "ArgumentNullException: if the index array is null then it throws." }, { "code": null, "e": 25986, "s": 25575, "text": "Array.GetValue(Int64[]) method is used to get the value at the specified position in the multidimensional-dimensional Array. The indexes are passed to this method by a 1D array, that means the 1D array which is passed that contains the specified index as array element of 1D array, and the element is to be searched that is at that index which is in the 1D array. The indexes are specified as 64-bit integers. " }, { "code": null, "e": 25995, "s": 25986, "text": "Syntax: " }, { "code": null, "e": 26035, "s": 25995, "text": "public object GetValue (long[] index);\n" }, { "code": null, "e": 26164, "s": 26035, "text": "Here, “index[]” is a 1D array of 64-bit integers that represent the index specifying the position of the element to be searched." }, { "code": null, "e": 26319, "s": 26164, "text": "Returns: This method returns the element at the specified index define by the passed 1D array to the GetValue method. The value is a 32-bit integer value." }, { "code": null, "e": 26331, "s": 26319, "text": "Exceptions:" }, { "code": null, "e": 26489, "s": 26331, "text": "ArgumentException: If the number of dimensions in the current array is not equal to the number of elements in index array which is passed to GetValue method." }, { "code": null, "e": 26664, "s": 26489, "text": "ArgumentOutOfRangeException: If the elements in index array defines a range which is outside the range of valid indexes for the corresponding dimension of the current array ." }, { "code": null, "e": 26730, "s": 26664, "text": "ArgumentNullException: if the index array is null then it throws." }, { "code": null, "e": 26742, "s": 26730, "text": "Example 1: " }, { "code": null, "e": 26745, "s": 26742, "text": "C#" }, { "code": "// C# program to demonstrate the// Array.GetValue(Int32[]) and// Array.GetValue(Int64[]) methodusing System;public class GFG { public static void Main() { // declare a character // array of size 1x2x2x3 // it has 2 3D array // which have 2 row and 3 column each char[, , , ] arr = new char[1, 2, 2, 3]{ { {// array 1 {'A', 'B', 'C'}, {'D', 'E', 'F'} }, {// array 2 {'G', 'H', 'I'}, {'J', 'K', 'L'}} } /*Array look like |----------------------------------| | -------------------------------- | | |A| |B| |C| | | |D| |E| |F| | | -------------------------------- | | -------------------------------- | | |G| |H| |I| | | |J| |K| |L| | | -------------------------------- | |__________________________________| */ }; // initialize a integer array // contains the index of the element // index of 'L' int[] indx = new int[4]{0, 1, 1, 2}; // \"indx\" array is passing // to GetValue(Int32[]) method Console.WriteLine(\"Element at index [0, 1, 1, 2] is : {0}\", arr.GetValue(indx)); }}", "e": 28023, "s": 26745, "text": null }, { "code": null, "e": 28061, "s": 28023, "text": "Element at index [0, 1, 1, 2] is : L\n" }, { "code": null, "e": 28074, "s": 28063, "text": "Example 2:" }, { "code": null, "e": 28077, "s": 28074, "text": "C#" }, { "code": "// C# program to demonstrate the// Array.GetValue(Int32[]) and// Array.GetValue(Int64[]) methodusing System; class GFG { public static void Main() { // declare a character // array of size 1x2x2x3 // it has 2 3D array // which have 2 row and // 3 column each string[, , , ] arr = new string[1, 2, 2, 3]; /*Array look like|------------------------------------|| ---------------------------------- || |C++| |Java| |C#| || |Perl| |python| |PHP| || ---------------------------------- || ---------------------------------- || |Ruby| |F#| |Julia| || |SQL| |Kotlin| |GO| || ---------------------------------- ||____________________________________|*/ arr.SetValue(\"C++\", 0, 0, 0, 0); arr.SetValue(\"Java\", 0, 0, 0, 1); arr.SetValue(\"C#\", 0, 0, 0, 2); arr.SetValue(\"Perl\", 0, 0, 1, 0); arr.SetValue(\"Python\", 0, 0, 1, 1); arr.SetValue(\"PHP\", 0, 0, 1, 2); arr.SetValue(\"Ruby\", 0, 1, 0, 1); arr.SetValue(\"F#\", 0, 1, 0, 1); arr.SetValue(\"Julia\", 0, 1, 0, 2); arr.SetValue(\"SQL\", 0, 1, 1, 0); arr.SetValue(\"kotlin\", 0, 1, 1, 1); arr.SetValue(\"GO\", 0, 1, 1, 2); // initialize a integer array // contains the index of the element // index of 'C#' int[] indx = new int[4]{0, 1, 1, 2}; // \"indx\" array is passing // to GetValue(Int32[]) method Console.WriteLine(\"Element at index [0, 1, 1, 2] is : {0}\", arr.GetValue(indx)); }}", "e": 29585, "s": 28077, "text": null }, { "code": null, "e": 29624, "s": 29585, "text": "Element at index [0, 1, 1, 2] is : GO\n" }, { "code": null, "e": 29749, "s": 29624, "text": "Note: For online compiler it is not possible to use 32-bit or 64-bit integer. Use offline compiler for 32 or 64-bit integer." }, { "code": null, "e": 29763, "s": 29749, "text": "CSharp-Arrays" }, { "code": null, "e": 29777, "s": 29763, "text": "CSharp-method" }, { "code": null, "e": 29780, "s": 29777, "text": "C#" }, { "code": null, "e": 29878, "s": 29780, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29887, "s": 29878, "text": "Comments" }, { "code": null, "e": 29900, "s": 29887, "text": "Old Comments" }, { "code": null, "e": 29940, "s": 29900, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 29963, "s": 29940, "text": "Extension Method in C#" }, { "code": null, "e": 29991, "s": 29963, "text": "HashSet in C# with Examples" }, { "code": null, "e": 30013, "s": 29991, "text": "Partial Classes in C#" }, { "code": null, "e": 30030, "s": 30013, "text": "C# | Inheritance" }, { "code": null, "e": 30070, "s": 30030, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 30103, "s": 30070, "text": "Linked List Implementation in C#" }, { "code": null, "e": 30146, "s": 30103, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 30162, "s": 30146, "text": "C# | List Class" } ]
Absolute List Sorting | Practice | GeeksforGeeks
Given a linked list L of N nodes, sorted in ascending order based on the absolute values of its data,i.e. negative values are considered as positive ones. Sort the linked list according to the actual values, consider negative numbers as negative and positive number as positive. Example 1: Input: List: 1, -2, -3, 4, -5 Output: List: -5, -3, -2, 1, 4 Example 2: Input: List: 5, -10 Output: List: -10, 5 Your Task: You don't need to read or print anyhting. Your Task is to comple the function sortList() which takes the head of the Linked List as input parameter and sort the list in ascending order. Don't create a new Linked List instead rearrange the given List. Expected Time Complexity: O(N) Expected Space Complexity: O(1) Constraints 1 ≤ N ≤ 104 -105 ≤ L[i] ≤ 105 0 tthakare733 days ago Don't Follow This //java solution -> TC -> 1.29 class GfG{ Node sortList(Node head) { // Your code here ArrayList<Integer> adj = new ArrayList<>(); while(head != null){ adj.add(head.data ); head = head.next; } Collections.sort(adj); Node returnNull = null; for(int i = 0; i < adj.size(); i++){ if(i == adj.size() - 1){ System.out.print(adj.get(i)); } else { System.out.print(adj.get(i)+" "); } } return returnNull; } } +1 shahabuddinbravo405 days ago class Solution{public: void sortList(Node** head) { // Node *ptr=*head; // T(n)=O(N*logN) : s.c(n)=O(n); // priority_queue<int,vector<int>,greater<int>> minH; // while(ptr){ // minH.push(ptr->data); // ptr=ptr->next; // } // ptr=*head; // while(ptr){ // ptr->data=minH.top(); // minH.pop(); // ptr=ptr->next; // } // vector<int>positive; // T(n)=O(n) : S.C = O(n); // vector<int>negative; // Node *ptr=*head; // while(ptr) // { // if(ptr->data<0){ // negative.push_back(ptr->data); // } // else{ // positive.push_back(ptr->data); // } // ptr=ptr->next; // } // ptr=*head; // while(ptr){ // for(int i=0;i<negative.size();i++){ // ptr->data=negative[negative.size()-1-i]; // ptr=ptr->next; // } // for(int i=0;i<positive.size();i++){ // ptr->data=positive[i]; // ptr=ptr->next; // } // } }}; 0 rishu1 week ago class GfG { Node sortList(Node head) { // Your code here Node prev=head; Node curr=head.next; while(curr!=null){ if(curr.data<0){ Node buff = curr.next; curr.next = head; prev.next = buff; head=curr; curr=prev.next; continue; } prev=curr; curr=curr.next; } return head; } } 0 vt28522412 months ago Simple Solution : JAVA Node sortList(Node head) { Node curr=head; while(curr.next!=null){ if(curr.next.data<0){ Node temp=curr.next; curr.next=curr.next.next; temp.next=head; head=temp; } else{ curr=curr.next; } } return head;} 0 owaischem2 months ago def sortList(head): n=head list1=[] while n!=None: list1.append(n.data) n=n.next list1.sort() n=head head=n count=0 while n!=None: n.data=list1[count] n=n.next count+=1 return head 0 sharma_nitin_262 months ago bubble sort class Solution { public: void sortList(Node** head){ Node *temp=*head; Node *index=NULL; int tep=0; while(temp!=NULL) { index=temp->next; while(index!=NULL){ if(temp->data>index->data){ tep=temp->data; temp->data=index->data; index->data=tep; } index=index->next; } temp=temp->next; } } }; 0 anirudhkrishna222 months ago void sortList(Node** head) { Node* prev=*head; Node* cur=prev->next; while(cur) { if(cur->data<prev->data) { prev->next=cur->next; cur->next=*head; *head=cur; cur=prev->next; } else { cur=cur->next; prev=prev->next; } } } 0 ashmeetsingh78012 months ago void sortList(Node** head) { Node* prev = (*head); Node* curr = (*head)->next; while (curr != NULL) { if (curr->data < prev->data) { prev->next = curr->next; curr->next = (*head); (*head) = curr; curr = prev; } else prev = curr; curr = curr->next; } } 0 indiakamanthan3 months ago class GfG { Node sortList(Node head) { Node h=head.next; Node prev=head; Node hh=head; while(h!=null) { if(h.data<0) { prev.next=h.next; h.next=hh; hh=h; h=prev.next; } else { prev=h; h=h.next; } } prev=null; return hh; } } +1 ap123413 months ago Solution in Java class GfG{Node sortList(Node head) { Node prev = head; Node curr = head.next; while(curr != null){ if(curr.data < prev.data){ prev.next = curr.next; curr.next = head; head = curr; curr = prev; }else{ prev = curr; } curr = curr.next; } return head; }} 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": 517, "s": 238, "text": "Given a linked list L of N nodes, sorted in ascending order based on the absolute values of its data,i.e. negative values are considered as positive ones. Sort the linked list according to the actual values, consider negative numbers as negative and positive number as positive." }, { "code": null, "e": 531, "s": 517, "text": "\nExample 1: " }, { "code": null, "e": 594, "s": 531, "text": "Input: \nList: 1, -2, -3, 4, -5\nOutput: \nList: -5, -3, -2, 1, 4" }, { "code": null, "e": 609, "s": 596, "text": "Example 2: " }, { "code": null, "e": 652, "s": 609, "text": "Input: \nList: 5, -10\nOutput: \nList: -10, 5" }, { "code": null, "e": 916, "s": 654, "text": "Your Task:\nYou don't need to read or print anyhting. Your Task is to comple the function sortList() which takes the head of the Linked List as input parameter and sort the list in ascending order. Don't create a new Linked List instead rearrange the given List." }, { "code": null, "e": 981, "s": 918, "text": "Expected Time Complexity: O(N)\nExpected Space Complexity: O(1)" }, { "code": null, "e": 1026, "s": 981, "text": "\nConstraints\n1 ≤ N ≤ 104\n-105 ≤ L[i] ≤ 105" }, { "code": null, "e": 1028, "s": 1026, "text": "0" }, { "code": null, "e": 1049, "s": 1028, "text": "tthakare733 days ago" }, { "code": null, "e": 1067, "s": 1049, "text": "Don't Follow This" }, { "code": null, "e": 1545, "s": 1069, "text": "//java solution -> TC -> 1.29\nclass GfG{\n\tNode sortList(Node head) {\n\t\t// Your code here\n\t\tArrayList<Integer> adj = new ArrayList<>();\n\t\twhile(head != null){\n\t\t adj.add(head.data );\n\t\t head = head.next;\n\t\t}\n\t\tCollections.sort(adj);\n\t\tNode returnNull = null;\n\t\n\t\tfor(int i = 0; i < adj.size(); i++){\n\t\t if(i == adj.size() - 1){\n\t\t System.out.print(adj.get(i));\n\t\t } else {\n\t\t System.out.print(adj.get(i)+\" \"); \n\t\t }\n\t\t}\n\t\treturn returnNull;\n\t}\n}" }, { "code": null, "e": 1548, "s": 1545, "text": "+1" }, { "code": null, "e": 1577, "s": 1548, "text": "shahabuddinbravo405 days ago" }, { "code": null, "e": 2779, "s": 1577, "text": "class Solution{public: void sortList(Node** head) { // Node *ptr=*head; // T(n)=O(N*logN) : s.c(n)=O(n); // priority_queue<int,vector<int>,greater<int>> minH; // while(ptr){ // minH.push(ptr->data); // ptr=ptr->next; // } // ptr=*head; // while(ptr){ // ptr->data=minH.top(); // minH.pop(); // ptr=ptr->next; // } // vector<int>positive; // T(n)=O(n) : S.C = O(n); // vector<int>negative; // Node *ptr=*head; // while(ptr) // { // if(ptr->data<0){ // negative.push_back(ptr->data); // } // else{ // positive.push_back(ptr->data); // } // ptr=ptr->next; // } // ptr=*head; // while(ptr){ // for(int i=0;i<negative.size();i++){ // ptr->data=negative[negative.size()-1-i]; // ptr=ptr->next; // } // for(int i=0;i<positive.size();i++){ // ptr->data=positive[i]; // ptr=ptr->next; // } // } }}; " }, { "code": null, "e": 2781, "s": 2779, "text": "0" }, { "code": null, "e": 2797, "s": 2781, "text": "rishu1 week ago" }, { "code": null, "e": 3152, "s": 2797, "text": "class GfG\n{\nNode sortList(Node head) {\n // Your code here \n Node prev=head;\n Node curr=head.next;\n while(curr!=null){\n if(curr.data<0){\n Node buff = curr.next;\n curr.next = head;\n prev.next = buff;\n head=curr;\n curr=prev.next;\n continue;\n }\n prev=curr;\n curr=curr.next;\n }\n return head;\n}\n}" }, { "code": null, "e": 3154, "s": 3152, "text": "0" }, { "code": null, "e": 3176, "s": 3154, "text": "vt28522412 months ago" }, { "code": null, "e": 3199, "s": 3176, "text": "Simple Solution : JAVA" }, { "code": null, "e": 3470, "s": 3199, "text": "Node sortList(Node head) { Node curr=head; while(curr.next!=null){ if(curr.next.data<0){ Node temp=curr.next; curr.next=curr.next.next; temp.next=head; head=temp; } else{ curr=curr.next; } } return head;}" }, { "code": null, "e": 3472, "s": 3470, "text": "0" }, { "code": null, "e": 3494, "s": 3472, "text": "owaischem2 months ago" }, { "code": null, "e": 3747, "s": 3494, "text": "def sortList(head): n=head list1=[] while n!=None: list1.append(n.data) n=n.next list1.sort() n=head head=n count=0 while n!=None: n.data=list1[count] n=n.next count+=1 return head" }, { "code": null, "e": 3749, "s": 3747, "text": "0" }, { "code": null, "e": 3777, "s": 3749, "text": "sharma_nitin_262 months ago" }, { "code": null, "e": 4311, "s": 3777, "text": "bubble sort\n\nclass Solution\n{\npublic:\n void sortList(Node** head){\n Node *temp=*head;\n Node *index=NULL;\n int tep=0;\n\n while(temp!=NULL)\n {\n index=temp->next;\n while(index!=NULL){\n if(temp->data>index->data){ \n tep=temp->data;\n temp->data=index->data;\n index->data=tep;\n }\n index=index->next;\n }\n temp=temp->next;\n }\n }\n};" }, { "code": null, "e": 4313, "s": 4311, "text": "0" }, { "code": null, "e": 4342, "s": 4313, "text": "anirudhkrishna222 months ago" }, { "code": null, "e": 4742, "s": 4342, "text": "void sortList(Node** head) { Node* prev=*head; Node* cur=prev->next; while(cur) { if(cur->data<prev->data) { prev->next=cur->next; cur->next=*head; *head=cur; cur=prev->next; } else { cur=cur->next; prev=prev->next; } } }" }, { "code": null, "e": 4744, "s": 4742, "text": "0" }, { "code": null, "e": 4773, "s": 4744, "text": "ashmeetsingh78012 months ago" }, { "code": null, "e": 5173, "s": 4773, "text": "void sortList(Node** head) { Node* prev = (*head); Node* curr = (*head)->next; while (curr != NULL) { if (curr->data < prev->data) { prev->next = curr->next; curr->next = (*head); (*head) = curr; curr = prev; } else prev = curr; curr = curr->next; } }" }, { "code": null, "e": 5175, "s": 5173, "text": "0" }, { "code": null, "e": 5202, "s": 5175, "text": "indiakamanthan3 months ago" }, { "code": null, "e": 5537, "s": 5202, "text": "\nclass GfG\n{\nNode sortList(Node head) {\n Node h=head.next;\n Node prev=head;\n Node hh=head;\n \n while(h!=null)\n{\n if(h.data<0)\n {\n prev.next=h.next;\n h.next=hh;\n hh=h;\n h=prev.next;\n \n }\n else\n {\n prev=h;\n h=h.next;\n }\n}\n prev=null;\nreturn hh;\n\n \n}\n\n}" }, { "code": null, "e": 5540, "s": 5537, "text": "+1" }, { "code": null, "e": 5560, "s": 5540, "text": "ap123413 months ago" }, { "code": null, "e": 5577, "s": 5560, "text": "Solution in Java" }, { "code": null, "e": 5903, "s": 5577, "text": "class GfG{Node sortList(Node head) { Node prev = head; Node curr = head.next; while(curr != null){ if(curr.data < prev.data){ prev.next = curr.next; curr.next = head; head = curr; curr = prev; }else{ prev = curr; } curr = curr.next; } return head; }} " }, { "code": null, "e": 6049, "s": 5903, "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": 6085, "s": 6049, "text": " Login to access your submissions. " }, { "code": null, "e": 6095, "s": 6085, "text": "\nProblem\n" }, { "code": null, "e": 6105, "s": 6095, "text": "\nContest\n" }, { "code": null, "e": 6168, "s": 6105, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6316, "s": 6168, "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": 6524, "s": 6316, "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": 6630, "s": 6524, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
PHP | array_keys() Function - GeeksforGeeks
11 Nov, 2021 The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Syntax: array array_keys($input_array, $search_value, $strict) Parameters: The function takes three parameters out of which one is mandatory and other two are optional. $input_array (mandatory): Refers to the array that we want to operate on.$search_value (optional): Refers to the value of the array by which we want to search the array for the key elements. If this parameter is passed then the function will return keys corresponding to this element only otherwise it will return all keys of the array.$strict (optional): Determines if strict comparison (===) should be used during the search. false is the default value. $input_array (mandatory): Refers to the array that we want to operate on. $search_value (optional): Refers to the value of the array by which we want to search the array for the key elements. If this parameter is passed then the function will return keys corresponding to this element only otherwise it will return all keys of the array. $strict (optional): Determines if strict comparison (===) should be used during the search. false is the default value. Return Value: The function returns an array containing either all of the keys or subset of keys the input array depending upon the parameters passed. Examples: Input : $input_array = ("one" => "shyam", 2 => "rishav", "three" => "gaurav") Output : Array ( [0] => one [1] => 2 [2] => three ) Input : $input_array = ("one", "two", "three", "one", "four", "three", "one", "one") $search_value = "one" Output : Array ( [0] => 0 [1] => 3 [2] => 6 [3] => 7 ) In the below program, we have passed a simple associative array to the function array_keys(), to print all of its keys: <?php // PHP function to illustrate the use of array_keys()function get_Key($array){ $result = array_keys($array); return($result);} $array = array("one" => "shyam", 2 => "rishav", "three" => "gaurav");print_r(get_Key($array)); ?> Output: Array ( [0] => one [1] => 2 [2] => three ) In the below program, along with the array we have passed a value only for which the key position is returned. <?php // PHP function to illustrate the use of array_keys()function get_Key($array, $search_value){ $result = array_keys($array, $search_value); return($result);} $array = array("one", "two", "three", "one", "four", "three", "one", "one");$search_value = "one";print_r(get_Key($array, $search_value)); ?> Output: Array ( [0] => 0 [1] => 3 [2] => 6 [3] => 7 ) Reference: http://php.net/manual/en/function.array-keys.php surindertarika1234 PHP-array PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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? PHP | Converting string to Date and DateTime Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26099, "s": 26071, "text": "\n11 Nov, 2021" }, { "code": null, "e": 26228, "s": 26099, "text": "The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys." }, { "code": null, "e": 26236, "s": 26228, "text": "Syntax:" }, { "code": null, "e": 26291, "s": 26236, "text": "array array_keys($input_array, $search_value, $strict)" }, { "code": null, "e": 26397, "s": 26291, "text": "Parameters: The function takes three parameters out of which one is mandatory and other two are optional." }, { "code": null, "e": 26853, "s": 26397, "text": "$input_array (mandatory): Refers to the array that we want to operate on.$search_value (optional): Refers to the value of the array by which we want to search the array for the key elements. If this parameter is passed then the function will return keys corresponding to this element only otherwise it will return all keys of the array.$strict (optional): Determines if strict comparison (===) should be used during the search. false is the default value." }, { "code": null, "e": 26927, "s": 26853, "text": "$input_array (mandatory): Refers to the array that we want to operate on." }, { "code": null, "e": 27191, "s": 26927, "text": "$search_value (optional): Refers to the value of the array by which we want to search the array for the key elements. If this parameter is passed then the function will return keys corresponding to this element only otherwise it will return all keys of the array." }, { "code": null, "e": 27311, "s": 27191, "text": "$strict (optional): Determines if strict comparison (===) should be used during the search. false is the default value." }, { "code": null, "e": 27461, "s": 27311, "text": "Return Value: The function returns an array containing either all of the keys or subset of keys the input array depending upon the parameters passed." }, { "code": null, "e": 27471, "s": 27461, "text": "Examples:" }, { "code": null, "e": 27881, "s": 27471, "text": "Input : $input_array = (\"one\" => \"shyam\", 2 => \"rishav\", \n \"three\" => \"gaurav\") \nOutput :\nArray\n(\n [0] => one\n [1] => 2\n [2] => three\n)\n\nInput : $input_array = (\"one\", \"two\", \"three\", \"one\", \n \"four\", \"three\", \"one\", \"one\")\n $search_value = \"one\"\nOutput :\nArray\n(\n [0] => 0\n [1] => 3\n [2] => 6\n [3] => 7\n)\n" }, { "code": null, "e": 28001, "s": 27881, "text": "In the below program, we have passed a simple associative array to the function array_keys(), to print all of its keys:" }, { "code": "<?php // PHP function to illustrate the use of array_keys()function get_Key($array){ $result = array_keys($array); return($result);} $array = array(\"one\" => \"shyam\", 2 => \"rishav\", \"three\" => \"gaurav\");print_r(get_Key($array)); ?>", "e": 28270, "s": 28001, "text": null }, { "code": null, "e": 28278, "s": 28270, "text": "Output:" }, { "code": null, "e": 28334, "s": 28278, "text": "Array\n(\n [0] => one\n [1] => 2\n [2] => three\n)\n" }, { "code": null, "e": 28445, "s": 28334, "text": "In the below program, along with the array we have passed a value only for which the key position is returned." }, { "code": "<?php // PHP function to illustrate the use of array_keys()function get_Key($array, $search_value){ $result = array_keys($array, $search_value); return($result);} $array = array(\"one\", \"two\", \"three\", \"one\", \"four\", \"three\", \"one\", \"one\");$search_value = \"one\";print_r(get_Key($array, $search_value)); ?>", "e": 28790, "s": 28445, "text": null }, { "code": null, "e": 28798, "s": 28790, "text": "Output:" }, { "code": null, "e": 28861, "s": 28798, "text": "Array\n(\n [0] => 0\n [1] => 3\n [2] => 6\n [3] => 7\n)\n" }, { "code": null, "e": 28921, "s": 28861, "text": "Reference: http://php.net/manual/en/function.array-keys.php" }, { "code": null, "e": 28940, "s": 28921, "text": "surindertarika1234" }, { "code": null, "e": 28950, "s": 28940, "text": "PHP-array" }, { "code": null, "e": 28963, "s": 28950, "text": "PHP-function" }, { "code": null, "e": 28967, "s": 28963, "text": "PHP" }, { "code": null, "e": 28984, "s": 28967, "text": "Web Technologies" }, { "code": null, "e": 28988, "s": 28984, "text": "PHP" }, { "code": null, "e": 29086, "s": 28988, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29136, "s": 29086, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 29176, "s": 29136, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 29237, "s": 29176, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 29287, "s": 29237, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 29332, "s": 29287, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 29372, "s": 29332, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29405, "s": 29372, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29450, "s": 29405, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29493, "s": 29450, "text": "How to fetch data from an API in ReactJS ?" } ]
How to Create Dummy Variables in Python with Pandas? - GeeksforGeeks
16 Jan, 2022 A dataset may contain various type of values, sometimes it consists of categorical values. So, in-order to use those categorical value for programming efficiently we create dummy variables. A dummy variable is a binary variable that indicates whether a separate categorical variable takes on a specific value. Explanation: As you can see three dummy variables are created for the three categorical values of the temperature attribute. We can create dummy variables in python using get_dummies() method. Syntax: pandas.get_dummies(data, prefix=None, prefix_sep=’_’,) Parameters: data= input data i.e. it includes pandas data frame. list . set . numpy arrays etc. prefix= Initial value prefix_sep= Data values separation. Return Type: Dummy variables. Step-by-step Approach: Import necessary modules Consider the data Perform operations on data to get dummies Example 1: Python3 # import required modulesimport pandas as pdimport numpy as np # create datasetdf = pd.DataFrame({'Temperature': ['Hot', 'Cold', 'Warm', 'Cold'], }) # display datasetprint(df) # create dummy variablespd.get_dummies(df) Output: Example 2: Consider List arrays to get dummies Python3 # import required modulesimport pandas as pdimport numpy as np # create datasets = pd.Series(list('abca')) # display datasetprint(s) # create dummy variablespd.get_dummies(s) Output: Example 3: Here is another example, to get dummy variables. Python3 # import required modulesimport pandas as pdimport numpy as np # create datasetdf = pd.DataFrame({'A': ['hello', 'vignan', 'geeks'], 'B': ['vignan', 'hello', 'hello'], 'C': [1, 2, 3]}) # display datasetprint(df) # create dummy variablespd.get_dummies(df) Output: sooda367 saurabh1990aror Python-numpy Python-pandas Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26139, "s": 26111, "text": "\n16 Jan, 2022" }, { "code": null, "e": 26450, "s": 26139, "text": "A dataset may contain various type of values, sometimes it consists of categorical values. So, in-order to use those categorical value for programming efficiently we create dummy variables. A dummy variable is a binary variable that indicates whether a separate categorical variable takes on a specific value. " }, { "code": null, "e": 26463, "s": 26450, "text": "Explanation:" }, { "code": null, "e": 26643, "s": 26463, "text": "As you can see three dummy variables are created for the three categorical values of the temperature attribute. We can create dummy variables in python using get_dummies() method." }, { "code": null, "e": 26706, "s": 26643, "text": "Syntax: pandas.get_dummies(data, prefix=None, prefix_sep=’_’,)" }, { "code": null, "e": 26718, "s": 26706, "text": "Parameters:" }, { "code": null, "e": 26802, "s": 26718, "text": "data= input data i.e. it includes pandas data frame. list . set . numpy arrays etc." }, { "code": null, "e": 26824, "s": 26802, "text": "prefix= Initial value" }, { "code": null, "e": 26860, "s": 26824, "text": "prefix_sep= Data values separation." }, { "code": null, "e": 26890, "s": 26860, "text": "Return Type: Dummy variables." }, { "code": null, "e": 26913, "s": 26890, "text": "Step-by-step Approach:" }, { "code": null, "e": 26938, "s": 26913, "text": "Import necessary modules" }, { "code": null, "e": 26956, "s": 26938, "text": "Consider the data" }, { "code": null, "e": 26998, "s": 26956, "text": "Perform operations on data to get dummies" }, { "code": null, "e": 27010, "s": 26998, "text": "Example 1: " }, { "code": null, "e": 27018, "s": 27010, "text": "Python3" }, { "code": "# import required modulesimport pandas as pdimport numpy as np # create datasetdf = pd.DataFrame({'Temperature': ['Hot', 'Cold', 'Warm', 'Cold'], }) # display datasetprint(df) # create dummy variablespd.get_dummies(df)", "e": 27255, "s": 27018, "text": null }, { "code": null, "e": 27263, "s": 27255, "text": "Output:" }, { "code": null, "e": 27274, "s": 27263, "text": "Example 2:" }, { "code": null, "e": 27310, "s": 27274, "text": "Consider List arrays to get dummies" }, { "code": null, "e": 27318, "s": 27310, "text": "Python3" }, { "code": "# import required modulesimport pandas as pdimport numpy as np # create datasets = pd.Series(list('abca')) # display datasetprint(s) # create dummy variablespd.get_dummies(s)", "e": 27493, "s": 27318, "text": null }, { "code": null, "e": 27501, "s": 27493, "text": "Output:" }, { "code": null, "e": 27513, "s": 27501, "text": "Example 3: " }, { "code": null, "e": 27562, "s": 27513, "text": "Here is another example, to get dummy variables." }, { "code": null, "e": 27570, "s": 27562, "text": "Python3" }, { "code": "# import required modulesimport pandas as pdimport numpy as np # create datasetdf = pd.DataFrame({'A': ['hello', 'vignan', 'geeks'], 'B': ['vignan', 'hello', 'hello'], 'C': [1, 2, 3]}) # display datasetprint(df) # create dummy variablespd.get_dummies(df)", "e": 27861, "s": 27570, "text": null }, { "code": null, "e": 27869, "s": 27861, "text": "Output:" }, { "code": null, "e": 27878, "s": 27869, "text": "sooda367" }, { "code": null, "e": 27894, "s": 27878, "text": "saurabh1990aror" }, { "code": null, "e": 27907, "s": 27894, "text": "Python-numpy" }, { "code": null, "e": 27921, "s": 27907, "text": "Python-pandas" }, { "code": null, "e": 27945, "s": 27921, "text": "Technical Scripter 2020" }, { "code": null, "e": 27952, "s": 27945, "text": "Python" }, { "code": null, "e": 27971, "s": 27952, "text": "Technical Scripter" }, { "code": null, "e": 28069, "s": 27971, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28087, "s": 28069, "text": "Python Dictionary" }, { "code": null, "e": 28122, "s": 28087, "text": "Read a file line by line in Python" }, { "code": null, "e": 28154, "s": 28122, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28176, "s": 28154, "text": "Enumerate() in Python" }, { "code": null, "e": 28218, "s": 28176, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28248, "s": 28218, "text": "Iterate over a list in Python" }, { "code": null, "e": 28274, "s": 28248, "text": "Python String | replace()" }, { "code": null, "e": 28303, "s": 28274, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28347, "s": 28303, "text": "Reading and Writing to text files in Python" } ]
Game of stones - GeeksforGeeks
10 May, 2021 Given an integer N which is the number of stones in a pile and the game of stones is being played between you and your friend, the task is to find whether you’ll win or not. A player (on his/her turn) can remove 1 or 2 or 3 coins, the game continues in alternating turns. The one who is not able to make the move loses the game. In other words, the player who removes last set of coins always wins. Print YES if you can win the game else print NO. Examples: Input: N = 4 Output: NO If there are 4 stones in the bag, then you will never win the game. No matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. Hence, you are not able to make the move.Input: N = 3 Output: YES Yes you can win the game, you just remove all 3 stones in your turn. Approach: First consider base cases, i.e for n = [1, 2, 3]. In these cases you always win as you can pick all stone and your friend is not able to make the move. If n = 4, you will lose. Because no matter how many you take, you will leave some stones behind for your friend to take and win the game. So in order to win, you have to ensure that you never reach the situation where there are exactly four stones left when your turn comes up. Similarly, if there are 5, 6, or 7 stones you can win by taking just enough to leave 4 stones for your friend. But if there are 8 stones on the pile, you will lose because regardless whether you pick 1, 2 or 3 stones, your friend can pick 3, 2 or 1 stone to ensure that, again, 4 stones will be left for you . It is obvious that the same pattern repeats, so, if n % 4 == 0 then you will always lose. Below is the implementation of the above approach: C++ Java python 3 C# PHP Javascript // C++ program of game of stones#include <bits/stdc++.h>using namespace std; // Function that returns true if u winbool checkWin(int n){ if (n % 4 != 0) return true; return false;} // Driver codeint main(){ // n is number of stones int n = 4; if (checkWin(n)) cout << "YES" << endl; else cout << "NO" << endl; return 0;} // Java program of game of stonesimport java.io.*; class GFG { // Function that returns true if u winstatic boolean checkWin(int n){ if (n % 4 != 0) return true; return false;} // Driver code public static void main (String[] args) { // n is number of stones int n = 4; if (checkWin(n)) System.out.println("YES"); else System.out.println( "NO"); }//This code is contributed by akt_mit } # Python3 program of game of stones # Function that returns true if u windef checkWin( n): if (n % 4 != 0): return True return False # Driver codeif __name__ == "__main__": # n is number of stones n = 4 if (checkWin(n)): print ( "YES") else: print ("NO") //C# program of game of stonesusing System; public class GFG{// Function that returns true if u winstatic bool checkWin(int n){ if (n % 4 != 0) return true; return false;} // Driver code static public void Main (){ // n is number of stones int n = 4; if (checkWin(n)) Console.WriteLine("YES"); else Console.WriteLine( "NO"); }//This code is contributed by ajit} <?php// PHP program of game of stones // Function that returns// true if u winfunction checkWin($n){ if ($n % 4 != 0) return true; return false;} // Driver code // n is number of stones$n = 4; if (checkWin($n)) echo "YES","\n" ;else echo "NO","\n" ; // This code is contributed// by ANKITRAI1?> <script> // Javascript program of game of stones // Function that returns true if u win function checkWin(n) { if (n % 4 != 0) return true; return false; } // n is number of stones let n = 4; if (checkWin(n)) document.write("YES"); else document.write( "NO"); </script> NO jit_t ankthon ukasp divyesh072019 Modular Arithmetic School Programming Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Operator Overloading in C++ Copy Constructor in C++ Polymorphism in C++ Friend class and function in C++ Introduction To PYTHON Types of Operating Systems Overriding in Java Constructors in Java Exceptions in Java
[ { "code": null, "e": 25799, "s": 25771, "text": "\n10 May, 2021" }, { "code": null, "e": 26259, "s": 25799, "text": "Given an integer N which is the number of stones in a pile and the game of stones is being played between you and your friend, the task is to find whether you’ll win or not. A player (on his/her turn) can remove 1 or 2 or 3 coins, the game continues in alternating turns. The one who is not able to make the move loses the game. In other words, the player who removes last set of coins always wins. Print YES if you can win the game else print NO. Examples: " }, { "code": null, "e": 26582, "s": 26259, "text": "Input: N = 4 Output: NO If there are 4 stones in the bag, then you will never win the game. No matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. Hence, you are not able to make the move.Input: N = 3 Output: YES Yes you can win the game, you just remove all 3 stones in your turn. " }, { "code": null, "e": 26596, "s": 26584, "text": "Approach: " }, { "code": null, "e": 26748, "s": 26596, "text": "First consider base cases, i.e for n = [1, 2, 3]. In these cases you always win as you can pick all stone and your friend is not able to make the move." }, { "code": null, "e": 27026, "s": 26748, "text": "If n = 4, you will lose. Because no matter how many you take, you will leave some stones behind for your friend to take and win the game. So in order to win, you have to ensure that you never reach the situation where there are exactly four stones left when your turn comes up." }, { "code": null, "e": 27336, "s": 27026, "text": "Similarly, if there are 5, 6, or 7 stones you can win by taking just enough to leave 4 stones for your friend. But if there are 8 stones on the pile, you will lose because regardless whether you pick 1, 2 or 3 stones, your friend can pick 3, 2 or 1 stone to ensure that, again, 4 stones will be left for you ." }, { "code": null, "e": 27426, "s": 27336, "text": "It is obvious that the same pattern repeats, so, if n % 4 == 0 then you will always lose." }, { "code": null, "e": 27478, "s": 27426, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27482, "s": 27478, "text": "C++" }, { "code": null, "e": 27487, "s": 27482, "text": "Java" }, { "code": null, "e": 27496, "s": 27487, "text": "python 3" }, { "code": null, "e": 27499, "s": 27496, "text": "C#" }, { "code": null, "e": 27503, "s": 27499, "text": "PHP" }, { "code": null, "e": 27514, "s": 27503, "text": "Javascript" }, { "code": "// C++ program of game of stones#include <bits/stdc++.h>using namespace std; // Function that returns true if u winbool checkWin(int n){ if (n % 4 != 0) return true; return false;} // Driver codeint main(){ // n is number of stones int n = 4; if (checkWin(n)) cout << \"YES\" << endl; else cout << \"NO\" << endl; return 0;}", "e": 27878, "s": 27514, "text": null }, { "code": "// Java program of game of stonesimport java.io.*; class GFG { // Function that returns true if u winstatic boolean checkWin(int n){ if (n % 4 != 0) return true; return false;} // Driver code public static void main (String[] args) { // n is number of stones int n = 4; if (checkWin(n)) System.out.println(\"YES\"); else System.out.println( \"NO\"); }//This code is contributed by akt_mit }", "e": 28338, "s": 27878, "text": null }, { "code": "# Python3 program of game of stones # Function that returns true if u windef checkWin( n): if (n % 4 != 0): return True return False # Driver codeif __name__ == \"__main__\": # n is number of stones n = 4 if (checkWin(n)): print ( \"YES\") else: print (\"NO\")", "e": 28638, "s": 28338, "text": null }, { "code": "//C# program of game of stonesusing System; public class GFG{// Function that returns true if u winstatic bool checkWin(int n){ if (n % 4 != 0) return true; return false;} // Driver code static public void Main (){ // n is number of stones int n = 4; if (checkWin(n)) Console.WriteLine(\"YES\"); else Console.WriteLine( \"NO\"); }//This code is contributed by ajit}", "e": 29078, "s": 28638, "text": null }, { "code": "<?php// PHP program of game of stones // Function that returns// true if u winfunction checkWin($n){ if ($n % 4 != 0) return true; return false;} // Driver code // n is number of stones$n = 4; if (checkWin($n)) echo \"YES\",\"\\n\" ;else echo \"NO\",\"\\n\" ; // This code is contributed// by ANKITRAI1?>", "e": 29392, "s": 29078, "text": null }, { "code": "<script> // Javascript program of game of stones // Function that returns true if u win function checkWin(n) { if (n % 4 != 0) return true; return false; } // n is number of stones let n = 4; if (checkWin(n)) document.write(\"YES\"); else document.write( \"NO\"); </script>", "e": 29753, "s": 29392, "text": null }, { "code": null, "e": 29756, "s": 29753, "text": "NO" }, { "code": null, "e": 29764, "s": 29758, "text": "jit_t" }, { "code": null, "e": 29772, "s": 29764, "text": "ankthon" }, { "code": null, "e": 29778, "s": 29772, "text": "ukasp" }, { "code": null, "e": 29792, "s": 29778, "text": "divyesh072019" }, { "code": null, "e": 29811, "s": 29792, "text": "Modular Arithmetic" }, { "code": null, "e": 29830, "s": 29811, "text": "School Programming" }, { "code": null, "e": 29849, "s": 29830, "text": "Modular Arithmetic" }, { "code": null, "e": 29947, "s": 29849, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29966, "s": 29947, "text": "Interfaces in Java" }, { "code": null, "e": 29994, "s": 29966, "text": "Operator Overloading in C++" }, { "code": null, "e": 30018, "s": 29994, "text": "Copy Constructor in C++" }, { "code": null, "e": 30038, "s": 30018, "text": "Polymorphism in C++" }, { "code": null, "e": 30071, "s": 30038, "text": "Friend class and function in C++" }, { "code": null, "e": 30094, "s": 30071, "text": "Introduction To PYTHON" }, { "code": null, "e": 30121, "s": 30094, "text": "Types of Operating Systems" }, { "code": null, "e": 30140, "s": 30121, "text": "Overriding in Java" }, { "code": null, "e": 30161, "s": 30140, "text": "Constructors in Java" } ]
GATE | GATE CS 2008 | Question 50 - GeeksforGeeks
28 Jun, 2021 Which of the following statements are true? I. Every left-recursive grammar can be converted to a right-recursive grammar and vice-versa II. All productions can be removed from any context-free grammar by suitable transformations III. The language generated by a context-free grammar all of whose productions are of the form X --> w or X --> wY (where, w is a string of terminals and Y is a non-terminal), is always regular IV. The derivation trees of strings generated by a context-free grammar in Chomsky Normal Form are always binary trees (A) I, II, III and IV(B) II, III and IV only(C) I, III and IV only(D) I, II and IV onlyAnswer: (C)Explanation: I is true as we can always remove left recursion from any given grammar.(For better understanding, see this.) II is false as we can remove all epsilon productions only if grammar doesn’t contain epsilon in the language. III is true as it is the definition of regular grammar.(For better understanding, see type-3 languages in this article.) IV is true because in chomsky normal form, all the productions are of type X -> YZ or X -> t, where X, Y, Z are variables and ‘t’ is terminal string. When we draw the derivation tree for every node there are at most 2 children. That’s why Derivation trees of grammars in chomsky normal form are Binary trees.(For better understanding, see this.) Thus, C is the correct choice.Quiz of this Question GATE-CS-2008 GATE-GATE CS 2008 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25695, "s": 25667, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25739, "s": 25695, "text": "Which of the following statements are true?" }, { "code": null, "e": 26266, "s": 25739, "text": "I. Every left-recursive grammar can be converted to a \n right-recursive grammar and vice-versa\nII. All productions can be removed from any context-free \n grammar by suitable transformations\nIII. The language generated by a context-free grammar all of whose \n productions are of the form X --> w or X --> wY (where, w is a string of \n terminals and Y is a non-terminal), is always regular\nIV. The derivation trees of strings generated by a context-free grammar \n in Chomsky Normal Form are always binary trees " }, { "code": null, "e": 27117, "s": 26266, "text": "(A) I, II, III and IV(B) II, III and IV only(C) I, III and IV only(D) I, II and IV onlyAnswer: (C)Explanation: I is true as we can always remove left recursion from any given grammar.(For better understanding, see this.) II is false as we can remove all epsilon productions only if grammar doesn’t contain epsilon in the language. III is true as it is the definition of regular grammar.(For better understanding, see type-3 languages in this article.) IV is true because in chomsky normal form, all the productions are of type X -> YZ or X -> t, where X, Y, Z are variables and ‘t’ is terminal string. When we draw the derivation tree for every node there are at most 2 children. That’s why Derivation trees of grammars in chomsky normal form are Binary trees.(For better understanding, see this.) Thus, C is the correct choice.Quiz of this Question" }, { "code": null, "e": 27130, "s": 27117, "text": "GATE-CS-2008" }, { "code": null, "e": 27148, "s": 27130, "text": "GATE-GATE CS 2008" }, { "code": null, "e": 27153, "s": 27148, "text": "GATE" }, { "code": null, "e": 27251, "s": 27153, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27285, "s": 27251, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 27319, "s": 27285, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 27353, "s": 27319, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27386, "s": 27353, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 27422, "s": 27386, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27456, "s": 27422, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27492, "s": 27456, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27526, "s": 27492, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27560, "s": 27526, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Find whether an array is subset of another array using Map - GeeksforGeeks
08 Jun, 2021 Given two arrays: arr1[0..m-1] and arr2[0..n-1]. Find whether arr2[] is a subset of arr1[] or not. Both the arrays are not in sorted order. It may be assumed that elements in both arrays are distinct.Examples: Input: arr1[] = {11, 1, 13, 21, 3, 7}, arr2[] = {11, 3, 7, 1} Output: arr2[] is a subset of arr1[] Input: arr1[] = {1, 2, 3, 4, 5, 6}, arr2[] = {1, 2, 4} Output: arr2[] is a subset of arr1[] Input: arr1[] = {10, 5, 2, 23, 19}, arr2[] = {19, 5, 3} Output: arr2[] is not a subset of arr1[] Simple Approach: A simple approach is to run two nested loops. The outer loop picks all the elements of B[] one by one. The inner loop linearly searches for the element picked by the outer loop in A[]. If all elements are found, then print Yes, else print No. You can check the solution here.Efficient Approach: Create a map to store the frequency of each distinct number present in A[]. Then we will check if each number of B[] is present in map or not. If present in the map, we will decrement the frequency value for that number by one and check for the next number. If map value for any number becomes zero, we will erase it from the map. If any number of B[] is not found in the map, we will set the flag value and break the loops and print No. Otherwise, we will print Yes. C++ Java Python C# Javascript // C++ program to check if an array is// subset of another array #include <bits/stdc++.h>using namespace std; // Function to check if an array is// subset of another array int isSubset(int a[], int b[], int m, int n){ // map to store the values of array a[] map<int, int> mp1; for (int i = 0; i < m; i++) mp1[a[i]]++; // flag value int f = 0; for (int i = 0; i < n; i++) { // if b[i] is not present in map // then array b[] can not be a // subset of array a[] if (mp1.find(b[i]) == mp1.end()) { f = 1; break; } // if if b[i] is present in map // decrement by one else { mp1[b[i]]--; if (mp1[b[i]] == 0) mp1.erase(mp1.find(b[i])); } } return f;} // Driver codeint main(){ int arr1[] = { 11, 1, 13, 21, 3, 7 }; int arr2[] = { 11, 3, 7, 1 }; int m = sizeof(arr1) / sizeof(arr1[0]); int n = sizeof(arr2) / sizeof(arr2[0]); if (!isSubset(arr1, arr2, m, n)) cout<<"arr2[] is subset of arr1[] "; else cout<<"arr2[] is not a subset of arr1[]"; return 0;} // Java program to check if an array is// subset of another arrayimport java.util.*; class GFG{ // Function to check if an array is // subset of another array static int isSubset(int a[], int b[], int m, int n) { // map to store the values of array a[] HashMap<Integer, Integer> mp1 = new HashMap<Integer, Integer>(); for (int i = 0; i < m; i++) if (mp1.containsKey(a[i])) { mp1.put(a[i], mp1.get(a[i]) + 1); } else { mp1.put(a[i], 1); } // flag value int f = 0; for (int i = 0; i < n; i++) { // if b[i] is not present in map // then array b[] can not be a // subset of array a[] if (!mp1.containsKey(b[i])) { f = 1; break; } // if if b[i] is present in map // decrement by one else { mp1.put(b[i], mp1.get(b[i]) - 1); if (mp1.get(b[i]) == 0) mp1.remove(b[i]); } } return f; } // Driver code public static void main(String[] args) { int arr1[] = { 11, 1, 13, 21, 3, 7 }; int arr2[] = { 11, 3, 7, 1 }; int m = arr1.length; int n = arr2.length; if (isSubset(arr1, arr2, m, n)!=1) System.out.print("arr2[] is subset of arr1[] "); else System.out.print("arr2[] is not a subset of arr1[]"); }} // This code is contributed by Rajput-Ji # Python program to check if an array is# subset of another array # Function to check if an array is# subset of another arraydef isSubset(a, b, m, n) : # map to store the values of array a mp1 = {} for i in range(m): if a[i] not in mp1: mp1[a[i]] = 0 mp1[a[i]] += 1 # flag value f = 0 for i in range(n): # if b[i] is not present in map # then array b can not be a # subset of array a if b[i] not in mp1: f = 1 break # if if b[i] is present in map # decrement by one else : mp1[b[i]] -= 1 if (mp1[b[i]] == 0): mp1.pop(b[i]) return f # Driver codearr1 = [11, 1, 13, 21, 3, 7 ]arr2 = [11, 3, 7, 1 ] m = len(arr1)n = len(arr2) if (not isSubset(arr1, arr2, m, n)): print("arr2[] is subset of arr1[] ")else: print("arr2[] is not a subset of arr1[]") # This code is contributed by Shubhamsingh10 // C# program to check if an array is// subset of another arrayusing System;using System.Collections.Generic; class GFG{ // Function to check if an array is // subset of another array static int isSubset(int []a, int []b, int m, int n) { // map to store the values of array []a Dictionary<int, int> mp1 = new Dictionary<int, int>(); for (int i = 0; i < m; i++) if (mp1.ContainsKey(a[i])) { mp1[a[i]] = mp1[a[i]] + 1; } else { mp1.Add(a[i], 1); } // flag value int f = 0; for (int i = 0; i < n; i++) { // if b[i] is not present in map // then array []b can not be a // subset of array []a if (!mp1.ContainsKey(b[i])) { f = 1; break; } // if if b[i] is present in map // decrement by one else { mp1[b[i]] = mp1[b[i]] - 1; if (mp1[b[i]] == 0) mp1.Remove(b[i]); } } return f; } // Driver code public static void Main(String[] args) { int []arr1 = {11, 1, 13, 21, 3, 7}; int []arr2 = {11, 3, 7, 1}; int m = arr1.Length; int n = arr2.Length; if (isSubset(arr1, arr2, m, n) != 1) Console.Write("arr2[] is subset of arr1[] "); else Console.Write("arr2[] is not a subset of arr1[]"); }} // This code is contributed by PrinciRaj1992 <script> // JavaScript program to check if an array is// subset of another array // Function to check if an array is// subset of another array function isSubset(a, b, m, n) { // map to store the values of array a[] let mp = new Map(); for (let i = 0; i < m; i++) { if (mp.has(a[i])) { mp.set(a[i], mp.get(a[i]) + 1) } else { mp.set(a[i], 1) } } // flag value let f = 0; for (let i = 0; i < n; i++) { // if b[i] is not present in map // then array b[] can not be a // subset of array a[] if (!mp.has(b[i])) { f = 1; break; } // if if b[i] is present in map // decrement by one else { mp.set(b[i], mp.get(b[i]) - 1); if (mp.get(b[i]) == 0) mp.delete(b[i]); } } return f;} // Driver code let arr1 = [11, 1, 13, 21, 3, 7];let arr2 = [11, 3, 7, 1]; let m = arr1.length;let n = arr2.length; if (!isSubset(arr1, arr2, m, n)) document.write("arr2[] is subset of arr1[] ");else document.write("arr2[] is not a subset of arr1[]"); // This code is contributed by gfgking </script> arr2[] is subset of arr1[] Time Complexity: O (n) Rajput-Ji princiraj1992 SHUBHAMSINGH10 gfgking cpp-map subset Arrays Arrays subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Find subarray with given sum | Set 1 (Nonnegative Numbers) Remove duplicates from sorted array Move all negative numbers to beginning and positive to end with constant extra space Merge Overlapping Intervals
[ { "code": null, "e": 26066, "s": 26038, "text": "\n08 Jun, 2021" }, { "code": null, "e": 26278, "s": 26066, "text": "Given two arrays: arr1[0..m-1] and arr2[0..n-1]. Find whether arr2[] is a subset of arr1[] or not. Both the arrays are not in sorted order. It may be assumed that elements in both arrays are distinct.Examples: " }, { "code": null, "e": 26571, "s": 26278, "text": "Input: arr1[] = {11, 1, 13, 21, 3, 7}, arr2[] = {11, 3, 7, 1}\nOutput: arr2[] is a subset of arr1[]\n\nInput: arr1[] = {1, 2, 3, 4, 5, 6}, arr2[] = {1, 2, 4}\nOutput: arr2[] is a subset of arr1[]\n\nInput: arr1[] = {10, 5, 2, 23, 19}, arr2[] = {19, 5, 3}\nOutput: arr2[] is not a subset of arr1[]" }, { "code": null, "e": 27354, "s": 26573, "text": "Simple Approach: A simple approach is to run two nested loops. The outer loop picks all the elements of B[] one by one. The inner loop linearly searches for the element picked by the outer loop in A[]. If all elements are found, then print Yes, else print No. You can check the solution here.Efficient Approach: Create a map to store the frequency of each distinct number present in A[]. Then we will check if each number of B[] is present in map or not. If present in the map, we will decrement the frequency value for that number by one and check for the next number. If map value for any number becomes zero, we will erase it from the map. If any number of B[] is not found in the map, we will set the flag value and break the loops and print No. Otherwise, we will print Yes. " }, { "code": null, "e": 27358, "s": 27354, "text": "C++" }, { "code": null, "e": 27363, "s": 27358, "text": "Java" }, { "code": null, "e": 27370, "s": 27363, "text": "Python" }, { "code": null, "e": 27373, "s": 27370, "text": "C#" }, { "code": null, "e": 27384, "s": 27373, "text": "Javascript" }, { "code": "// C++ program to check if an array is// subset of another array #include <bits/stdc++.h>using namespace std; // Function to check if an array is// subset of another array int isSubset(int a[], int b[], int m, int n){ // map to store the values of array a[] map<int, int> mp1; for (int i = 0; i < m; i++) mp1[a[i]]++; // flag value int f = 0; for (int i = 0; i < n; i++) { // if b[i] is not present in map // then array b[] can not be a // subset of array a[] if (mp1.find(b[i]) == mp1.end()) { f = 1; break; } // if if b[i] is present in map // decrement by one else { mp1[b[i]]--; if (mp1[b[i]] == 0) mp1.erase(mp1.find(b[i])); } } return f;} // Driver codeint main(){ int arr1[] = { 11, 1, 13, 21, 3, 7 }; int arr2[] = { 11, 3, 7, 1 }; int m = sizeof(arr1) / sizeof(arr1[0]); int n = sizeof(arr2) / sizeof(arr2[0]); if (!isSubset(arr1, arr2, m, n)) cout<<\"arr2[] is subset of arr1[] \"; else cout<<\"arr2[] is not a subset of arr1[]\"; return 0;}", "e": 28530, "s": 27384, "text": null }, { "code": "// Java program to check if an array is// subset of another arrayimport java.util.*; class GFG{ // Function to check if an array is // subset of another array static int isSubset(int a[], int b[], int m, int n) { // map to store the values of array a[] HashMap<Integer, Integer> mp1 = new HashMap<Integer, Integer>(); for (int i = 0; i < m; i++) if (mp1.containsKey(a[i])) { mp1.put(a[i], mp1.get(a[i]) + 1); } else { mp1.put(a[i], 1); } // flag value int f = 0; for (int i = 0; i < n; i++) { // if b[i] is not present in map // then array b[] can not be a // subset of array a[] if (!mp1.containsKey(b[i])) { f = 1; break; } // if if b[i] is present in map // decrement by one else { mp1.put(b[i], mp1.get(b[i]) - 1); if (mp1.get(b[i]) == 0) mp1.remove(b[i]); } } return f; } // Driver code public static void main(String[] args) { int arr1[] = { 11, 1, 13, 21, 3, 7 }; int arr2[] = { 11, 3, 7, 1 }; int m = arr1.length; int n = arr2.length; if (isSubset(arr1, arr2, m, n)!=1) System.out.print(\"arr2[] is subset of arr1[] \"); else System.out.print(\"arr2[] is not a subset of arr1[]\"); }} // This code is contributed by Rajput-Ji", "e": 30136, "s": 28530, "text": null }, { "code": "# Python program to check if an array is# subset of another array # Function to check if an array is# subset of another arraydef isSubset(a, b, m, n) : # map to store the values of array a mp1 = {} for i in range(m): if a[i] not in mp1: mp1[a[i]] = 0 mp1[a[i]] += 1 # flag value f = 0 for i in range(n): # if b[i] is not present in map # then array b can not be a # subset of array a if b[i] not in mp1: f = 1 break # if if b[i] is present in map # decrement by one else : mp1[b[i]] -= 1 if (mp1[b[i]] == 0): mp1.pop(b[i]) return f # Driver codearr1 = [11, 1, 13, 21, 3, 7 ]arr2 = [11, 3, 7, 1 ] m = len(arr1)n = len(arr2) if (not isSubset(arr1, arr2, m, n)): print(\"arr2[] is subset of arr1[] \")else: print(\"arr2[] is not a subset of arr1[]\") # This code is contributed by Shubhamsingh10", "e": 31130, "s": 30136, "text": null }, { "code": "// C# program to check if an array is// subset of another arrayusing System;using System.Collections.Generic; class GFG{ // Function to check if an array is // subset of another array static int isSubset(int []a, int []b, int m, int n) { // map to store the values of array []a Dictionary<int, int> mp1 = new Dictionary<int, int>(); for (int i = 0; i < m; i++) if (mp1.ContainsKey(a[i])) { mp1[a[i]] = mp1[a[i]] + 1; } else { mp1.Add(a[i], 1); } // flag value int f = 0; for (int i = 0; i < n; i++) { // if b[i] is not present in map // then array []b can not be a // subset of array []a if (!mp1.ContainsKey(b[i])) { f = 1; break; } // if if b[i] is present in map // decrement by one else { mp1[b[i]] = mp1[b[i]] - 1; if (mp1[b[i]] == 0) mp1.Remove(b[i]); } } return f; } // Driver code public static void Main(String[] args) { int []arr1 = {11, 1, 13, 21, 3, 7}; int []arr2 = {11, 3, 7, 1}; int m = arr1.Length; int n = arr2.Length; if (isSubset(arr1, arr2, m, n) != 1) Console.Write(\"arr2[] is subset of arr1[] \"); else Console.Write(\"arr2[] is not a subset of arr1[]\"); }} // This code is contributed by PrinciRaj1992", "e": 32729, "s": 31130, "text": null }, { "code": "<script> // JavaScript program to check if an array is// subset of another array // Function to check if an array is// subset of another array function isSubset(a, b, m, n) { // map to store the values of array a[] let mp = new Map(); for (let i = 0; i < m; i++) { if (mp.has(a[i])) { mp.set(a[i], mp.get(a[i]) + 1) } else { mp.set(a[i], 1) } } // flag value let f = 0; for (let i = 0; i < n; i++) { // if b[i] is not present in map // then array b[] can not be a // subset of array a[] if (!mp.has(b[i])) { f = 1; break; } // if if b[i] is present in map // decrement by one else { mp.set(b[i], mp.get(b[i]) - 1); if (mp.get(b[i]) == 0) mp.delete(b[i]); } } return f;} // Driver code let arr1 = [11, 1, 13, 21, 3, 7];let arr2 = [11, 3, 7, 1]; let m = arr1.length;let n = arr2.length; if (!isSubset(arr1, arr2, m, n)) document.write(\"arr2[] is subset of arr1[] \");else document.write(\"arr2[] is not a subset of arr1[]\"); // This code is contributed by gfgking </script>", "e": 33907, "s": 32729, "text": null }, { "code": null, "e": 33934, "s": 33907, "text": "arr2[] is subset of arr1[]" }, { "code": null, "e": 33960, "s": 33936, "text": "Time Complexity: O (n) " }, { "code": null, "e": 33970, "s": 33960, "text": "Rajput-Ji" }, { "code": null, "e": 33984, "s": 33970, "text": "princiraj1992" }, { "code": null, "e": 33999, "s": 33984, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 34007, "s": 33999, "text": "gfgking" }, { "code": null, "e": 34015, "s": 34007, "text": "cpp-map" }, { "code": null, "e": 34022, "s": 34015, "text": "subset" }, { "code": null, "e": 34029, "s": 34022, "text": "Arrays" }, { "code": null, "e": 34036, "s": 34029, "text": "Arrays" }, { "code": null, "e": 34043, "s": 34036, "text": "subset" }, { "code": null, "e": 34141, "s": 34043, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34168, "s": 34141, "text": "Count pairs with given sum" }, { "code": null, "e": 34199, "s": 34168, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 34224, "s": 34199, "text": "Window Sliding Technique" }, { "code": null, "e": 34262, "s": 34224, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 34283, "s": 34262, "text": "Next Greater Element" }, { "code": null, "e": 34341, "s": 34283, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 34400, "s": 34341, "text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)" }, { "code": null, "e": 34436, "s": 34400, "text": "Remove duplicates from sorted array" }, { "code": null, "e": 34521, "s": 34436, "text": "Move all negative numbers to beginning and positive to end with constant extra space" } ]
Ruby | String delete() Method - GeeksforGeeks
13 Dec, 2019 delete is a String class method in Ruby which is used to return a copy of the given string with all characters in the intersection of its arguments deleted. Syntax: str.delete(parameter_list) Parameters: Here, str is the given string and parameter_list are the specified characters. Returns: A new copy of the string with all characters in the intersection of its arguments deleted. Example 1: # Ruby program to demonstrate # the delete method # Taking a string and # using the methodstr = "String Counting"puts str.delete "ing" Output: Str Cout Example 2: # Ruby program to demonstrate # the delete method # Taking a string and # using the methodstr = "String Counting"puts str.delete "ing", "^n" str2 = "Ruby Method\\r\\n" puts str2.delete "\\" Output: Strn Countn Ruby Methodrn Ruby String-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Include v/s Extend in Ruby Global Variable in Ruby Ruby | Hash delete() function Ruby | Types of Variables Ruby | Enumerator each_with_index function Ruby | Case Statement Ruby | Array select() function Ruby | Data Types Ruby | Numeric round() function Ruby | String capitalize() Method
[ { "code": null, "e": 24897, "s": 24869, "text": "\n13 Dec, 2019" }, { "code": null, "e": 25054, "s": 24897, "text": "delete is a String class method in Ruby which is used to return a copy of the given string with all characters in the intersection of its arguments deleted." }, { "code": null, "e": 25089, "s": 25054, "text": "Syntax: str.delete(parameter_list)" }, { "code": null, "e": 25180, "s": 25089, "text": "Parameters: Here, str is the given string and parameter_list are the specified characters." }, { "code": null, "e": 25280, "s": 25180, "text": "Returns: A new copy of the string with all characters in the intersection of its arguments deleted." }, { "code": null, "e": 25291, "s": 25280, "text": "Example 1:" }, { "code": "# Ruby program to demonstrate # the delete method # Taking a string and # using the methodstr = \"String Counting\"puts str.delete \"ing\"", "e": 25433, "s": 25291, "text": null }, { "code": null, "e": 25441, "s": 25433, "text": "Output:" }, { "code": null, "e": 25451, "s": 25441, "text": "Str Cout\n" }, { "code": null, "e": 25462, "s": 25451, "text": "Example 2:" }, { "code": "# Ruby program to demonstrate # the delete method # Taking a string and # using the methodstr = \"String Counting\"puts str.delete \"ing\", \"^n\" str2 = \"Ruby Method\\\\r\\\\n\" puts str2.delete \"\\\\\"", "e": 25661, "s": 25462, "text": null }, { "code": null, "e": 25669, "s": 25661, "text": "Output:" }, { "code": null, "e": 25696, "s": 25669, "text": "Strn Countn\nRuby Methodrn\n" }, { "code": null, "e": 25714, "s": 25696, "text": "Ruby String-class" }, { "code": null, "e": 25727, "s": 25714, "text": "Ruby-Methods" }, { "code": null, "e": 25732, "s": 25727, "text": "Ruby" }, { "code": null, "e": 25830, "s": 25732, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25857, "s": 25830, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 25881, "s": 25857, "text": "Global Variable in Ruby" }, { "code": null, "e": 25911, "s": 25881, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 25937, "s": 25911, "text": "Ruby | Types of Variables" }, { "code": null, "e": 25980, "s": 25937, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 26002, "s": 25980, "text": "Ruby | Case Statement" }, { "code": null, "e": 26033, "s": 26002, "text": "Ruby | Array select() function" }, { "code": null, "e": 26051, "s": 26033, "text": "Ruby | Data Types" }, { "code": null, "e": 26083, "s": 26051, "text": "Ruby | Numeric round() function" } ]
How to create dynamic length array with numbers and sum the numbers using JavaScript ? - GeeksforGeeks
25 Aug, 2021 In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. Unlike most languages where array is a reference to the multiple variable, in JavaScript array is a single variable that stores multiple elements. JavaScript Arrays are Dynamic in nature it means, the length of array can be modified at run time (when necessary). Array length can be specified after declaring array as shown in the following example. Example: Javascript // Declare an array of undefined sizevar arr = []; // Set array length to 10arr.length = 10; // Print the length to consoleconsole.log(arr); Output: Array(10) [ <10 empty slots> ] As you can see, this method explain the array with 10 empty slots. The following example declares an array and take input elements using prompt dynamically and print the sum of all elements and display the result sing alert. Example: Javascript (function () { // Declare an array of undefined size var arr = []; // Notice how the size of array // is not dot defined // Initiating loop to iterate // for inputs for (var i = 0; i < 10; i++) { // Feeding integer inputs to array arr[i] = +prompt('Enter number'); // Calculate sum of array elements var sum = arr.reduce(function (a, b) { return a + b; }, 0) } alert(sum);})(); Output: Input : 1 2 3 4 5 6 7 8 9 10 Output :55 kk773572498 JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26545, "s": 26517, "text": "\n25 Aug, 2021" }, { "code": null, "e": 26870, "s": 26545, "text": "In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. Unlike most languages where array is a reference to the multiple variable, in JavaScript array is a single variable that stores multiple elements." }, { "code": null, "e": 27073, "s": 26870, "text": "JavaScript Arrays are Dynamic in nature it means, the length of array can be modified at run time (when necessary). Array length can be specified after declaring array as shown in the following example." }, { "code": null, "e": 27082, "s": 27073, "text": "Example:" }, { "code": null, "e": 27093, "s": 27082, "text": "Javascript" }, { "code": "// Declare an array of undefined sizevar arr = []; // Set array length to 10arr.length = 10; // Print the length to consoleconsole.log(arr);", "e": 27234, "s": 27093, "text": null }, { "code": null, "e": 27243, "s": 27234, "text": "Output: " }, { "code": null, "e": 27274, "s": 27243, "text": "Array(10) [ <10 empty slots> ]" }, { "code": null, "e": 27499, "s": 27274, "text": "As you can see, this method explain the array with 10 empty slots. The following example declares an array and take input elements using prompt dynamically and print the sum of all elements and display the result sing alert." }, { "code": null, "e": 27508, "s": 27499, "text": "Example:" }, { "code": null, "e": 27519, "s": 27508, "text": "Javascript" }, { "code": "(function () { // Declare an array of undefined size var arr = []; // Notice how the size of array // is not dot defined // Initiating loop to iterate // for inputs for (var i = 0; i < 10; i++) { // Feeding integer inputs to array arr[i] = +prompt('Enter number'); // Calculate sum of array elements var sum = arr.reduce(function (a, b) { return a + b; }, 0) } alert(sum);})();", "e": 27987, "s": 27519, "text": null }, { "code": null, "e": 27995, "s": 27987, "text": "Output:" }, { "code": null, "e": 28035, "s": 27995, "text": "Input : 1 2 3 4 5 6 7 8 9 10\nOutput :55" }, { "code": null, "e": 28047, "s": 28035, "text": "kk773572498" }, { "code": null, "e": 28063, "s": 28047, "text": "JavaScript-Misc" }, { "code": null, "e": 28074, "s": 28063, "text": "JavaScript" }, { "code": null, "e": 28091, "s": 28074, "text": "Web Technologies" }, { "code": null, "e": 28189, "s": 28091, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28229, "s": 28189, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28290, "s": 28229, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28331, "s": 28290, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28353, "s": 28331, "text": "JavaScript | Promises" }, { "code": null, "e": 28407, "s": 28353, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28447, "s": 28407, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28480, "s": 28447, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28523, "s": 28480, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28585, "s": 28523, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Python | Pandas Index.values - GeeksforGeeks
20 Feb, 2019 Pandas Index is an immutable ndarray implementing an ordered, sliceable set. It is the basic object which stores the axis labels for all pandas objects. Pandas Index.values attribute return an array representing the data in the given Index object. Syntax: Index.values Parameter : None Returns : an array Example #1: Use Index.values attribute to return an array representing the data in the given Index object. # importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Melbourne', 'Sanghai', 'Lisbon', 'Doha', 'Moscow', 'Rio']) # Print the indexprint(idx) Output : Now we will use Index.values attribute to return an array representing the data in the given Index object. # return an arrayresult = idx.values # Print the resultprint(result) Output :As we can see in the output, the Index.values attribute has successfully returned an array representing the data of the given Index object. Example #2 : Use Index.values attribute to return an array representing the data in the given Index object. # importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index([900 + 3j, 700 + 25j, 620 + 10j, 388 + 44j, 900]) # Print the indexprint(idx) Output : Now we will use Index.values attribute to return an array representing the data in the given Index object. # return an arrayresult = idx.values # Print the resultprint(result) Output :As we can see in the output, the Index.values attribute has successfully returned an array representing the data of the given Index object. Python pandas-indexing Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26245, "s": 26217, "text": "\n20 Feb, 2019" }, { "code": null, "e": 26398, "s": 26245, "text": "Pandas Index is an immutable ndarray implementing an ordered, sliceable set. It is the basic object which stores the axis labels for all pandas objects." }, { "code": null, "e": 26493, "s": 26398, "text": "Pandas Index.values attribute return an array representing the data in the given Index object." }, { "code": null, "e": 26514, "s": 26493, "text": "Syntax: Index.values" }, { "code": null, "e": 26531, "s": 26514, "text": "Parameter : None" }, { "code": null, "e": 26550, "s": 26531, "text": "Returns : an array" }, { "code": null, "e": 26657, "s": 26550, "text": "Example #1: Use Index.values attribute to return an array representing the data in the given Index object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Melbourne', 'Sanghai', 'Lisbon', 'Doha', 'Moscow', 'Rio']) # Print the indexprint(idx)", "e": 26827, "s": 26657, "text": null }, { "code": null, "e": 26836, "s": 26827, "text": "Output :" }, { "code": null, "e": 26943, "s": 26836, "text": "Now we will use Index.values attribute to return an array representing the data in the given Index object." }, { "code": "# return an arrayresult = idx.values # Print the resultprint(result)", "e": 27013, "s": 26943, "text": null }, { "code": null, "e": 27269, "s": 27013, "text": "Output :As we can see in the output, the Index.values attribute has successfully returned an array representing the data of the given Index object. Example #2 : Use Index.values attribute to return an array representing the data in the given Index object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index([900 + 3j, 700 + 25j, 620 + 10j, 388 + 44j, 900]) # Print the indexprint(idx)", "e": 27428, "s": 27269, "text": null }, { "code": null, "e": 27437, "s": 27428, "text": "Output :" }, { "code": null, "e": 27544, "s": 27437, "text": "Now we will use Index.values attribute to return an array representing the data in the given Index object." }, { "code": "# return an arrayresult = idx.values # Print the resultprint(result)", "e": 27614, "s": 27544, "text": null }, { "code": null, "e": 27762, "s": 27614, "text": "Output :As we can see in the output, the Index.values attribute has successfully returned an array representing the data of the given Index object." }, { "code": null, "e": 27785, "s": 27762, "text": "Python pandas-indexing" }, { "code": null, "e": 27799, "s": 27785, "text": "Python-pandas" }, { "code": null, "e": 27806, "s": 27799, "text": "Python" }, { "code": null, "e": 27904, "s": 27806, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27922, "s": 27904, "text": "Python Dictionary" }, { "code": null, "e": 27957, "s": 27922, "text": "Read a file line by line in Python" }, { "code": null, "e": 27989, "s": 27957, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28011, "s": 27989, "text": "Enumerate() in Python" }, { "code": null, "e": 28053, "s": 28011, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28083, "s": 28053, "text": "Iterate over a list in Python" }, { "code": null, "e": 28109, "s": 28083, "text": "Python String | replace()" }, { "code": null, "e": 28138, "s": 28109, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28182, "s": 28138, "text": "Reading and Writing to text files in Python" } ]
Year plus(TemporalAmount) method in Java with Examples - GeeksforGeeks
25 Feb, 2019 The plus(TemporalAmount) method of Year class is used to return a copy of this year after adding the specified amount of TemporalAmount to this Year object. An exception is thrown, If the specified unit cannot be added to Year. The TemporalAmount passed is created from the Period object. This instance is immutable and unaffected by this method call. Syntax: public Year plus(TemporalAmount amountToadd) Parameters: This method accepts only one parameter TemporalAmount which represents the amount to add to Year object. Return Value: This method returns a Year based on this year with the specified amount added. Exception: This method throws following Exceptions: DateTimeException – This exception is thrown if the addition cannot be made. ArithmeticException – This exception is thrown if numeric overflow occurs. Below programs illustrate the plus(TemporalAmount amountToadd) method: Program 1: // Java program to demonstrate// Year.plus(TemporalAmount amountToadd) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create a Year object Year year = Year.of(2019); // print instance System.out.println("Year :" + year); // create temporalAmount object from period class // passing temporalAmount to // plus() method Year value = year.plus( Period.ofYears(12)); // print result System.out.println("Value after addition: " + value); }} Year :2019 Value after addition: 2031 Program 2: // Java program to demonstrate// Year.plus(TemporalAmount amountToadd) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create a Year object Year year = Year.of(2019); // print instance System.out.println("Year :" + year); // create temporalAmount object from period class // passing temporalAmount to // plus() method Year value = year.plus( Period.ofYears(120)); // print result System.out.println("Value after addition: " + value); }} Year :2019 Value after addition: 2139 References:https://docs.oracle.com/javase/10/docs/api/java/time/Year.html#plus(java.time.temporal.TemporalAmount) Java 8 Java-Functions Java-Year Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25789, "s": 25761, "text": "\n25 Feb, 2019" }, { "code": null, "e": 26141, "s": 25789, "text": "The plus(TemporalAmount) method of Year class is used to return a copy of this year after adding the specified amount of TemporalAmount to this Year object. An exception is thrown, If the specified unit cannot be added to Year. The TemporalAmount passed is created from the Period object. This instance is immutable and unaffected by this method call." }, { "code": null, "e": 26149, "s": 26141, "text": "Syntax:" }, { "code": null, "e": 26195, "s": 26149, "text": "public Year plus(TemporalAmount amountToadd)\n" }, { "code": null, "e": 26312, "s": 26195, "text": "Parameters: This method accepts only one parameter TemporalAmount which represents the amount to add to Year object." }, { "code": null, "e": 26405, "s": 26312, "text": "Return Value: This method returns a Year based on this year with the specified amount added." }, { "code": null, "e": 26457, "s": 26405, "text": "Exception: This method throws following Exceptions:" }, { "code": null, "e": 26534, "s": 26457, "text": "DateTimeException – This exception is thrown if the addition cannot be made." }, { "code": null, "e": 26609, "s": 26534, "text": "ArithmeticException – This exception is thrown if numeric overflow occurs." }, { "code": null, "e": 26680, "s": 26609, "text": "Below programs illustrate the plus(TemporalAmount amountToadd) method:" }, { "code": null, "e": 26691, "s": 26680, "text": "Program 1:" }, { "code": "// Java program to demonstrate// Year.plus(TemporalAmount amountToadd) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create a Year object Year year = Year.of(2019); // print instance System.out.println(\"Year :\" + year); // create temporalAmount object from period class // passing temporalAmount to // plus() method Year value = year.plus( Period.ofYears(12)); // print result System.out.println(\"Value after addition: \" + value); }}", "e": 27362, "s": 26691, "text": null }, { "code": null, "e": 27401, "s": 27362, "text": "Year :2019\nValue after addition: 2031\n" }, { "code": null, "e": 27412, "s": 27401, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Year.plus(TemporalAmount amountToadd) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // create a Year object Year year = Year.of(2019); // print instance System.out.println(\"Year :\" + year); // create temporalAmount object from period class // passing temporalAmount to // plus() method Year value = year.plus( Period.ofYears(120)); // print result System.out.println(\"Value after addition: \" + value); }}", "e": 28084, "s": 27412, "text": null }, { "code": null, "e": 28123, "s": 28084, "text": "Year :2019\nValue after addition: 2139\n" }, { "code": null, "e": 28237, "s": 28123, "text": "References:https://docs.oracle.com/javase/10/docs/api/java/time/Year.html#plus(java.time.temporal.TemporalAmount)" }, { "code": null, "e": 28244, "s": 28237, "text": "Java 8" }, { "code": null, "e": 28259, "s": 28244, "text": "Java-Functions" }, { "code": null, "e": 28269, "s": 28259, "text": "Java-Year" }, { "code": null, "e": 28274, "s": 28269, "text": "Java" }, { "code": null, "e": 28279, "s": 28274, "text": "Java" }, { "code": null, "e": 28377, "s": 28279, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28428, "s": 28377, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28458, "s": 28428, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28477, "s": 28458, "text": "Interfaces in Java" }, { "code": null, "e": 28492, "s": 28477, "text": "Stream In Java" }, { "code": null, "e": 28523, "s": 28492, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28541, "s": 28523, "text": "ArrayList in Java" }, { "code": null, "e": 28573, "s": 28541, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28593, "s": 28573, "text": "Stack Class in Java" }, { "code": null, "e": 28625, "s": 28593, "text": "Multidimensional Arrays in Java" } ]
Check if bits of a number has count of consecutive set bits in increasing order - GeeksforGeeks
04 Apr, 2022 Given a integer n > 0, the task is to find whether in the bit pattern of integer count of continuous 1’s are in increasing from left to right. Examples : Input:19 Output:Yes Explanation: Bit-pattern of 19 = 10011, Counts of continuous 1's from left to right are 1, 2 which are in increasing order. Input : 183 Output : yes Explanation: Bit-pattern of 183 = 10110111, Counts of continuous 1's from left to right are 1, 2, 3 which are in increasing order. A simple solution is to store binary representation of given number into a string, then traverse from left to right and count the number of continuous 1’s. For every encounter of 0 check the value of previous count of continuous 1’s to that of current value, if the value of previous count is greater than the value of current count then return False, Else when string ends return True. C++ Java Python3 C# Javascript // C++ program to find if bit-pattern// of a number has increasing value of// continuous-1 or not.#include <bits/stdc++.h>using namespace std; // Returns true if n has increasing count of// continuous-1 else falsebool findContinuous1(int n){ const int bits = 8 * sizeof(int); // store the bit-pattern of n into // bit bitset- bp string bp = bitset<bits>(n).to_string(); // set prev_count = 0 and curr_count = 0. int prev_count = 0, curr_count = 0; int i = 0; while (i < bits) { if (bp[i] == '1') { // increment current count of continuous-1 curr_count++; i++; } // traverse all continuous-0 else if (bp[i - 1] == '0') { i++; curr_count = 0; continue; } // check prev_count and curr_count // on encounter of first zero after // continuous-1s else { if (curr_count < prev_count) return 0; i++; prev_count = curr_count; curr_count = 0; } } // check for last sequence of continuous-1 if (prev_count > curr_count && (curr_count != 0)) return 0; return 1;} // Driver codeint main(){ int n = 179; if (findContinuous1(n)) cout << "Yes"; else cout << "No"; return 0;} // Java program to find if bit-pattern// of a number has increasing value of// continuous-1 or not.import java.io.*;public class GFG { // Returns true if n has increasing count of // continuous-1 else false static boolean findContinuous1(int n) { // converting decimal integer to binary string then // store the bit-pattern of n into // bit bitset- bp by converting the binary string to // char array char[] bp = (Integer.toBinaryString(n)).toCharArray(); int bits = bp.length; // set prev_count = 0 and curr_count = 0. int prev_count = 0; int curr_count = 0; int i = 0; while (i < bits) { if (bp[i] == '1') { // increment current count of continuous-1 curr_count++; i++; } // traverse all continuous-0 else if (bp[i - 1] == '0') { i++; curr_count = 0; continue; } // check prev_count and curr_count // on encounter of first zero after // continuous-1s else { if (curr_count < prev_count) return false; i++; prev_count = curr_count; curr_count = 0; } } // check for last sequence of continuous-1 if ((prev_count > curr_count) && (curr_count != 0)) return false; return true; } // Driver code public static void main(String args[]) { int n = 179; if (findContinuous1(n)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by phasing17 # Python3 program to find if bit-pattern# of a number has increasing value of# continuous-1 or not. # Returns true if n has increasing count of# continuous-1 else false def findContinuous1(n): # store the bit-pattern of n into # bit bitset- bp bp = list(bin(n)) bits = len(bp) # set prev_count = 0 and curr_count = 0. prev_count = 0 curr_count = 0 i = 0 while (i < bits): if (bp[i] == '1'): # increment current count of continuous-1 curr_count += 1 i += 1 # traverse all continuous-0 elif (bp[i - 1] == '0'): i += 1 curr_count = 0 continue # check prev_count and curr_count # on encounter of first zero after # continuous-1s else: if (curr_count < prev_count): return 0 i += 1 prev_count = curr_count curr_count = 0 # check for last sequence of continuous-1 if (prev_count > curr_count and (curr_count != 0)): return 0 return 1 # Driver coden = 179if (findContinuous1(n)): print("Yes")else: print("No") # This code is contributed by SHUBHAMSINGH10 // C# program to find if bit-pattern// of a number has increasing value of// continuous-1 or not.using System;using System.Collections.Specialized; class GFG{ // Returns true if n has increasing count of // continuous-1 else false static bool findContinuous1(int n) { // store the bit-pattern of n into // bit bitset- bp string bp = Convert.ToString(n, 2); int bits = bp.Length; // set prev_count = 0 and curr_count = 0. int prev_count = 0, curr_count = 0; int i = 0; while (i < bits) { if (bp[i] == '1') { // increment current count of continuous-1 curr_count++; i++; } // traverse all continuous-0 else if (bp[i - 1] == '0') { i++; curr_count = 0; continue; } // check prev_count and curr_count // on encounter of first zero after // continuous-1s else { if (curr_count < prev_count) return false; i++; prev_count = curr_count; curr_count = 0; } } // check for last sequence of continuous-1 if (prev_count > curr_count && (curr_count != 0)) return false; return true; } // Driver Code static void Main() { int n = 179; if (findContinuous1(n)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This Code was contributed by phasing17 <script>// JavaScript program to find if bit-pattern// of a number has increasing value of// continuous-1 or not.function dec2bin(dec) { return (dec >>> 0).toString(2);}// Returns true if n has increasing count of// continuous-1 else falsefunction findContinuous1(n){ // store the bit-pattern of n into // bit bitset- bp let bp = dec2bin(n) let bits = bp.length // set prev_count = 0 and curr_count = 0. let prev_count = 0 let curr_count = 0 let i = 0 while (i < bits){ if (bp[i] == '1'){ // increment current count of continuous-1 curr_count += 1; i += 1; } // traverse all continuous-0 else if (bp[i - 1] == '0'){ i += 1 curr_count = 0 continue } // check prev_count and curr_count // on encounter of first zero after // continuous-1s else{ if (curr_count < prev_count) return 0 i += 1 prev_count = curr_count curr_count = 0 } } // check for last sequence of continuous-1 if (prev_count > curr_count && (curr_count != 0)) return 0 return 1}// Driver coden = 179if (findContinuous1(n)) document.write( "Yes")else document.write( "No") </script> Yes An efficient solution is to use decimal to binary conversion loop that divides number by 2 and take remainder as bit. This loop finds bits from right to left. So we check if right to left is in decreasing order or not. Below is the implementation. C++ Java Python3 C# PHP Javascript // C++ program to check if counts of consecutive// 1s are increasing order.#include<bits/stdc++.h>using namespace std; // Returns true if n has counts of consecutive// 1's are increasing order.bool areSetBitsIncreasing(int n){ // Initialize previous count int prev_count = INT_MAX; // We traverse bits from right to left // and check if counts are decreasing // order. while (n > 0) { // Ignore 0s until we reach a set bit. while (n > 0 && n % 2 == 0) n = n/2; // Count current set bits int curr_count = 1; while (n > 0 && n % 2 == 1) { n = n/2; curr_count++; } // Compare current with previous and // update previous. if (curr_count >= prev_count) return false; prev_count = curr_count; } return true;} // Driver codeint main(){ int n = 10; if (areSetBitsIncreasing(n)) cout << "Yes"; else cout << "No"; return 0;} // Java program to check if counts of// consecutive 1s are increasing order.import java .io.*; class GFG { // Returns true if n has counts of // consecutive 1's are increasing // order. static boolean areSetBitsIncreasing(int n) { // Initialize previous count int prev_count = Integer.MAX_VALUE; // We traverse bits from right to // left and check if counts are // decreasing order. while (n > 0) { // Ignore 0s until we reach // a set bit. while (n > 0 && n % 2 == 0) n = n/2; // Count current set bits int curr_count = 1; while (n > 0 && n % 2 == 1) { n = n/2; curr_count++; } // Compare current with previous // and update previous. if (curr_count >= prev_count) return false; prev_count = curr_count; } return true; } // Driver code static public void main (String[] args) { int n = 10; if (areSetBitsIncreasing(n)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by anuj_67. # Python3 program to check if counts of# consecutive 1s are increasing order. import sys # Returns true if n has counts of# consecutive 1's are increasing order.def areSetBitsIncreasing(n): # Initialize previous count prev_count = sys.maxsize # We traverse bits from right to # left and check if counts are # decreasing order. while (n > 0): # Ignore 0s until we reach a # set bit. while (n > 0 and n % 2 == 0): n = int(n/2) # Count current set bits curr_count = 1 while (n > 0 and n % 2 == 1): n = n/2 curr_count += 1 # Compare current with previous # and update previous. if (curr_count >= prev_count): return False prev_count = curr_count return True # Driver coden = 10 if (areSetBitsIncreasing(n)): print("Yes")else: print("No") # This code is contributed by Smitha // C# program to check if counts of// consecutive 1s are increasing order.using System; class GFG { // Returns true if n has counts of // consecutive 1's are increasing // order. static bool areSetBitsIncreasing(int n) { // Initialize previous count int prev_count = int.MaxValue; // We traverse bits from right to // left and check if counts are // decreasing order. while (n > 0) { // Ignore 0s until we reach // a set bit. while (n > 0 && n % 2 == 0) n = n/2; // Count current set bits int curr_count = 1; while (n > 0 && n % 2 == 1) { n = n/2; curr_count++; } // Compare current with previous // and update previous. if (curr_count >= prev_count) return false; prev_count = curr_count; } return true; } // Driver code static public void Main () { int n = 10; if (areSetBitsIncreasing(n)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by anuj_67. <?php// PHP program to check if// counts of consecutive// 1s are increasing order. // Returns true if n has// counts of consecutive// 1's are increasing order.function areSetBitsIncreasing( $n){ // Initialize previous count $prev_count = PHP_INT_MAX; // We traverse bits from right // to left and check if counts // are decreasing order. while ($n > 0) { // Ignore 0s until we // reach a set bit. while ($n > 0 && $n % 2 == 0) $n = $n / 2; // Count current set bits $curr_count = 1; while ($n > 0 and $n % 2 == 1) { $n = $n / 2; $curr_count++; } // Compare current with previous // and update previous. if ($curr_count >= $prev_count) return false; $prev_count = $curr_count; } return true;} // Driver code$n = 10;if (areSetBitsIncreasing($n)) echo "Yes";else echo "No"; // This code is contributed by anuj_67?> <script> // Javascript program to check if counts of// consecutive 1s are increasing order. // Returns true if n has counts of// consecutive 1's are increasing// order.function areSetBitsIncreasing(n){ // Initialize previous count var prev_count = Number.MAX_VALUE; // We traverse bits from right to // left and check if counts are // decreasing order. while (n > 0) { // Ignore 0s until we reach // a set bit. while (n > 0 && n % 2 == 0) n = parseInt(n / 2); // Count current set bits var curr_count = 1; while (n > 0 && n % 2 == 1) { n = n / 2; curr_count++; } // Compare current with previous // and update previous. if (curr_count >= prev_count) return false; prev_count = curr_count; } return true;} // Driver codevar n = 10; if (areSetBitsIncreasing(n)) document.write("Yes");else document.write("No"); // This code is contributed by Rajput-Ji </script> No Time Complexity: O(log2n) Auxiliary Space: O(1) This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. vt_m Smitha Dinesh Semwal SHUBHAMSINGH10 Rajput-Ji rohan07 samim2000 surinderdawra388 phasing17 Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Cyclic Redundancy Check and Modulo-2 Division Add two numbers without using arithmetic operators Josephus problem | Set 1 (A O(n) Solution) Bits manipulation (Important tactics) Bit Fields in C Find the element that appears once Set, Clear and Toggle a given bit of a number in C C++ bitset and its application Divide two integers without using multiplication, division and mod operator
[ { "code": null, "e": 26647, "s": 26619, "text": "\n04 Apr, 2022" }, { "code": null, "e": 26791, "s": 26647, "text": "Given a integer n > 0, the task is to find whether in the bit pattern of integer count of continuous 1’s are in increasing from left to right. " }, { "code": null, "e": 26803, "s": 26791, "text": "Examples : " }, { "code": null, "e": 27107, "s": 26803, "text": "Input:19\nOutput:Yes\nExplanation: Bit-pattern of 19 = 10011,\nCounts of continuous 1's from left to right \nare 1, 2 which are in increasing order.\n\nInput : 183\nOutput : yes\nExplanation: Bit-pattern of 183 = 10110111,\nCounts of continuous 1's from left to right \nare 1, 2, 3 which are in increasing order." }, { "code": null, "e": 27495, "s": 27107, "text": "A simple solution is to store binary representation of given number into a string, then traverse from left to right and count the number of continuous 1’s. For every encounter of 0 check the value of previous count of continuous 1’s to that of current value, if the value of previous count is greater than the value of current count then return False, Else when string ends return True. " }, { "code": null, "e": 27499, "s": 27495, "text": "C++" }, { "code": null, "e": 27504, "s": 27499, "text": "Java" }, { "code": null, "e": 27512, "s": 27504, "text": "Python3" }, { "code": null, "e": 27515, "s": 27512, "text": "C#" }, { "code": null, "e": 27526, "s": 27515, "text": "Javascript" }, { "code": "// C++ program to find if bit-pattern// of a number has increasing value of// continuous-1 or not.#include <bits/stdc++.h>using namespace std; // Returns true if n has increasing count of// continuous-1 else falsebool findContinuous1(int n){ const int bits = 8 * sizeof(int); // store the bit-pattern of n into // bit bitset- bp string bp = bitset<bits>(n).to_string(); // set prev_count = 0 and curr_count = 0. int prev_count = 0, curr_count = 0; int i = 0; while (i < bits) { if (bp[i] == '1') { // increment current count of continuous-1 curr_count++; i++; } // traverse all continuous-0 else if (bp[i - 1] == '0') { i++; curr_count = 0; continue; } // check prev_count and curr_count // on encounter of first zero after // continuous-1s else { if (curr_count < prev_count) return 0; i++; prev_count = curr_count; curr_count = 0; } } // check for last sequence of continuous-1 if (prev_count > curr_count && (curr_count != 0)) return 0; return 1;} // Driver codeint main(){ int n = 179; if (findContinuous1(n)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 28858, "s": 27526, "text": null }, { "code": "// Java program to find if bit-pattern// of a number has increasing value of// continuous-1 or not.import java.io.*;public class GFG { // Returns true if n has increasing count of // continuous-1 else false static boolean findContinuous1(int n) { // converting decimal integer to binary string then // store the bit-pattern of n into // bit bitset- bp by converting the binary string to // char array char[] bp = (Integer.toBinaryString(n)).toCharArray(); int bits = bp.length; // set prev_count = 0 and curr_count = 0. int prev_count = 0; int curr_count = 0; int i = 0; while (i < bits) { if (bp[i] == '1') { // increment current count of continuous-1 curr_count++; i++; } // traverse all continuous-0 else if (bp[i - 1] == '0') { i++; curr_count = 0; continue; } // check prev_count and curr_count // on encounter of first zero after // continuous-1s else { if (curr_count < prev_count) return false; i++; prev_count = curr_count; curr_count = 0; } } // check for last sequence of continuous-1 if ((prev_count > curr_count) && (curr_count != 0)) return false; return true; } // Driver code public static void main(String args[]) { int n = 179; if (findContinuous1(n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by phasing17", "e": 30386, "s": 28858, "text": null }, { "code": "# Python3 program to find if bit-pattern# of a number has increasing value of# continuous-1 or not. # Returns true if n has increasing count of# continuous-1 else false def findContinuous1(n): # store the bit-pattern of n into # bit bitset- bp bp = list(bin(n)) bits = len(bp) # set prev_count = 0 and curr_count = 0. prev_count = 0 curr_count = 0 i = 0 while (i < bits): if (bp[i] == '1'): # increment current count of continuous-1 curr_count += 1 i += 1 # traverse all continuous-0 elif (bp[i - 1] == '0'): i += 1 curr_count = 0 continue # check prev_count and curr_count # on encounter of first zero after # continuous-1s else: if (curr_count < prev_count): return 0 i += 1 prev_count = curr_count curr_count = 0 # check for last sequence of continuous-1 if (prev_count > curr_count and (curr_count != 0)): return 0 return 1 # Driver coden = 179if (findContinuous1(n)): print(\"Yes\")else: print(\"No\") # This code is contributed by SHUBHAMSINGH10", "e": 31568, "s": 30386, "text": null }, { "code": "// C# program to find if bit-pattern// of a number has increasing value of// continuous-1 or not.using System;using System.Collections.Specialized; class GFG{ // Returns true if n has increasing count of // continuous-1 else false static bool findContinuous1(int n) { // store the bit-pattern of n into // bit bitset- bp string bp = Convert.ToString(n, 2); int bits = bp.Length; // set prev_count = 0 and curr_count = 0. int prev_count = 0, curr_count = 0; int i = 0; while (i < bits) { if (bp[i] == '1') { // increment current count of continuous-1 curr_count++; i++; } // traverse all continuous-0 else if (bp[i - 1] == '0') { i++; curr_count = 0; continue; } // check prev_count and curr_count // on encounter of first zero after // continuous-1s else { if (curr_count < prev_count) return false; i++; prev_count = curr_count; curr_count = 0; } } // check for last sequence of continuous-1 if (prev_count > curr_count && (curr_count != 0)) return false; return true; } // Driver Code static void Main() { int n = 179; if (findContinuous1(n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This Code was contributed by phasing17", "e": 33215, "s": 31568, "text": null }, { "code": "<script>// JavaScript program to find if bit-pattern// of a number has increasing value of// continuous-1 or not.function dec2bin(dec) { return (dec >>> 0).toString(2);}// Returns true if n has increasing count of// continuous-1 else falsefunction findContinuous1(n){ // store the bit-pattern of n into // bit bitset- bp let bp = dec2bin(n) let bits = bp.length // set prev_count = 0 and curr_count = 0. let prev_count = 0 let curr_count = 0 let i = 0 while (i < bits){ if (bp[i] == '1'){ // increment current count of continuous-1 curr_count += 1; i += 1; } // traverse all continuous-0 else if (bp[i - 1] == '0'){ i += 1 curr_count = 0 continue } // check prev_count and curr_count // on encounter of first zero after // continuous-1s else{ if (curr_count < prev_count) return 0 i += 1 prev_count = curr_count curr_count = 0 } } // check for last sequence of continuous-1 if (prev_count > curr_count && (curr_count != 0)) return 0 return 1}// Driver coden = 179if (findContinuous1(n)) document.write( \"Yes\")else document.write( \"No\") </script>", "e": 34524, "s": 33215, "text": null }, { "code": null, "e": 34528, "s": 34524, "text": "Yes" }, { "code": null, "e": 34750, "s": 34530, "text": "An efficient solution is to use decimal to binary conversion loop that divides number by 2 and take remainder as bit. This loop finds bits from right to left. So we check if right to left is in decreasing order or not. " }, { "code": null, "e": 34781, "s": 34750, "text": "Below is the implementation. " }, { "code": null, "e": 34785, "s": 34781, "text": "C++" }, { "code": null, "e": 34790, "s": 34785, "text": "Java" }, { "code": null, "e": 34798, "s": 34790, "text": "Python3" }, { "code": null, "e": 34801, "s": 34798, "text": "C#" }, { "code": null, "e": 34805, "s": 34801, "text": "PHP" }, { "code": null, "e": 34816, "s": 34805, "text": "Javascript" }, { "code": "// C++ program to check if counts of consecutive// 1s are increasing order.#include<bits/stdc++.h>using namespace std; // Returns true if n has counts of consecutive// 1's are increasing order.bool areSetBitsIncreasing(int n){ // Initialize previous count int prev_count = INT_MAX; // We traverse bits from right to left // and check if counts are decreasing // order. while (n > 0) { // Ignore 0s until we reach a set bit. while (n > 0 && n % 2 == 0) n = n/2; // Count current set bits int curr_count = 1; while (n > 0 && n % 2 == 1) { n = n/2; curr_count++; } // Compare current with previous and // update previous. if (curr_count >= prev_count) return false; prev_count = curr_count; } return true;} // Driver codeint main(){ int n = 10; if (areSetBitsIncreasing(n)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 35810, "s": 34816, "text": null }, { "code": "// Java program to check if counts of// consecutive 1s are increasing order.import java .io.*; class GFG { // Returns true if n has counts of // consecutive 1's are increasing // order. static boolean areSetBitsIncreasing(int n) { // Initialize previous count int prev_count = Integer.MAX_VALUE; // We traverse bits from right to // left and check if counts are // decreasing order. while (n > 0) { // Ignore 0s until we reach // a set bit. while (n > 0 && n % 2 == 0) n = n/2; // Count current set bits int curr_count = 1; while (n > 0 && n % 2 == 1) { n = n/2; curr_count++; } // Compare current with previous // and update previous. if (curr_count >= prev_count) return false; prev_count = curr_count; } return true; } // Driver code static public void main (String[] args) { int n = 10; if (areSetBitsIncreasing(n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by anuj_67.", "e": 37116, "s": 35810, "text": null }, { "code": "# Python3 program to check if counts of# consecutive 1s are increasing order. import sys # Returns true if n has counts of# consecutive 1's are increasing order.def areSetBitsIncreasing(n): # Initialize previous count prev_count = sys.maxsize # We traverse bits from right to # left and check if counts are # decreasing order. while (n > 0): # Ignore 0s until we reach a # set bit. while (n > 0 and n % 2 == 0): n = int(n/2) # Count current set bits curr_count = 1 while (n > 0 and n % 2 == 1): n = n/2 curr_count += 1 # Compare current with previous # and update previous. if (curr_count >= prev_count): return False prev_count = curr_count return True # Driver coden = 10 if (areSetBitsIncreasing(n)): print(\"Yes\")else: print(\"No\") # This code is contributed by Smitha", "e": 38059, "s": 37116, "text": null }, { "code": "// C# program to check if counts of// consecutive 1s are increasing order.using System; class GFG { // Returns true if n has counts of // consecutive 1's are increasing // order. static bool areSetBitsIncreasing(int n) { // Initialize previous count int prev_count = int.MaxValue; // We traverse bits from right to // left and check if counts are // decreasing order. while (n > 0) { // Ignore 0s until we reach // a set bit. while (n > 0 && n % 2 == 0) n = n/2; // Count current set bits int curr_count = 1; while (n > 0 && n % 2 == 1) { n = n/2; curr_count++; } // Compare current with previous // and update previous. if (curr_count >= prev_count) return false; prev_count = curr_count; } return true; } // Driver code static public void Main () { int n = 10; if (areSetBitsIncreasing(n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by anuj_67.", "e": 39335, "s": 38059, "text": null }, { "code": "<?php// PHP program to check if// counts of consecutive// 1s are increasing order. // Returns true if n has// counts of consecutive// 1's are increasing order.function areSetBitsIncreasing( $n){ // Initialize previous count $prev_count = PHP_INT_MAX; // We traverse bits from right // to left and check if counts // are decreasing order. while ($n > 0) { // Ignore 0s until we // reach a set bit. while ($n > 0 && $n % 2 == 0) $n = $n / 2; // Count current set bits $curr_count = 1; while ($n > 0 and $n % 2 == 1) { $n = $n / 2; $curr_count++; } // Compare current with previous // and update previous. if ($curr_count >= $prev_count) return false; $prev_count = $curr_count; } return true;} // Driver code$n = 10;if (areSetBitsIncreasing($n)) echo \"Yes\";else echo \"No\"; // This code is contributed by anuj_67?>", "e": 40308, "s": 39335, "text": null }, { "code": "<script> // Javascript program to check if counts of// consecutive 1s are increasing order. // Returns true if n has counts of// consecutive 1's are increasing// order.function areSetBitsIncreasing(n){ // Initialize previous count var prev_count = Number.MAX_VALUE; // We traverse bits from right to // left and check if counts are // decreasing order. while (n > 0) { // Ignore 0s until we reach // a set bit. while (n > 0 && n % 2 == 0) n = parseInt(n / 2); // Count current set bits var curr_count = 1; while (n > 0 && n % 2 == 1) { n = n / 2; curr_count++; } // Compare current with previous // and update previous. if (curr_count >= prev_count) return false; prev_count = curr_count; } return true;} // Driver codevar n = 10; if (areSetBitsIncreasing(n)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by Rajput-Ji </script>", "e": 41359, "s": 40308, "text": null }, { "code": null, "e": 41362, "s": 41359, "text": "No" }, { "code": null, "e": 41390, "s": 41364, "text": "Time Complexity: O(log2n)" }, { "code": null, "e": 41412, "s": 41390, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 41848, "s": 41412, "text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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": 41853, "s": 41848, "text": "vt_m" }, { "code": null, "e": 41874, "s": 41853, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 41889, "s": 41874, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 41899, "s": 41889, "text": "Rajput-Ji" }, { "code": null, "e": 41907, "s": 41899, "text": "rohan07" }, { "code": null, "e": 41917, "s": 41907, "text": "samim2000" }, { "code": null, "e": 41934, "s": 41917, "text": "surinderdawra388" }, { "code": null, "e": 41944, "s": 41934, "text": "phasing17" }, { "code": null, "e": 41954, "s": 41944, "text": "Bit Magic" }, { "code": null, "e": 41964, "s": 41954, "text": "Bit Magic" }, { "code": null, "e": 42062, "s": 41964, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42092, "s": 42062, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 42138, "s": 42092, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 42189, "s": 42138, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 42232, "s": 42189, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 42270, "s": 42232, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 42286, "s": 42270, "text": "Bit Fields in C" }, { "code": null, "e": 42321, "s": 42286, "text": "Find the element that appears once" }, { "code": null, "e": 42372, "s": 42321, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 42403, "s": 42372, "text": "C++ bitset and its application" } ]
C# | Implicitly Typed Arrays - GeeksforGeeks
23 Jun, 2021 Implicitly typed arrays are those arrays in which the type of the array is deduced from the element specified in the array initializer. The implicitly typed arrays are similar to implicitly typed variable. In general, implicitly typed arrays are used in the query expression.Important points about implicitly typed arrays: In C#, the implicitly typed arrays do not contain any specific data type. In implicitly typed array, when the user initializes the arrays with any data type then compiler automatically convert these arrays into that data type. Implicitly typed arrays generally declared using var keyword, here var does not follow []. For Example: var iarray = new []{1, 2, 3}; All types of array-like 1-D, Multidimensional, and Jagged Arrays etc. can be created as an implicitly typed array. In C#, it is necessary to initialize implicitly typed array and have the same data type. Example 1: Below program illustrates how to use 1-Dimensional Implicitly typed array. CSharp // C# program to illustrate// 1-D implicitly typed arrayusing System; public class GFG { // Main method static public void Main() { // Creating and initializing 1-D // implicitly typed array var author_names = new[] {"Shilpa", "Soniya", "Shivi", "Ritika"}; Console.WriteLine("List of Authors is: "); // Display the data of the given array foreach(string data in author_names) { Console.WriteLine(data); } }} List of Authors is: Shilpa Soniya Shivi Ritika Example 2: Below program illustrate the use of Multidimensional implicitly typed arrays. CSharp // C# program to illustrate// 2-D implicitly typed arrayusing System; public class GFG { // Main method static public void Main() { // Creating and initializing // 2-D implicitly typed array var language = new[, ] { {"C", "Java"}, {"Python", "C#"} }; Console.WriteLine("Programming Languages: "); // taking a string string a; // Display the value at index [1, 0] a = language[1, 0]; Console.WriteLine(a); // Display the value at index [0, 2] a = language[0, 1]; Console.WriteLine(a); }} Programming Languages: Python Java Example 3: Below code demonstrate the use of Implicitly typed jagged arrays. CSharp // C# program to illustrate// implicitly typed jagged arrayusing System; class GFG { // Main method static public void Main() { // Creating and initializing // implicitly typed jagged array var jarray = new[] { new[] { 785, 721, 344, 123 }, new[] { 234, 600 }, new[] { 34, 545, 808 }, new[] { 200, 220 } }; Console.WriteLine("Data of jagged array is :"); // Display the data of array for (int a = 0; a < jarray.Length; a++) { for (int b = 0; b < jarray[a].Length; b++) Console.Write(jarray[a][b] + " "); Console.WriteLine(); } }} Data of jagged array is : 785 721 344 123 234 600 34 545 808 200 220 ruhelaa48 CSharp-Arrays Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Linked List Implementation in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n23 Jun, 2021" }, { "code": null, "e": 25872, "s": 25547, "text": "Implicitly typed arrays are those arrays in which the type of the array is deduced from the element specified in the array initializer. The implicitly typed arrays are similar to implicitly typed variable. In general, implicitly typed arrays are used in the query expression.Important points about implicitly typed arrays: " }, { "code": null, "e": 25946, "s": 25872, "text": "In C#, the implicitly typed arrays do not contain any specific data type." }, { "code": null, "e": 26099, "s": 25946, "text": "In implicitly typed array, when the user initializes the arrays with any data type then compiler automatically convert these arrays into that data type." }, { "code": null, "e": 26204, "s": 26099, "text": "Implicitly typed arrays generally declared using var keyword, here var does not follow []. For Example: " }, { "code": null, "e": 26234, "s": 26204, "text": "var iarray = new []{1, 2, 3};" }, { "code": null, "e": 26349, "s": 26234, "text": "All types of array-like 1-D, Multidimensional, and Jagged Arrays etc. can be created as an implicitly typed array." }, { "code": null, "e": 26438, "s": 26349, "text": "In C#, it is necessary to initialize implicitly typed array and have the same data type." }, { "code": null, "e": 26526, "s": 26438, "text": "Example 1: Below program illustrates how to use 1-Dimensional Implicitly typed array. " }, { "code": null, "e": 26533, "s": 26526, "text": "CSharp" }, { "code": "// C# program to illustrate// 1-D implicitly typed arrayusing System; public class GFG { // Main method static public void Main() { // Creating and initializing 1-D // implicitly typed array var author_names = new[] {\"Shilpa\", \"Soniya\", \"Shivi\", \"Ritika\"}; Console.WriteLine(\"List of Authors is: \"); // Display the data of the given array foreach(string data in author_names) { Console.WriteLine(data); } }}", "e": 27057, "s": 26533, "text": null }, { "code": null, "e": 27105, "s": 27057, "text": "List of Authors is: \nShilpa\nSoniya\nShivi\nRitika" }, { "code": null, "e": 27198, "s": 27107, "text": "Example 2: Below program illustrate the use of Multidimensional implicitly typed arrays. " }, { "code": null, "e": 27205, "s": 27198, "text": "CSharp" }, { "code": "// C# program to illustrate// 2-D implicitly typed arrayusing System; public class GFG { // Main method static public void Main() { // Creating and initializing // 2-D implicitly typed array var language = new[, ] { {\"C\", \"Java\"}, {\"Python\", \"C#\"} }; Console.WriteLine(\"Programming Languages: \"); // taking a string string a; // Display the value at index [1, 0] a = language[1, 0]; Console.WriteLine(a); // Display the value at index [0, 2] a = language[0, 1]; Console.WriteLine(a); }}", "e": 27822, "s": 27205, "text": null }, { "code": null, "e": 27858, "s": 27822, "text": "Programming Languages: \nPython\nJava" }, { "code": null, "e": 27938, "s": 27860, "text": "Example 3: Below code demonstrate the use of Implicitly typed jagged arrays. " }, { "code": null, "e": 27945, "s": 27938, "text": "CSharp" }, { "code": "// C# program to illustrate// implicitly typed jagged arrayusing System; class GFG { // Main method static public void Main() { // Creating and initializing // implicitly typed jagged array var jarray = new[] { new[] { 785, 721, 344, 123 }, new[] { 234, 600 }, new[] { 34, 545, 808 }, new[] { 200, 220 } }; Console.WriteLine(\"Data of jagged array is :\"); // Display the data of array for (int a = 0; a < jarray.Length; a++) { for (int b = 0; b < jarray[a].Length; b++) Console.Write(jarray[a][b] + \" \"); Console.WriteLine(); } }}", "e": 28628, "s": 27945, "text": null }, { "code": null, "e": 28700, "s": 28628, "text": "Data of jagged array is :\n785 721 344 123 \n234 600 \n34 545 808 \n200 220" }, { "code": null, "e": 28712, "s": 28702, "text": "ruhelaa48" }, { "code": null, "e": 28726, "s": 28712, "text": "CSharp-Arrays" }, { "code": null, "e": 28733, "s": 28726, "text": "Picked" }, { "code": null, "e": 28736, "s": 28733, "text": "C#" }, { "code": null, "e": 28834, "s": 28736, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28857, "s": 28834, "text": "Extension Method in C#" }, { "code": null, "e": 28885, "s": 28857, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28902, "s": 28885, "text": "C# | Inheritance" }, { "code": null, "e": 28924, "s": 28902, "text": "Partial Classes in C#" }, { "code": null, "e": 28953, "s": 28924, "text": "C# | Generics - Introduction" }, { "code": null, "e": 28993, "s": 28953, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 29016, "s": 28993, "text": "Switch Statement in C#" }, { "code": null, "e": 29056, "s": 29016, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 29099, "s": 29056, "text": "C# | How to insert an element in an Array?" } ]
Pandas.get_option() function in Python - GeeksforGeeks
02 Jun, 2021 Pandas have an options system that lets you customize some aspects of its behavior, display-related options being those the user is most likely to adjust. Let us see how to see the value of a specified option. Syntax : pandas.get_option(pat)Parameters : pat : Regexp which should match a single option. Returns : Value of the option Raises : OptionError if no such option exists Example 1 : Fetching the value of maximum and minimum number of columns and rows that can be displayed. Python3 # importing the moduleimport pandas as pd # fetching maximum number of# columns that can be displayedprint("The value of max_columns : " + str(pd.get_option("display.max_columns"))) # fetching maximum number of# rows that can be displayedprint("The value of max_rows : " + str(pd.get_option("display.max_rows"))) # fetching minimum number of# rows that can be displayedprint("The value of min_rows : " + str(pd.get_option("display.min_rows"))) Output : Output may vary. Example 2 : Fetching the attributes related to Excel files. Python3 # importing the moduleimport pandas as pd # default Excel reader engine for ‘ods’ filesprint("The default Excel reader engine for ‘ods’ files : " + str(pd.get_option("io.excel.ods.reader"))) # default Excel reader engine for ‘xls’ filesprint("The default Excel reader engine for ‘xls’ files : " + str(pd.get_option("io.excel.xls.reader"))) # default Excel writer engine for ‘xls’ filesprint("The default Excel writer engine for ‘xls’ files : " + str(pd.get_option("io.excel.xls.writer"))) # default Excel reader engine for ‘xlsb’ filesprint("The default Excel reader engine for ‘xlsb’ files : " + str(pd.get_option("io.excel.xlsb.reader"))) # default Excel reader engine for ‘xlsm’ filesprint("The default Excel reader engine for ‘xlsm’ files : " + str(pd.get_option("io.excel.xlsm.reader"))) # default Excel writer engine for ‘xlsm’ filesprint("The default Excel writer engine for ‘xlsm’ files : " + str(pd.get_option("io.excel.xlsm.writer"))) # default Excel reader engine for ‘xlsm’ filesprint("The default Excel reader engine for ‘xlsx’ files : " + str(pd.get_option("io.excel.xlsx.reader"))) # default Excel writer engine for ‘xlsx’ filesprint("The default Excel writer engine for ‘xlsx’ files : " + str(pd.get_option("io.excel.xlsx.writer"))) Output : anikaseth98 Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n02 Jun, 2021" }, { "code": null, "e": 25747, "s": 25537, "text": "Pandas have an options system that lets you customize some aspects of its behavior, display-related options being those the user is most likely to adjust. Let us see how to see the value of a specified option." }, { "code": null, "e": 25792, "s": 25747, "text": "Syntax : pandas.get_option(pat)Parameters : " }, { "code": null, "e": 25841, "s": 25792, "text": "pat : Regexp which should match a single option." }, { "code": null, "e": 25919, "s": 25841, "text": "Returns : Value of the option Raises : OptionError if no such option exists " }, { "code": null, "e": 26025, "s": 25919, "text": "Example 1 : Fetching the value of maximum and minimum number of columns and rows that can be displayed. " }, { "code": null, "e": 26033, "s": 26025, "text": "Python3" }, { "code": "# importing the moduleimport pandas as pd # fetching maximum number of# columns that can be displayedprint(\"The value of max_columns : \" + str(pd.get_option(\"display.max_columns\"))) # fetching maximum number of# rows that can be displayedprint(\"The value of max_rows : \" + str(pd.get_option(\"display.max_rows\"))) # fetching minimum number of# rows that can be displayedprint(\"The value of min_rows : \" + str(pd.get_option(\"display.min_rows\")))", "e": 26492, "s": 26033, "text": null }, { "code": null, "e": 26503, "s": 26492, "text": "Output : " }, { "code": null, "e": 26520, "s": 26503, "text": "Output may vary." }, { "code": null, "e": 26581, "s": 26520, "text": "Example 2 : Fetching the attributes related to Excel files. " }, { "code": null, "e": 26589, "s": 26581, "text": "Python3" }, { "code": "# importing the moduleimport pandas as pd # default Excel reader engine for ‘ods’ filesprint(\"The default Excel reader engine for ‘ods’ files : \" + str(pd.get_option(\"io.excel.ods.reader\"))) # default Excel reader engine for ‘xls’ filesprint(\"The default Excel reader engine for ‘xls’ files : \" + str(pd.get_option(\"io.excel.xls.reader\"))) # default Excel writer engine for ‘xls’ filesprint(\"The default Excel writer engine for ‘xls’ files : \" + str(pd.get_option(\"io.excel.xls.writer\"))) # default Excel reader engine for ‘xlsb’ filesprint(\"The default Excel reader engine for ‘xlsb’ files : \" + str(pd.get_option(\"io.excel.xlsb.reader\"))) # default Excel reader engine for ‘xlsm’ filesprint(\"The default Excel reader engine for ‘xlsm’ files : \" + str(pd.get_option(\"io.excel.xlsm.reader\"))) # default Excel writer engine for ‘xlsm’ filesprint(\"The default Excel writer engine for ‘xlsm’ files : \" + str(pd.get_option(\"io.excel.xlsm.writer\"))) # default Excel reader engine for ‘xlsm’ filesprint(\"The default Excel reader engine for ‘xlsx’ files : \" + str(pd.get_option(\"io.excel.xlsx.reader\"))) # default Excel writer engine for ‘xlsx’ filesprint(\"The default Excel writer engine for ‘xlsx’ files : \" + str(pd.get_option(\"io.excel.xlsx.writer\")))", "e": 27878, "s": 26589, "text": null }, { "code": null, "e": 27889, "s": 27878, "text": "Output : " }, { "code": null, "e": 27903, "s": 27891, "text": "anikaseth98" }, { "code": null, "e": 27917, "s": 27903, "text": "Python-pandas" }, { "code": null, "e": 27924, "s": 27917, "text": "Python" }, { "code": null, "e": 28022, "s": 27924, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28054, "s": 28022, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28096, "s": 28054, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28138, "s": 28096, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28165, "s": 28138, "text": "Python Classes and Objects" }, { "code": null, "e": 28221, "s": 28165, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28243, "s": 28221, "text": "Defaultdict in Python" }, { "code": null, "e": 28282, "s": 28243, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28313, "s": 28282, "text": "Python | os.path.join() method" }, { "code": null, "e": 28342, "s": 28313, "text": "Create a directory in Python" } ]
Iterative selection sort for linked list - GeeksforGeeks
21 Jun, 2021 Given a linked list, the task is to sort the linked list in ascending order by using selection sort.Examples: Input : 1->4->2->2->3 Output : 1->2->2->3->4 Input : 5->4->3->2 Output : 2->3->4->5 Selection Sort Algorithm: Iterate the given list N times where N is the number of elements in the list. In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.Example: list = 64 25 12 22 11 // Find the minimum element in list(0...4) // and place it at beginning 11 25 12 22 64 // Find the minimum element in list(1...4) // and place it at beginning of list(1...4) 11 12 25 22 64 // Find the minimum element in list(2...4) // and place it at beginning of list(2...4) 11 12 22 25 64 // Find the minimum element in list(3...4) // and place it at beginning of list(3...4) 11 12 22 25 64 The swapping required can be done in two ways: By swapping the data parts of the nodes.By swapping the complete nodes. By swapping the data parts of the nodes. By swapping the complete nodes. Second implementation is generally used when elements of the list are some kind of records because in such a case data swapping becomes tedious and expensive due to the presence of a large number of data elements.Implementation Method 1: Below is the implementation of selection sort function for sorting linked lists by swapping only data parts of a node. C++ Java C# Javascript Python3 void selectionSort(node* head){ node* temp = head; // Traverse the List while (temp) { node* min = temp; node* r = temp->next; // Traverse the unsorted sublist while (r) { if (min->data > r->data) min = r; r = r->next; } // Swap Data int x = temp->data; temp->data = min->data; min->data = x; temp = temp->next; }} void selectionSort(node head){ node temp = head; // Traverse the List while (temp) { node min = temp; node r = temp.next; // Traverse the unsorted sublist while (r) { if (min.data > r.data) min = r; r = r.next; } // Swap Data int x = temp.data; temp.data = min.data; min.data = x; temp = temp.next; }} // This code is contributed by shivanisinghss2110 static void selectionSort(node head){ node temp = head; // Traverse the List while (temp) { node min = temp; node r = temp.next; // Traverse the unsorted sublist while (r) { if (min.data > r.data) min = r; r = r.next; } // Swap Data int x = temp.data; temp.data = min.data; min.data = x; temp = temp.next; }}// This code contributed by shivanisinghss2110 <script> function selectionSort(head){ var temp = head; // Traverse the List while (temp) { var min = temp; var r = temp.next; // Traverse the unsorted sublist while (r) { if (min.data > r.data) min = r; r = r.next; } // Swap Data var x = temp.data; temp.data = min.data; min.data = x; temp = temp.next; }} </script> def selectionSort(head): temp = head # Traverse the List while (temp): minn = temp r = temp.next # Traverse the unsorted sublist while (r): if (minn.data > r.data): minn = r r = r.next # Swap Data x = temp.data temp.data = minn.data minn.data = x temp = temp.next # This code is contributed by shubhamsingh10 Method 2: Data swapping is no doubt easier to implement and understand, but in some cases( as one mentioned above ), it isn’t desirable. While doing swapping of the next parts of two nodes, four cases are needed to be taken into consideration : Nodes are adjacent and the first node is the starting node.Nodes are adjacent and the first node isn’t the starting node.Nodes aren’t adjacent and the first node is the starting node.Nodes aren’t adjacent and the first node isn’t the starting node. Nodes are adjacent and the first node is the starting node. Nodes are adjacent and the first node isn’t the starting node. Nodes aren’t adjacent and the first node is the starting node. Nodes aren’t adjacent and the first node isn’t the starting node. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Linked List Nodestruct Node { int data; Node* next;}; // Utility function to create a// new Linked List NodeNode* newNode(int val){ Node* temp = new Node; temp->data = val; temp->next = NULL; return temp;} // Function to sort a linked list using selection// sort algorithm by swapping the next pointersNode* selectionSort(Node* head){ Node *a, *b, *c, *d, *r; a = b = head; // While b is not the last node while (b->next) { c = d = b->next; // While d is pointing to a valid node while (d) { if (b->data > d->data) { // If d appears immediately after b if (b->next == d) { // Case 1: b is the head of the linked list if (b == head) { // Move d before b b->next = d->next; d->next = b; // Swap b and d pointers r = b; b = d; d = r; c = d; // Update the head head = b; // Skip to the next element // as it is already in order d = d->next; } // Case 2: b is not the head of the linked list else { // Move d before b b->next = d->next; d->next = b; a->next = d; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d->next; } } // If b and d have some non-zero // number of nodes in between them else { // Case 3: b is the head of the linked list if (b == head) { // Swap b->next and d->next r = b->next; b->next = d->next; d->next = r; c->next = b; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d->next; // Update the head head = b; } // Case 4: b is not the head of the linked list else { // Swap b->next and d->next r = b->next; b->next = d->next; d->next = r; c->next = b; a->next = d; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d->next; } } } else { // Update c and skip to the next element // as it is already in order c = d; d = d->next; } } a = b; b = b->next; } return head;} // Function to print the listvoid printList(Node* head){ while (head) { cout << head->data << " "; head = head->next; }} // Driver Codeint main(){ Node* head = newNode(5); head->next = newNode(4); head->next->next = newNode(3); head = selectionSort(head); printList(head); return 0;} // Java implementation of the approachclass GFG { // Linked List Node static class Node { int data; Node next; }; // Utility function to create a // new Linked List Node static Node newNode(int val) { Node temp = new Node(); temp.data = val; temp.next = null; return temp; } // Function to sort a linked list using selection // sort algorithm by swapping the next pointers static Node selectionSort(Node head) { Node a, b, c, d, r; a = b = head; // While b is not the last node while (b.next != null) { c = d = b.next; // While d is pointing to a valid node while (d != null) { if (b.data > d.data) { // If d appears immediately after b if (b.next == d) { // Case 1: b is the head of the linked list if (b == head) { // Move d before b b.next = d.next; d.next = b; // Swap b and d pointers r = b; b = d; d = r; c = d; // Update the head head = b; // Skip to the next element // as it is already in order d = d.next; } // Case 2: b is not the head of the linked list else { // Move d before b b.next = d.next; d.next = b; a.next = d; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; } } // If b and d have some non-zero // number of nodes in between them else { // Case 3: b is the head of the linked list if (b == head) { // Swap b.next and d.next r = b.next; b.next = d.next; d.next = r; c.next = b; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; // Update the head head = b; } // Case 4: b is not the head of the linked list else { // Swap b.next and d.next r = b.next; b.next = d.next; d.next = r; c.next = b; a.next = d; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; } } } else { // Update c and skip to the next element // as it is already in order c = d; d = d.next; } } a = b; b = b.next; } return head; } // Function to print the list static void printList(Node head) { while (head != null) { System.out.print(head.data + " "); head = head.next; } } // Driver Code public static void main(String args[]) { Node head = newNode(5); head.next = newNode(4); head.next.next = newNode(3); head = selectionSort(head); printList(head); }} // This code is contributed by Arnab Kundu # Python3 implementation of the approach # Linked List Nodeclass Node: def __init__(self, val): self.data = val self.next = None # Function to sort a linked list# using selection sort algorithm# by swapping the next pointersdef selectionSort(head): a = b = head # While b is not the last node while b.next: c = d = b.next # While d is pointing to a valid node while d: if b.data > d.data: # If d appears immediately after b if b.next == d: # Case 1: b is the head # of the linked list if b == head: # Move d before b b.next = d.next d.next = b # Swap b and d pointers b, d = d, b c = d # Update the head head = b # Skip to the next element # as it is already in order d = d.next # Case 2: b is not the head # of the linked list else: # Move d before b b.next = d.next d.next = b a.next = d # Swap b and d pointers b, d = d, b c = d # Skip to the next element # as it is already in order d = d.next # If b and d have some non-zero # number of nodes in between them else: # Case 3: b is the head # of the linked list if b == head: # Swap b.next and d.next r = b.next b.next = d.next d.next = r c.next = b # Swap b and d pointers b, d = d, b c = d # Skip to the next element # as it is already in order d = d.next # Update the head head = b # Case 4: b is not the head # of the linked list else: # Swap b.next and d.next r = b.next b.next = d.next d.next = r c.next = b a.next = d # Swap b and d pointers b, d = d, b c = d # Skip to the next element # as it is already in order d = d.next else: # Update c and skip to the next element # as it is already in order c = d d = d.next a = b b = b.next return head # Function to print the listdef printList(head): while head: print(head.data, end = " ") head = head.next # Driver Codeif __name__ == "__main__": head = Node(5) head.next = Node(4) head.next.next = Node(3) head = selectionSort(head) printList(head) # This code is contributed# by Rituraj Jain // C# implementation of the approachusing System; class GFG { // Linked List Node public class Node { public int data; public Node next; }; // Utility function to create a // new Linked List Node static Node newNode(int val) { Node temp = new Node(); temp.data = val; temp.next = null; return temp; } // Function to sort a linked list using selection // sort algorithm by swapping the next pointers static Node selectionSort(Node head) { Node a, b, c, d, r; a = b = head; // While b is not the last node while (b.next != null) { c = d = b.next; // While d is pointing to a valid node while (d != null) { if (b.data > d.data) { // If d appears immediately after b if (b.next == d) { // Case 1: b is the head of the linked list if (b == head) { // Move d before b b.next = d.next; d.next = b; // Swap b and d pointers r = b; b = d; d = r; c = d; // Update the head head = b; // Skip to the next element // as it is already in order d = d.next; } // Case 2: b is not the head of the linked list else { // Move d before b b.next = d.next; d.next = b; a.next = d; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; } } // If b and d have some non-zero // number of nodes in between them else { // Case 3: b is the head of the linked list if (b == head) { // Swap b.next and d.next r = b.next; b.next = d.next; d.next = r; c.next = b; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; // Update the head head = b; } // Case 4: b is not the head of the linked list else { // Swap b.next and d.next r = b.next; b.next = d.next; d.next = r; c.next = b; a.next = d; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; } } } else { // Update c and skip to the next element // as it is already in order c = d; d = d.next; } } a = b; b = b.next; } return head; } // Function to print the list static void printList(Node head) { while (head != null) { Console.Write(head.data + " "); head = head.next; } } // Driver Code public static void Main(String[] arg) { Node head = newNode(5); head.next = newNode(4); head.next.next = newNode(3); head = selectionSort(head); printList(head); }} // This code contributed by Rajput-Ji <script>// Javascript implementation of the approach // Structure of a node of linked listclass Node { constructor() { this.data = 0; this.next = null; } } // Utility function to create a// new Linked List Nodefunction newNode( val){ var temp = new Node(); temp.data = val; temp.next = null; return temp;} // Function to sort a linked list using selection// sort algorithm by swapping the next pointersfunction selectionSort( head) { var a, b, c, d, r; a = b = head; // While b is not the last node while (b.next != null) { c = d = b.next; // While d is pointing to a valid node while (d != null) { if (b.data > d.data) { // If d appears immediately after b if (b.next == d) { // Case 1: b is the head of the linked list if (b == head) { // Move d before b b.next = d.next; d.next = b; // Swap b and d pointers r = b; b = d; d = r; c = d; // Update the head head = b; // Skip to the next element // as it is already in order d = d.next; } // Case 2: b is not the head of the linked list else { // Move d before b b.next = d.next; d.next = b; a.next = d; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; } } // If b and d have some non-zero // number of nodes in between them else { // Case 3: b is the head of the linked list if (b == head) { // Swap b.next and d.next r = b.next; b.next = d.next; d.next = r; c.next = b; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; // Update the head head = b; } // Case 4: b is not the head of the linked list else { // Swap b.next and d.next r = b.next; b.next = d.next; d.next = r; c.next = b; a.next = d; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; } } } else { // Update c and skip to the next element // as it is already in order c = d; d = d.next; } } a = b; b = b.next; } return head; } // Function to print the listfunction printList( head){ while (head != null) { document.write(head.data + " "); head = head.next; }} // Driver Code var head = newNode(5); head.next = newNode(4); head.next.next = newNode(3); head = selectionSort(head); printList(head); // This code is contributed by jana_sayantan.</script> 3 4 5 andrew1234 rituraj_jain Rajput-Ji SHUBHAMSINGH10 shivanisinghss2110 jana_sayantan rrrtnx selection-sort Linked List Sorting Linked List Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. LinkedList in Java Linked List vs Array Doubly Linked List | Set 1 (Introduction and Insertion) Merge two sorted linked lists Queue - Linked List Implementation
[ { "code": null, "e": 25841, "s": 25813, "text": "\n21 Jun, 2021" }, { "code": null, "e": 25953, "s": 25841, "text": "Given a linked list, the task is to sort the linked list in ascending order by using selection sort.Examples: " }, { "code": null, "e": 26038, "s": 25953, "text": "Input : 1->4->2->2->3\nOutput : 1->2->2->3->4\n\nInput : 5->4->3->2\nOutput : 2->3->4->5" }, { "code": null, "e": 26313, "s": 26040, "text": "Selection Sort Algorithm: Iterate the given list N times where N is the number of elements in the list. In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.Example: " }, { "code": null, "e": 26733, "s": 26313, "text": "list = 64 25 12 22 11\n\n// Find the minimum element in list(0...4)\n// and place it at beginning\n11 25 12 22 64\n\n// Find the minimum element in list(1...4)\n// and place it at beginning of list(1...4)\n11 12 25 22 64\n\n// Find the minimum element in list(2...4)\n// and place it at beginning of list(2...4)\n11 12 22 25 64\n\n// Find the minimum element in list(3...4)\n// and place it at beginning of list(3...4)\n11 12 22 25 64 " }, { "code": null, "e": 26782, "s": 26733, "text": "The swapping required can be done in two ways: " }, { "code": null, "e": 26854, "s": 26782, "text": "By swapping the data parts of the nodes.By swapping the complete nodes." }, { "code": null, "e": 26895, "s": 26854, "text": "By swapping the data parts of the nodes." }, { "code": null, "e": 26927, "s": 26895, "text": "By swapping the complete nodes." }, { "code": null, "e": 27286, "s": 26927, "text": "Second implementation is generally used when elements of the list are some kind of records because in such a case data swapping becomes tedious and expensive due to the presence of a large number of data elements.Implementation Method 1: Below is the implementation of selection sort function for sorting linked lists by swapping only data parts of a node. " }, { "code": null, "e": 27290, "s": 27286, "text": "C++" }, { "code": null, "e": 27295, "s": 27290, "text": "Java" }, { "code": null, "e": 27298, "s": 27295, "text": "C#" }, { "code": null, "e": 27309, "s": 27298, "text": "Javascript" }, { "code": null, "e": 27317, "s": 27309, "text": "Python3" }, { "code": "void selectionSort(node* head){ node* temp = head; // Traverse the List while (temp) { node* min = temp; node* r = temp->next; // Traverse the unsorted sublist while (r) { if (min->data > r->data) min = r; r = r->next; } // Swap Data int x = temp->data; temp->data = min->data; min->data = x; temp = temp->next; }}", "e": 27755, "s": 27317, "text": null }, { "code": "void selectionSort(node head){ node temp = head; // Traverse the List while (temp) { node min = temp; node r = temp.next; // Traverse the unsorted sublist while (r) { if (min.data > r.data) min = r; r = r.next; } // Swap Data int x = temp.data; temp.data = min.data; min.data = x; temp = temp.next; }} // This code is contributed by shivanisinghss2110", "e": 28230, "s": 27755, "text": null }, { "code": "static void selectionSort(node head){ node temp = head; // Traverse the List while (temp) { node min = temp; node r = temp.next; // Traverse the unsorted sublist while (r) { if (min.data > r.data) min = r; r = r.next; } // Swap Data int x = temp.data; temp.data = min.data; min.data = x; temp = temp.next; }}// This code contributed by shivanisinghss2110", "e": 28708, "s": 28230, "text": null }, { "code": "<script> function selectionSort(head){ var temp = head; // Traverse the List while (temp) { var min = temp; var r = temp.next; // Traverse the unsorted sublist while (r) { if (min.data > r.data) min = r; r = r.next; } // Swap Data var x = temp.data; temp.data = min.data; min.data = x; temp = temp.next; }} </script>", "e": 29149, "s": 28708, "text": null }, { "code": "def selectionSort(head): temp = head # Traverse the List while (temp): minn = temp r = temp.next # Traverse the unsorted sublist while (r): if (minn.data > r.data): minn = r r = r.next # Swap Data x = temp.data temp.data = minn.data minn.data = x temp = temp.next # This code is contributed by shubhamsingh10", "e": 29625, "s": 29149, "text": null }, { "code": null, "e": 29872, "s": 29625, "text": "Method 2: Data swapping is no doubt easier to implement and understand, but in some cases( as one mentioned above ), it isn’t desirable. While doing swapping of the next parts of two nodes, four cases are needed to be taken into consideration : " }, { "code": null, "e": 30121, "s": 29872, "text": "Nodes are adjacent and the first node is the starting node.Nodes are adjacent and the first node isn’t the starting node.Nodes aren’t adjacent and the first node is the starting node.Nodes aren’t adjacent and the first node isn’t the starting node." }, { "code": null, "e": 30181, "s": 30121, "text": "Nodes are adjacent and the first node is the starting node." }, { "code": null, "e": 30244, "s": 30181, "text": "Nodes are adjacent and the first node isn’t the starting node." }, { "code": null, "e": 30307, "s": 30244, "text": "Nodes aren’t adjacent and the first node is the starting node." }, { "code": null, "e": 30373, "s": 30307, "text": "Nodes aren’t adjacent and the first node isn’t the starting node." }, { "code": null, "e": 30426, "s": 30373, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 30430, "s": 30426, "text": "C++" }, { "code": null, "e": 30435, "s": 30430, "text": "Java" }, { "code": null, "e": 30443, "s": 30435, "text": "Python3" }, { "code": null, "e": 30446, "s": 30443, "text": "C#" }, { "code": null, "e": 30457, "s": 30446, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Linked List Nodestruct Node { int data; Node* next;}; // Utility function to create a// new Linked List NodeNode* newNode(int val){ Node* temp = new Node; temp->data = val; temp->next = NULL; return temp;} // Function to sort a linked list using selection// sort algorithm by swapping the next pointersNode* selectionSort(Node* head){ Node *a, *b, *c, *d, *r; a = b = head; // While b is not the last node while (b->next) { c = d = b->next; // While d is pointing to a valid node while (d) { if (b->data > d->data) { // If d appears immediately after b if (b->next == d) { // Case 1: b is the head of the linked list if (b == head) { // Move d before b b->next = d->next; d->next = b; // Swap b and d pointers r = b; b = d; d = r; c = d; // Update the head head = b; // Skip to the next element // as it is already in order d = d->next; } // Case 2: b is not the head of the linked list else { // Move d before b b->next = d->next; d->next = b; a->next = d; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d->next; } } // If b and d have some non-zero // number of nodes in between them else { // Case 3: b is the head of the linked list if (b == head) { // Swap b->next and d->next r = b->next; b->next = d->next; d->next = r; c->next = b; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d->next; // Update the head head = b; } // Case 4: b is not the head of the linked list else { // Swap b->next and d->next r = b->next; b->next = d->next; d->next = r; c->next = b; a->next = d; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d->next; } } } else { // Update c and skip to the next element // as it is already in order c = d; d = d->next; } } a = b; b = b->next; } return head;} // Function to print the listvoid printList(Node* head){ while (head) { cout << head->data << \" \"; head = head->next; }} // Driver Codeint main(){ Node* head = newNode(5); head->next = newNode(4); head->next->next = newNode(3); head = selectionSort(head); printList(head); return 0;}", "e": 34540, "s": 30457, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Linked List Node static class Node { int data; Node next; }; // Utility function to create a // new Linked List Node static Node newNode(int val) { Node temp = new Node(); temp.data = val; temp.next = null; return temp; } // Function to sort a linked list using selection // sort algorithm by swapping the next pointers static Node selectionSort(Node head) { Node a, b, c, d, r; a = b = head; // While b is not the last node while (b.next != null) { c = d = b.next; // While d is pointing to a valid node while (d != null) { if (b.data > d.data) { // If d appears immediately after b if (b.next == d) { // Case 1: b is the head of the linked list if (b == head) { // Move d before b b.next = d.next; d.next = b; // Swap b and d pointers r = b; b = d; d = r; c = d; // Update the head head = b; // Skip to the next element // as it is already in order d = d.next; } // Case 2: b is not the head of the linked list else { // Move d before b b.next = d.next; d.next = b; a.next = d; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; } } // If b and d have some non-zero // number of nodes in between them else { // Case 3: b is the head of the linked list if (b == head) { // Swap b.next and d.next r = b.next; b.next = d.next; d.next = r; c.next = b; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; // Update the head head = b; } // Case 4: b is not the head of the linked list else { // Swap b.next and d.next r = b.next; b.next = d.next; d.next = r; c.next = b; a.next = d; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; } } } else { // Update c and skip to the next element // as it is already in order c = d; d = d.next; } } a = b; b = b.next; } return head; } // Function to print the list static void printList(Node head) { while (head != null) { System.out.print(head.data + \" \"); head = head.next; } } // Driver Code public static void main(String args[]) { Node head = newNode(5); head.next = newNode(4); head.next.next = newNode(3); head = selectionSort(head); printList(head); }} // This code is contributed by Arnab Kundu", "e": 39175, "s": 34540, "text": null }, { "code": "# Python3 implementation of the approach # Linked List Nodeclass Node: def __init__(self, val): self.data = val self.next = None # Function to sort a linked list# using selection sort algorithm# by swapping the next pointersdef selectionSort(head): a = b = head # While b is not the last node while b.next: c = d = b.next # While d is pointing to a valid node while d: if b.data > d.data: # If d appears immediately after b if b.next == d: # Case 1: b is the head # of the linked list if b == head: # Move d before b b.next = d.next d.next = b # Swap b and d pointers b, d = d, b c = d # Update the head head = b # Skip to the next element # as it is already in order d = d.next # Case 2: b is not the head # of the linked list else: # Move d before b b.next = d.next d.next = b a.next = d # Swap b and d pointers b, d = d, b c = d # Skip to the next element # as it is already in order d = d.next # If b and d have some non-zero # number of nodes in between them else: # Case 3: b is the head # of the linked list if b == head: # Swap b.next and d.next r = b.next b.next = d.next d.next = r c.next = b # Swap b and d pointers b, d = d, b c = d # Skip to the next element # as it is already in order d = d.next # Update the head head = b # Case 4: b is not the head # of the linked list else: # Swap b.next and d.next r = b.next b.next = d.next d.next = r c.next = b a.next = d # Swap b and d pointers b, d = d, b c = d # Skip to the next element # as it is already in order d = d.next else: # Update c and skip to the next element # as it is already in order c = d d = d.next a = b b = b.next return head # Function to print the listdef printList(head): while head: print(head.data, end = \" \") head = head.next # Driver Codeif __name__ == \"__main__\": head = Node(5) head.next = Node(4) head.next.next = Node(3) head = selectionSort(head) printList(head) # This code is contributed# by Rituraj Jain", "e": 42735, "s": 39175, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG { // Linked List Node public class Node { public int data; public Node next; }; // Utility function to create a // new Linked List Node static Node newNode(int val) { Node temp = new Node(); temp.data = val; temp.next = null; return temp; } // Function to sort a linked list using selection // sort algorithm by swapping the next pointers static Node selectionSort(Node head) { Node a, b, c, d, r; a = b = head; // While b is not the last node while (b.next != null) { c = d = b.next; // While d is pointing to a valid node while (d != null) { if (b.data > d.data) { // If d appears immediately after b if (b.next == d) { // Case 1: b is the head of the linked list if (b == head) { // Move d before b b.next = d.next; d.next = b; // Swap b and d pointers r = b; b = d; d = r; c = d; // Update the head head = b; // Skip to the next element // as it is already in order d = d.next; } // Case 2: b is not the head of the linked list else { // Move d before b b.next = d.next; d.next = b; a.next = d; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; } } // If b and d have some non-zero // number of nodes in between them else { // Case 3: b is the head of the linked list if (b == head) { // Swap b.next and d.next r = b.next; b.next = d.next; d.next = r; c.next = b; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; // Update the head head = b; } // Case 4: b is not the head of the linked list else { // Swap b.next and d.next r = b.next; b.next = d.next; d.next = r; c.next = b; a.next = d; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; } } } else { // Update c and skip to the next element // as it is already in order c = d; d = d.next; } } a = b; b = b.next; } return head; } // Function to print the list static void printList(Node head) { while (head != null) { Console.Write(head.data + \" \"); head = head.next; } } // Driver Code public static void Main(String[] arg) { Node head = newNode(5); head.next = newNode(4); head.next.next = newNode(3); head = selectionSort(head); printList(head); }} // This code contributed by Rajput-Ji", "e": 47387, "s": 42735, "text": null }, { "code": "<script>// Javascript implementation of the approach // Structure of a node of linked listclass Node { constructor() { this.data = 0; this.next = null; } } // Utility function to create a// new Linked List Nodefunction newNode( val){ var temp = new Node(); temp.data = val; temp.next = null; return temp;} // Function to sort a linked list using selection// sort algorithm by swapping the next pointersfunction selectionSort( head) { var a, b, c, d, r; a = b = head; // While b is not the last node while (b.next != null) { c = d = b.next; // While d is pointing to a valid node while (d != null) { if (b.data > d.data) { // If d appears immediately after b if (b.next == d) { // Case 1: b is the head of the linked list if (b == head) { // Move d before b b.next = d.next; d.next = b; // Swap b and d pointers r = b; b = d; d = r; c = d; // Update the head head = b; // Skip to the next element // as it is already in order d = d.next; } // Case 2: b is not the head of the linked list else { // Move d before b b.next = d.next; d.next = b; a.next = d; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; } } // If b and d have some non-zero // number of nodes in between them else { // Case 3: b is the head of the linked list if (b == head) { // Swap b.next and d.next r = b.next; b.next = d.next; d.next = r; c.next = b; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; // Update the head head = b; } // Case 4: b is not the head of the linked list else { // Swap b.next and d.next r = b.next; b.next = d.next; d.next = r; c.next = b; a.next = d; // Swap b and d pointers r = b; b = d; d = r; c = d; // Skip to the next element // as it is already in order d = d.next; } } } else { // Update c and skip to the next element // as it is already in order c = d; d = d.next; } } a = b; b = b.next; } return head; } // Function to print the listfunction printList( head){ while (head != null) { document.write(head.data + \" \"); head = head.next; }} // Driver Code var head = newNode(5); head.next = newNode(4); head.next.next = newNode(3); head = selectionSort(head); printList(head); // This code is contributed by jana_sayantan.</script>", "e": 51933, "s": 47387, "text": null }, { "code": null, "e": 51939, "s": 51933, "text": "3 4 5" }, { "code": null, "e": 51952, "s": 51941, "text": "andrew1234" }, { "code": null, "e": 51965, "s": 51952, "text": "rituraj_jain" }, { "code": null, "e": 51975, "s": 51965, "text": "Rajput-Ji" }, { "code": null, "e": 51990, "s": 51975, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 52009, "s": 51990, "text": "shivanisinghss2110" }, { "code": null, "e": 52023, "s": 52009, "text": "jana_sayantan" }, { "code": null, "e": 52030, "s": 52023, "text": "rrrtnx" }, { "code": null, "e": 52045, "s": 52030, "text": "selection-sort" }, { "code": null, "e": 52057, "s": 52045, "text": "Linked List" }, { "code": null, "e": 52065, "s": 52057, "text": "Sorting" }, { "code": null, "e": 52077, "s": 52065, "text": "Linked List" }, { "code": null, "e": 52085, "s": 52077, "text": "Sorting" }, { "code": null, "e": 52183, "s": 52085, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 52202, "s": 52183, "text": "LinkedList in Java" }, { "code": null, "e": 52223, "s": 52202, "text": "Linked List vs Array" }, { "code": null, "e": 52279, "s": 52223, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 52309, "s": 52279, "text": "Merge two sorted linked lists" } ]