title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Dependency tree of a Python Module
19 Aug, 2020 Generally, many Python packages are dependent on other packages but how do we know that on which packages is a module dependent? This is a python built-in module that can help us know the dependent packages but it shows all dependencies as a flat list, finding out which are the top-level packages and which packages do they depend on requires some effort. Let us see an example of how it works: Type given below command on your command prompt: $pip freeze Output: altair==4.1.0 attrs==19.3.0 docutils==0.15.2 entrypoints==0.3 Jinja2==2.11.2 jmespath==0.10.0 jsonschema==3.2.0 MarkupSafe==1.1.1 numpy==1.18.4 opencv-python==4.2.0.34 pandas==1.0.4 pyrsistent==0.16.0 python-dateutil==2.8.1 pytz==2020.1 six==1.15.0 toolz==0.10.0 urllib3==1.25.9 One easy way of doing so is to use the pipdeptree utility. The pipdeptree works on the command line and shows the installed python packages in the form of a dependency tree. This module does not come built-in with Python. To install it type the below command in the terminal. $pip install pipdeptree This will install the latest version of pipdeptree which requires at least Python 2.7. Now run this command on command prompt to get a dependency tree of all your Python modules. Command: $pipdeptree Output: $pipdeptree altair==4.1.0 - entrypoints [required: Any, installed: 0.3] - jinja2 [required: Any, installed: 2.11.2] - MarkupSafe [required: >=0.23, installed: 1.1.1] - jsonschema [required: Any, installed: 3.2.0] - attrs [required: >=17.4.0, installed: 19.3.0] - pyrsistent [required: >=0.14.0, installed: 0.16.0] - six [required: Any, installed: 1.15.0] - setuptools [required: Any, installed: 41.2.0] - six [required: >=1.11.0, installed: 1.15.0] - numpy [required: Any, installed: 1.18.4] - pandas [required: >=0.18, installed: 1.0.4] - numpy [required: >=1.13.3, installed: 1.18.4] - python-dateutil [required: >=2.6.1, installed: 2.8.1] - six [required: >=1.5, installed: 1.15.0] - pytz [required: >=2017.2, installed: 2020.1] - toolz [required: Any, installed: 0.10.0] docutils==0.15.2 jmespath==0.10.0 opencv-python==4.2.0.34 - numpy [required: >=1.17.3, installed: 1.18.4] pipdeptree==1.0.0 - pip [required: >=6.0.0, installed: 20.2.1] urllib3==1.25.9 Let’s see what happens when we use pipdeptree and freeze altogether, Command: $pipdeptree --freeze Output: altair==4.1.0 entrypoints==0.3 Jinja2==2.11.2 MarkupSafe==1.1.1 jsonschema==3.2.0 attrs==19.3.0 pyrsistent==0.16.0 six==1.15.0 setuptools==41.2.0 six==1.15.0 numpy==1.18.4 pandas==1.0.4 numpy==1.18.4 python-dateutil==2.8.1 six==1.15.0 pytz==2020.1 toolz==0.10.0 docutils==0.15.2 jmespath==0.10.0 Mako==1.1.3 MarkupSafe==1.1.1 opencv-python==4.2.0.34 numpy==1.18.4 pipdeptree==1.0.0 pip==20.2.1 scipy==1.5.2 numpy==1.18.4 urllib3==1.25.9 So, here we see that using pipdeptree along with freeze shows the output by combining the properties of both commands. So it looks like the output of pip freeze indicates which that package installed which another package, similar to pipdeptree but here indentation is used instead of a hyphen(-) to indicate tree. Commonly there occur two types of warnings while executing pipdeptree command, let us see them one by one. 1. Conflicting Dependencies: As the name suggests “conflicting dependency”, so is its relevance. Sometimes there is/are package(s) that are specified as a dependency of multiple packages with a different version, in this situation possible conflicting dependency warning arises. So, any package that’s specified as a dependency of multiple packages with a different version is considered as a possible conflicting dependency. pipdeptree by default warns about possible conflicting dependencies. Let us see one more example of pipdeptree: Command: $pipdeptree Output: Warning!!! Possibly conflicting dependencies found: * impacket==0.9.20 - ldap3 [required: ==2.5.1, installed: ?] - ldapdomaindump [required: >=0.9.0, installed: ?] ------------------------------------------------------------------------ alembic==1.0.11.dev0 attrs==18.2.0 dulwich==0.20.2 - certifi [required: Any, installed: 2018.11.29] - urllib3 [required: >=1.24.1, installed: 1.24.1] EditorConfig==0.12.1 Flask-Cors==3.0.8 - Flask [required: >=0.9, installed: 1.1.1] - Six [required: Any, installed: 1.13.0] Flask-Session==0.3.1 Flask-SocketIO==4.2.1 - Flask [required: >=0.9, installed: 1.1.1] - python-socketio [required: >=4.3.0, installed: 4.5.1] - python-engineio [required: >=3.9.0, installed: 3.12.1] - six [required: >=1.9.0, installed: 1.13.0] - six [required: >=1.9.0, installed: 1.13.0] google==2.0.1 - beautifulsoup4 [required: Any, installed: 4.8.0] html2text==2019.8.11 impacket==0.9.20 - ldap3 [required: ==2.5.1, installed: ?] - ldapdomaindump [required: >=0.9.0, installed: ?] ipython==5.8.0 - backports.shutil-get-terminal-size [required: Any, installed: 1.0.0] - pathlib2 [required: Any, installed: 2.3.5] - scandir [required: Any, installed: 1.10.0] - pexpect [required: Any, installed: 4.6.0] pip doesn’t have a true dependency resolution yet. The warning is printed to stderr (Standard error) instead of stdout (Standard Output). To completely silence this warning use the -w silence or –warn silence flag It can also be made mode strict with –warn fail in which case the command will not only print the warnings to stderr but also exit with a non-zero status code. This could be useful if you want to fit this tool into your CI pipeline. Note: The –warn flag was added in version 0.6.0. For older version, use –nowarn flag. 2. Circular Dependencies: This dependency occurs when two packages depend on each other. Suppose, package A depends upon package B and package B depends upon package A. For this let us see one more example: Command: $pipdeptree Output: Warning!!! Cyclic dependencies found: - CircularDependencyA => CircularDependencyB => CircularDependencyA - CircularDependencyB => CircularDependencyA => CircularDependencyB ------------------------------------------------------------------------ wsgiref==0.1.2 argparse==1.2.1 Note: They are also printed to stderr and can be controlled using the –warn flag. Now, we may sometimes want to know why a particular package is installed. Then we can use –reverse (or simply -r) flag for this. To find out what all packages require a particular package(s), it can be combined with –packages flag as shown in following example: Command: $pipdeptree --reverse --packages MarkupSafe,numpy Output: MarkupSafe==1.1.1 - Jinja2==2.11.2 [requires: MarkupSafe>=0.23] - altair==4.1.0 [requires: jinja2] - Mako==1.1.3 [requires: MarkupSafe>=0.9.2] numpy==1.18.4 - altair==4.1.0 [requires: numpy] - opencv-python==4.2.0.34 [requires: numpy>=1.17.3] - pandas==1.0.4 [requires: numpy>=1.13.3] - altair==4.1.0 [requires: pandas>=0.18] - scipy==1.5.2 [requires: numpy>=1.14.5] If you wish to track only the top-level packages in your requirements.txt file, it’s possible to do so using pipdeptree by grep-ing only the top-level lines from the output, Command: $pipdeptree | grep -P '^\w+' Output: Lookupy==0.1 wsgiref==0.1.2 argparse==1.2.1 psycopg2==2.5.2 Flask-Script==0.6.6 alembic==0.6.2 ipython==2.0.0 slugify==0.0.1 redis==2.9.1 There is a problem here though. The output doesn’t mention anything about Lookupy being installed as an editable package (refer to the output of pip freeze above) and information about its source is lost. To fix this, pipdeptree must be run with a -f or –freeze flag Command: $pipdeptree -f --warn silence | grep -P '^[\w0-9\-=.]+' Output: -e [email protected]:naiquevin/lookupy.git@cdbe30c160e1c29802df75e145ea4ad903c05386#egg=Lookupy-master wsgiref==0.1.2 argparse==1.2.1 psycopg2==2.5.2 Flask-Script==0.6.6 alembic==0.6.2 ipython==2.0.0 slugify==0.0.1 redis==2.9.1 Command: $ pipdeptree -f --warn silence | grep -P '^[\w0-9\-=.]+' > requirements.txt The freeze flag will also not output the hyphens for child dependencies, so you could dump the complete output of pipdeptree -f to the requirements.txt file making the file human-friendly (due to indentations) as well as pip-friendly. (Take care of duplicate dependencies though) pipdeptree uses flag –json to show output in JSON representation, as shown below: Command: $pipdeptree --json Output: [ { "package": { "key": "werkzeug", "package_name": "Werkzeug", "installed_version": "1.0.1" }, "dependencies": [] }, { "package": { "key": "urllib3", "package_name": "urllib3", "installed_version": "1.25.9" }, "dependencies": [] }, { "package": { "key": "pytz", "package_name": "pytz", "installed_version": "2020.1" }, "dependencies": [] }, { "package": { "key": "python-dateutil", "package_name": "python-dateutil", "installed_version": "2.8.1" }, "dependencies": [ { "key": "six", "package_name": "six", "installed_version": "1.15.0", "required_version": ">=1.5" } ] }, { "package": { "key": "pyrsistent", "package_name": "pyrsistent", "installed_version": "0.16.0" }, "dependencies": [ { "key": "six", "package_name": "six", "installed_version": "1.15.0", "required_version": null } ] }, { "package": { "key": "pipdeptree", "package_name": "pipdeptree", "installed_version": "1.0.0" }, "dependencies": [ { "key": "pip", "package_name": "pip", "installed_version": "20.2.1", "required_version": ">=6.0.0" } ] }, ] Note: –json will output a flat list of all packages with their immediate dependencies. To obtain nested JSON, use –-json-tree (added in version 0.11.0). Command: $pipdeptree --json-tree Output: [ { "key": "altair", "package_name": "altair", "installed_version": "4.1.0", "required_version": "4.1.0", "dependencies": [ { "key": "entrypoints", "package_name": "entrypoints", "installed_version": "0.3", "required_version": "Any", "dependencies": [] }, { "key": "jinja2", "package_name": "jinja2", "installed_version": "2.11.2", "required_version": "Any", "dependencies": [ { "key": "markupsafe", "package_name": "MarkupSafe", "installed_version": "1.1.1", "required_version": ">=0.23", "dependencies": [] } ] }, { "key": "urllib3", "package_name": "urllib3", "installed_version": "1.25.9", "required_version": "1.25.9", "dependencies": [] } ] python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Aug, 2020" }, { "code": null, "e": 157, "s": 28, "text": "Generally, many Python packages are dependent on other packages but how do we know that on which packages is a module dependent?" }, { "code": null, "e": 424, "s": 157, "text": "This is a python built-in module that can help us know the dependent packages but it shows all dependencies as a flat list, finding out which are the top-level packages and which packages do they depend on requires some effort. Let us see an example of how it works:" }, { "code": null, "e": 473, "s": 424, "text": "Type given below command on your command prompt:" }, { "code": null, "e": 486, "s": 473, "text": "$pip freeze\n" }, { "code": null, "e": 494, "s": 486, "text": "Output:" }, { "code": null, "e": 774, "s": 494, "text": "altair==4.1.0\nattrs==19.3.0\ndocutils==0.15.2\nentrypoints==0.3\nJinja2==2.11.2\njmespath==0.10.0\njsonschema==3.2.0\nMarkupSafe==1.1.1\nnumpy==1.18.4\nopencv-python==4.2.0.34\npandas==1.0.4\npyrsistent==0.16.0\npython-dateutil==2.8.1\npytz==2020.1\nsix==1.15.0\ntoolz==0.10.0\nurllib3==1.25.9\n" }, { "code": null, "e": 948, "s": 774, "text": "One easy way of doing so is to use the pipdeptree utility. The pipdeptree works on the command line and shows the installed python packages in the form of a dependency tree." }, { "code": null, "e": 1050, "s": 948, "text": "This module does not come built-in with Python. To install it type the below command in the terminal." }, { "code": null, "e": 1075, "s": 1050, "text": "$pip install pipdeptree\n" }, { "code": null, "e": 1162, "s": 1075, "text": "This will install the latest version of pipdeptree which requires at least Python 2.7." }, { "code": null, "e": 1254, "s": 1162, "text": "Now run this command on command prompt to get a dependency tree of all your Python modules." }, { "code": null, "e": 1263, "s": 1254, "text": "Command:" }, { "code": null, "e": 1276, "s": 1263, "text": "$pipdeptree\n" }, { "code": null, "e": 1284, "s": 1276, "text": "Output:" }, { "code": null, "e": 2287, "s": 1284, "text": "$pipdeptree\naltair==4.1.0\n - entrypoints [required: Any, installed: 0.3]\n - jinja2 [required: Any, installed: 2.11.2]\n - MarkupSafe [required: >=0.23, installed: 1.1.1]\n - jsonschema [required: Any, installed: 3.2.0]\n - attrs [required: >=17.4.0, installed: 19.3.0]\n - pyrsistent [required: >=0.14.0, installed: 0.16.0]\n - six [required: Any, installed: 1.15.0]\n - setuptools [required: Any, installed: 41.2.0]\n - six [required: >=1.11.0, installed: 1.15.0]\n - numpy [required: Any, installed: 1.18.4]\n - pandas [required: >=0.18, installed: 1.0.4]\n - numpy [required: >=1.13.3, installed: 1.18.4]\n - python-dateutil [required: >=2.6.1, installed: 2.8.1]\n - six [required: >=1.5, installed: 1.15.0]\n - pytz [required: >=2017.2, installed: 2020.1]\n - toolz [required: Any, installed: 0.10.0]\ndocutils==0.15.2\njmespath==0.10.0\nopencv-python==4.2.0.34\n - numpy [required: >=1.17.3, installed: 1.18.4]\npipdeptree==1.0.0\n - pip [required: >=6.0.0, installed: 20.2.1]\nurllib3==1.25.9\n" }, { "code": null, "e": 2356, "s": 2287, "text": "Let’s see what happens when we use pipdeptree and freeze altogether," }, { "code": null, "e": 2365, "s": 2356, "text": "Command:" }, { "code": null, "e": 2387, "s": 2365, "text": "$pipdeptree --freeze\n" }, { "code": null, "e": 2395, "s": 2387, "text": "Output:" }, { "code": null, "e": 2897, "s": 2395, "text": "altair==4.1.0\n entrypoints==0.3\n Jinja2==2.11.2\n MarkupSafe==1.1.1\n jsonschema==3.2.0\n attrs==19.3.0\n pyrsistent==0.16.0\n six==1.15.0\n setuptools==41.2.0\n six==1.15.0\n numpy==1.18.4\n pandas==1.0.4\n numpy==1.18.4\n python-dateutil==2.8.1\n six==1.15.0\n pytz==2020.1\n toolz==0.10.0\ndocutils==0.15.2\njmespath==0.10.0\nMako==1.1.3\n MarkupSafe==1.1.1\nopencv-python==4.2.0.34\n numpy==1.18.4\npipdeptree==1.0.0\n pip==20.2.1\nscipy==1.5.2\n numpy==1.18.4\nurllib3==1.25.9\n" }, { "code": null, "e": 3212, "s": 2897, "text": "So, here we see that using pipdeptree along with freeze shows the output by combining the properties of both commands. So it looks like the output of pip freeze indicates which that package installed which another package, similar to pipdeptree but here indentation is used instead of a hyphen(-) to indicate tree." }, { "code": null, "e": 3319, "s": 3212, "text": "Commonly there occur two types of warnings while executing pipdeptree command, let us see them one by one." }, { "code": null, "e": 3745, "s": 3319, "text": "1. Conflicting Dependencies: As the name suggests “conflicting dependency”, so is its relevance. Sometimes there is/are package(s) that are specified as a dependency of multiple packages with a different version, in this situation possible conflicting dependency warning arises. So, any package that’s specified as a dependency of multiple packages with a different version is considered as a possible conflicting dependency." }, { "code": null, "e": 3814, "s": 3745, "text": "pipdeptree by default warns about possible conflicting dependencies." }, { "code": null, "e": 3857, "s": 3814, "text": "Let us see one more example of pipdeptree:" }, { "code": null, "e": 3866, "s": 3857, "text": "Command:" }, { "code": null, "e": 3879, "s": 3866, "text": "$pipdeptree\n" }, { "code": null, "e": 3887, "s": 3879, "text": "Output:" }, { "code": null, "e": 5149, "s": 3887, "text": "Warning!!! Possibly conflicting dependencies found:\n* impacket==0.9.20\n - ldap3 [required: ==2.5.1, installed: ?]\n - ldapdomaindump [required: >=0.9.0, installed: ?]\n------------------------------------------------------------------------\nalembic==1.0.11.dev0\nattrs==18.2.0\ndulwich==0.20.2\n - certifi [required: Any, installed: 2018.11.29]\n - urllib3 [required: >=1.24.1, installed: 1.24.1]\nEditorConfig==0.12.1\nFlask-Cors==3.0.8\n - Flask [required: >=0.9, installed: 1.1.1]\n - Six [required: Any, installed: 1.13.0]\nFlask-Session==0.3.1\nFlask-SocketIO==4.2.1\n - Flask [required: >=0.9, installed: 1.1.1]\n - python-socketio [required: >=4.3.0, installed: 4.5.1]\n - python-engineio [required: >=3.9.0, installed: 3.12.1]\n - six [required: >=1.9.0, installed: 1.13.0]\n - six [required: >=1.9.0, installed: 1.13.0]\ngoogle==2.0.1\n - beautifulsoup4 [required: Any, installed: 4.8.0]\nhtml2text==2019.8.11\nimpacket==0.9.20\n - ldap3 [required: ==2.5.1, installed: ?]\n - ldapdomaindump [required: >=0.9.0, installed: ?]\nipython==5.8.0\n - backports.shutil-get-terminal-size [required: Any, installed: 1.0.0]\n - pathlib2 [required: Any, installed: 2.3.5]\n - scandir [required: Any, installed: 1.10.0]\n - pexpect [required: Any, installed: 4.6.0]\n" }, { "code": null, "e": 5597, "s": 5149, "text": " pip doesn’t have a true dependency resolution yet. The warning is printed to stderr (Standard error) instead of stdout (Standard Output). To completely silence this warning use the -w silence or –warn silence flag It can also be made mode strict with –warn fail in which case the command will not only print the warnings to stderr but also exit with a non-zero status code. This could be useful if you want to fit this tool into your CI pipeline." }, { "code": null, "e": 5683, "s": 5597, "text": "Note: The –warn flag was added in version 0.6.0. For older version, use –nowarn flag." }, { "code": null, "e": 5852, "s": 5683, "text": "2. Circular Dependencies: This dependency occurs when two packages depend on each other. Suppose, package A depends upon package B and package B depends upon package A." }, { "code": null, "e": 5890, "s": 5852, "text": "For this let us see one more example:" }, { "code": null, "e": 5899, "s": 5890, "text": "Command:" }, { "code": null, "e": 5912, "s": 5899, "text": "$pipdeptree\n" }, { "code": null, "e": 5920, "s": 5912, "text": "Output:" }, { "code": null, "e": 6199, "s": 5920, "text": "Warning!!! Cyclic dependencies found:\n- CircularDependencyA => CircularDependencyB => CircularDependencyA\n- CircularDependencyB => CircularDependencyA => CircularDependencyB\n------------------------------------------------------------------------\nwsgiref==0.1.2\nargparse==1.2.1\n" }, { "code": null, "e": 6281, "s": 6199, "text": "Note: They are also printed to stderr and can be controlled using the –warn flag." }, { "code": null, "e": 6507, "s": 6281, "text": "Now, we may sometimes want to know why a particular package is installed. Then we can use –reverse (or simply -r) flag for this. To find out what all packages require a particular package(s), it can be combined with –packages" }, { "code": null, "e": 6543, "s": 6507, "text": "flag as shown in following example:" }, { "code": null, "e": 6552, "s": 6543, "text": "Command:" }, { "code": null, "e": 6603, "s": 6552, "text": "$pipdeptree --reverse --packages MarkupSafe,numpy\n" }, { "code": null, "e": 6611, "s": 6603, "text": "Output:" }, { "code": null, "e": 6999, "s": 6611, "text": "MarkupSafe==1.1.1\n - Jinja2==2.11.2 [requires: MarkupSafe>=0.23]\n - altair==4.1.0 [requires: jinja2]\n - Mako==1.1.3 [requires: MarkupSafe>=0.9.2]\nnumpy==1.18.4\n - altair==4.1.0 [requires: numpy]\n - opencv-python==4.2.0.34 [requires: numpy>=1.17.3]\n - pandas==1.0.4 [requires: numpy>=1.13.3]\n - altair==4.1.0 [requires: pandas>=0.18]\n - scipy==1.5.2 [requires: numpy>=1.14.5]\n" }, { "code": null, "e": 7173, "s": 6999, "text": "If you wish to track only the top-level packages in your requirements.txt file, it’s possible to do so using pipdeptree by grep-ing only the top-level lines from the output," }, { "code": null, "e": 7182, "s": 7173, "text": "Command:" }, { "code": null, "e": 7212, "s": 7182, "text": "$pipdeptree | grep -P '^\\w+'\n" }, { "code": null, "e": 7220, "s": 7212, "text": "Output:" }, { "code": null, "e": 7360, "s": 7220, "text": "Lookupy==0.1\nwsgiref==0.1.2\nargparse==1.2.1\npsycopg2==2.5.2\nFlask-Script==0.6.6\nalembic==0.6.2\nipython==2.0.0\nslugify==0.0.1\nredis==2.9.1\n\n" }, { "code": null, "e": 7627, "s": 7360, "text": "There is a problem here though. The output doesn’t mention anything about Lookupy being installed as an editable package (refer to the output of pip freeze above) and information about its source is lost. To fix this, pipdeptree must be run with a -f or –freeze flag" }, { "code": null, "e": 7636, "s": 7627, "text": "Command:" }, { "code": null, "e": 7693, "s": 7636, "text": "$pipdeptree -f --warn silence | grep -P '^[\\w0-9\\-=.]+'\n" }, { "code": null, "e": 7701, "s": 7693, "text": "Output:" }, { "code": null, "e": 7931, "s": 7701, "text": "-e [email protected]:naiquevin/lookupy.git@cdbe30c160e1c29802df75e145ea4ad903c05386#egg=Lookupy-master\nwsgiref==0.1.2\nargparse==1.2.1\npsycopg2==2.5.2\nFlask-Script==0.6.6\nalembic==0.6.2\nipython==2.0.0\nslugify==0.0.1\nredis==2.9.1\n" }, { "code": null, "e": 7940, "s": 7931, "text": "Command:" }, { "code": null, "e": 8017, "s": 7940, "text": "$ pipdeptree -f --warn silence | grep -P '^[\\w0-9\\-=.]+' > requirements.txt\n" }, { "code": null, "e": 8297, "s": 8017, "text": "The freeze flag will also not output the hyphens for child dependencies, so you could dump the complete output of pipdeptree -f to the requirements.txt file making the file human-friendly (due to indentations) as well as pip-friendly. (Take care of duplicate dependencies though)" }, { "code": null, "e": 8379, "s": 8297, "text": "pipdeptree uses flag –json to show output in JSON representation, as shown below:" }, { "code": null, "e": 8388, "s": 8379, "text": "Command:" }, { "code": null, "e": 8408, "s": 8388, "text": "$pipdeptree --json\n" }, { "code": null, "e": 8416, "s": 8408, "text": "Output:" }, { "code": null, "e": 10147, "s": 8416, "text": "[\n {\n \"package\": {\n \"key\": \"werkzeug\",\n \"package_name\": \"Werkzeug\",\n \"installed_version\": \"1.0.1\"\n },\n \"dependencies\": []\n },\n {\n \"package\": {\n \"key\": \"urllib3\",\n \"package_name\": \"urllib3\",\n \"installed_version\": \"1.25.9\"\n },\n \"dependencies\": []\n },\n \n {\n \"package\": {\n \"key\": \"pytz\",\n \"package_name\": \"pytz\",\n \"installed_version\": \"2020.1\"\n },\n \"dependencies\": []\n },\n {\n \"package\": {\n \"key\": \"python-dateutil\",\n \"package_name\": \"python-dateutil\",\n \"installed_version\": \"2.8.1\"\n },\n \"dependencies\": [\n {\n \"key\": \"six\",\n \"package_name\": \"six\",\n \"installed_version\": \"1.15.0\",\n \"required_version\": \">=1.5\"\n }\n ]\n },\n {\n \"package\": {\n \"key\": \"pyrsistent\",\n \"package_name\": \"pyrsistent\",\n \"installed_version\": \"0.16.0\"\n },\n \"dependencies\": [\n {\n \"key\": \"six\",\n \"package_name\": \"six\",\n \"installed_version\": \"1.15.0\",\n \"required_version\": null\n }\n ]\n },\n {\n \"package\": {\n \"key\": \"pipdeptree\",\n \"package_name\": \"pipdeptree\",\n \"installed_version\": \"1.0.0\"\n },\n \"dependencies\": [\n {\n \"key\": \"pip\",\n \"package_name\": \"pip\",\n \"installed_version\": \"20.2.1\",\n \"required_version\": \">=6.0.0\"\n }\n ]\n },\n \n \n]\n\n\n" }, { "code": null, "e": 10300, "s": 10147, "text": "Note: –json will output a flat list of all packages with their immediate dependencies. To obtain nested JSON, use –-json-tree (added in version 0.11.0)." }, { "code": null, "e": 10309, "s": 10300, "text": "Command:" }, { "code": null, "e": 10334, "s": 10309, "text": "$pipdeptree --json-tree\n" }, { "code": null, "e": 10342, "s": 10334, "text": "Output:" }, { "code": null, "e": 11480, "s": 10342, "text": " [\n {\n \"key\": \"altair\",\n \"package_name\": \"altair\",\n \"installed_version\": \"4.1.0\",\n \"required_version\": \"4.1.0\",\n \"dependencies\": [\n {\n \"key\": \"entrypoints\",\n \"package_name\": \"entrypoints\",\n \"installed_version\": \"0.3\",\n \"required_version\": \"Any\",\n \"dependencies\": []\n },\n {\n \"key\": \"jinja2\",\n \"package_name\": \"jinja2\",\n \"installed_version\": \"2.11.2\",\n \"required_version\": \"Any\",\n \"dependencies\": [\n {\n \"key\": \"markupsafe\",\n \"package_name\": \"MarkupSafe\",\n \"installed_version\": \"1.1.1\",\n \"required_version\": \">=0.23\",\n \"dependencies\": []\n }\n ]\n },\n \n {\n \"key\": \"urllib3\",\n \"package_name\": \"urllib3\",\n \"installed_version\": \"1.25.9\",\n \"required_version\": \"1.25.9\",\n \"dependencies\": []\n }\n]\n" }, { "code": null, "e": 11495, "s": 11480, "text": "python-utility" }, { "code": null, "e": 11502, "s": 11495, "text": "Python" } ]
Python – Add Space between Potential Words
01 Sep, 2021 Given list of Strings, task is to add a space before sequence which begin with capital letters. Input : test_list = [“gfgBest”, “forGeeks”, “andComputerScienceStudents”] Output : [‘gfg Best’, ‘for Geeks’, ‘and Computer Science Students’] Explanation : Words segregated by Capitals. Input : test_list = [“ComputerScienceStudentsLoveGfg”] Output : [‘Computer Science Students Love Gfg’] Explanation : Words segregated by Capitals. Method #1 : Using loop + join() This is one of the ways in which this task can be performed. In this, we perform the task of iterating all the stings and then all the characters before adding space using loop in brute force manner. The isupper() is used to check for capital character. Python3 # Python3 code to demonstrate working of# Add Space between Potential Words# Using loop + join() # initializing listtest_list = ["gfgBest", "forGeeks", "andComputerScience"] # printing original listprint("The original list : " + str(test_list)) res = [] # loop to iterate all stringsfor ele in test_list: temp = [[]] for char in ele: # checking for upper case character if char.isupper(): temp.append([]) # appending character at latest list temp[-1].append(char) # joining lists after adding space res.append(' '.join(''.join(ele) for ele in temp)) # printing resultprint("The space added list of strings : " + str(res)) The original list : ['gfgBest', 'forGeeks', 'andComputerScience'] The space added list of strings : ['gfg Best', 'for Geeks', 'and Computer Science'] Method #2 : Using regex() + list comprehension The combination of above functions can also be used to solve this problem. In this we employ regex code to check for upper case letters and perform space addition and joining using list comprehension. Python3 # Python3 code to demonstrate working of# Add Space between Potential Words# Using regex() + list comprehensionimport re # initializing listtest_list = ["gfgBest", "forGeeks", "andComputerScience"] # printing original listprint("The original list : " + str(test_list)) # using regex() to perform taskres = [re.sub(r"(\w)([A-Z])", r"\1 \2", ele) for ele in test_list] # printing resultprint("The space added list of strings : " + str(res)) The original list : ['gfgBest', 'forGeeks', 'andComputerScience'] The space added list of strings : ['gfg Best', 'for Geeks', 'and Computer Science'] sweetyty Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Sep, 2021" }, { "code": null, "e": 124, "s": 28, "text": "Given list of Strings, task is to add a space before sequence which begin with capital letters." }, { "code": null, "e": 310, "s": 124, "text": "Input : test_list = [“gfgBest”, “forGeeks”, “andComputerScienceStudents”] Output : [‘gfg Best’, ‘for Geeks’, ‘and Computer Science Students’] Explanation : Words segregated by Capitals." }, { "code": null, "e": 459, "s": 310, "text": "Input : test_list = [“ComputerScienceStudentsLoveGfg”] Output : [‘Computer Science Students Love Gfg’] Explanation : Words segregated by Capitals. " }, { "code": null, "e": 491, "s": 459, "text": "Method #1 : Using loop + join()" }, { "code": null, "e": 746, "s": 491, "text": " This is one of the ways in which this task can be performed. In this, we perform the task of iterating all the stings and then all the characters before adding space using loop in brute force manner. The isupper() is used to check for capital character." }, { "code": null, "e": 754, "s": 746, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Add Space between Potential Words# Using loop + join() # initializing listtest_list = [\"gfgBest\", \"forGeeks\", \"andComputerScience\"] # printing original listprint(\"The original list : \" + str(test_list)) res = [] # loop to iterate all stringsfor ele in test_list: temp = [[]] for char in ele: # checking for upper case character if char.isupper(): temp.append([]) # appending character at latest list temp[-1].append(char) # joining lists after adding space res.append(' '.join(''.join(ele) for ele in temp)) # printing resultprint(\"The space added list of strings : \" + str(res))", "e": 1454, "s": 754, "text": null }, { "code": null, "e": 1604, "s": 1454, "text": "The original list : ['gfgBest', 'forGeeks', 'andComputerScience']\nThe space added list of strings : ['gfg Best', 'for Geeks', 'and Computer Science']" }, { "code": null, "e": 1651, "s": 1604, "text": "Method #2 : Using regex() + list comprehension" }, { "code": null, "e": 1852, "s": 1651, "text": "The combination of above functions can also be used to solve this problem. In this we employ regex code to check for upper case letters and perform space addition and joining using list comprehension." }, { "code": null, "e": 1860, "s": 1852, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Add Space between Potential Words# Using regex() + list comprehensionimport re # initializing listtest_list = [\"gfgBest\", \"forGeeks\", \"andComputerScience\"] # printing original listprint(\"The original list : \" + str(test_list)) # using regex() to perform taskres = [re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", ele) for ele in test_list] # printing resultprint(\"The space added list of strings : \" + str(res))", "e": 2299, "s": 1860, "text": null }, { "code": null, "e": 2449, "s": 2299, "text": "The original list : ['gfgBest', 'forGeeks', 'andComputerScience']\nThe space added list of strings : ['gfg Best', 'for Geeks', 'and Computer Science']" }, { "code": null, "e": 2458, "s": 2449, "text": "sweetyty" }, { "code": null, "e": 2479, "s": 2458, "text": "Python list-programs" }, { "code": null, "e": 2486, "s": 2479, "text": "Python" }, { "code": null, "e": 2502, "s": 2486, "text": "Python Programs" }, { "code": null, "e": 2600, "s": 2502, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2632, "s": 2600, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2659, "s": 2632, "text": "Python Classes and Objects" }, { "code": null, "e": 2680, "s": 2659, "text": "Python OOPs Concepts" }, { "code": null, "e": 2703, "s": 2680, "text": "Introduction To PYTHON" }, { "code": null, "e": 2759, "s": 2703, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2781, "s": 2759, "text": "Defaultdict in Python" }, { "code": null, "e": 2820, "s": 2781, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2858, "s": 2820, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2907, "s": 2858, "text": "Python | Convert string dictionary to dictionary" } ]
try and except in Python
To use exception handling in python, we first need to catch the all except clauses. Python provides, “try” and “except” keywords to catch exceptions. The “try” block code will be executed statement by statement. However, if an exception occurs, the remaining “try” code will not be executed and the except clause will be executed. try: some_statements_here except: exception_handling Let’s see above syntax with a very simple example − Live Demo try: print("Hello, World!") except: print("This is an error message!") Hello, World! Above is a very simple example, let’s understand the above concept with another example − Live Demo import sys List = ['abc', 0, 2, 4] for item in List: try: print("The List Item is", item) r = 1/int(item) break except: print("Oops!",sys.exc_info()[0],"occured.") print('\n') print("Next Item from the List is: ") print() print("The reciprocal of",item,"is",r) The List Item is abc Oops! <class 'ValueError'> occured. Next Item from the List is: The List Item is 0 Oops! <class 'ZeroDivisionError'> occured. Next Item from the List is: The List Item is 2 The reciprocal of 2 is 0.5 In the above program, the loops run until we get (as user input) an integer that has a valid reciprocal. The code which causes an exception to raise is placed within the try block. In case some exception occurs, it will be caught by the except block. We can test the above program with different exception errors. Below are some of the common exception errors − IOErrorRaised in case we cannot open the file. IOError Raised in case we cannot open the file. ImportErrorRaised in case module is missing. ImportError Raised in case module is missing. ValueErrorIt happened whenever we pass the argument with the correct type but an inappropriate value of a built-in operator or function. ValueError It happened whenever we pass the argument with the correct type but an inappropriate value of a built-in operator or function. KeyboardInterruptWhenever the user hits the interrupt key (generally control-c) KeyboardInterrupt Whenever the user hits the interrupt key (generally control-c) EOFErrorException raised when the built-in functions hit an end-of-file condition (EOF) without reading any data. EOFError Exception raised when the built-in functions hit an end-of-file condition (EOF) without reading any data.
[ { "code": null, "e": 1271, "s": 1187, "text": "To use exception handling in python, we first need to catch the all except clauses." }, { "code": null, "e": 1518, "s": 1271, "text": "Python provides, “try” and “except” keywords to catch exceptions. The “try” block code will be executed statement by statement. However, if an exception occurs, the remaining “try” code will not be executed and the except clause will be executed." }, { "code": null, "e": 1577, "s": 1518, "text": "try:\n some_statements_here\nexcept:\n exception_handling" }, { "code": null, "e": 1629, "s": 1577, "text": "Let’s see above syntax with a very simple example −" }, { "code": null, "e": 1640, "s": 1629, "text": " Live Demo" }, { "code": null, "e": 1717, "s": 1640, "text": "try:\n print(\"Hello, World!\")\nexcept:\n print(\"This is an error message!\")" }, { "code": null, "e": 1731, "s": 1717, "text": "Hello, World!" }, { "code": null, "e": 1821, "s": 1731, "text": "Above is a very simple example, let’s understand the above concept with another example −" }, { "code": null, "e": 1832, "s": 1821, "text": " Live Demo" }, { "code": null, "e": 2129, "s": 1832, "text": "import sys\nList = ['abc', 0, 2, 4]\nfor item in List:\n try:\n print(\"The List Item is\", item)\n r = 1/int(item)\n break\n except:\n print(\"Oops!\",sys.exc_info()[0],\"occured.\")\n print('\\n')\n print(\"Next Item from the List is: \")\n print()\nprint(\"The reciprocal of\",item,\"is\",r)" }, { "code": null, "e": 2350, "s": 2129, "text": "The List Item is abc\nOops! <class 'ValueError'> occured.\nNext Item from the List is:\nThe List Item is 0\nOops! <class 'ZeroDivisionError'> occured.\nNext Item from the List is:\nThe List Item is 2\nThe reciprocal of 2 is 0.5" }, { "code": null, "e": 2531, "s": 2350, "text": "In the above program, the loops run until we get (as user input) an integer that has a valid reciprocal. The code which causes an exception to raise is placed within the try block." }, { "code": null, "e": 2712, "s": 2531, "text": "In case some exception occurs, it will be caught by the except block. We can test the above program with different exception errors. Below are some of the common exception errors −" }, { "code": null, "e": 2759, "s": 2712, "text": "IOErrorRaised in case we cannot open the file." }, { "code": null, "e": 2767, "s": 2759, "text": "IOError" }, { "code": null, "e": 2807, "s": 2767, "text": "Raised in case we cannot open the file." }, { "code": null, "e": 2852, "s": 2807, "text": "ImportErrorRaised in case module is missing." }, { "code": null, "e": 2864, "s": 2852, "text": "ImportError" }, { "code": null, "e": 2898, "s": 2864, "text": "Raised in case module is missing." }, { "code": null, "e": 3035, "s": 2898, "text": "ValueErrorIt happened whenever we pass the argument with the correct type but an inappropriate value of a built-in operator or function." }, { "code": null, "e": 3046, "s": 3035, "text": "ValueError" }, { "code": null, "e": 3173, "s": 3046, "text": "It happened whenever we pass the argument with the correct type but an inappropriate value of a built-in operator or function." }, { "code": null, "e": 3253, "s": 3173, "text": "KeyboardInterruptWhenever the user hits the interrupt key (generally control-c)" }, { "code": null, "e": 3271, "s": 3253, "text": "KeyboardInterrupt" }, { "code": null, "e": 3334, "s": 3271, "text": "Whenever the user hits the interrupt key (generally control-c)" }, { "code": null, "e": 3448, "s": 3334, "text": "EOFErrorException raised when the built-in functions hit an end-of-file condition (EOF) without reading any data." }, { "code": null, "e": 3457, "s": 3448, "text": "EOFError" }, { "code": null, "e": 3563, "s": 3457, "text": "Exception raised when the built-in functions hit an end-of-file condition (EOF) without reading any data." } ]
Saving a Pandas Dataframe as a CSV
21 Aug, 2020 Pandas is an open source library which is built on top of NumPy library. It allows user for fast analysis, data cleaning & preparation of data efficiently. Pandas is fast and it has high-performance & productivity for users. Most of the datasets you work with are called DataFrames. DataFrames is a 2-Dimensional labeled Data Structure with index for rows and columns, where each cell is used to store a value of any type. Basically, DataFrames are Dictionary based out of NumPy Arrays. Let’s see how to save a Pandas DataFrame as a CSV file using to_csv() method. Example #1: Save csv to working directory. # importing pandas as pd import pandas as pd # list of name, degree, scorenme = ["aparna", "pankaj", "sudhir", "Geeku"]deg = ["MBA", "BCA", "M.Tech", "MBA"]scr = [90, 40, 80, 98] # dictionary of lists dict = {'name': nme, 'degree': deg, 'score': scr} df = pd.DataFrame(dict) # saving the dataframedf.to_csv('file1.csv') Output: Example #2: Saving CSV without headers and index. 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. # importing pandas as pd import pandas as pd # list of name, degree, scorenme = ["aparna", "pankaj", "sudhir", "Geeku"]deg = ["MBA", "BCA", "M.Tech", "MBA"]scr = [90, 40, 80, 98] # dictionary of lists dict = {'name': nme, 'degree': deg, 'score': scr} df = pd.DataFrame(dict) # saving the dataframedf.to_csv('file2.csv', header=False, index=False) Output: Example #3: Save csv file to a specified location. # importing pandas as pd import pandas as pd # list of name, degree, scorenme = ["aparna", "pankaj", "sudhir", "Geeku"]deg = ["MBA", "BCA", "M.Tech", "MBA"]scr = [90, 40, 80, 98] # dictionary of lists dict = {'name': nme, 'degree': deg, 'score': scr} df = pd.DataFrame(dict) # saving the dataframedf.to_csv(r'C:\Users\Admin\Desktop\file3.csv', index=False) Output: Example #4: Write a DataFrame to CSV file using tab separator. import pandas as pdimport numpy as npusers = {'Name': ['Amit', 'Cody', 'Drew'], 'Age': [20,21,25]}df = pd.DataFrame(users, columns=['Name','Age'])#create DataFrameprint("Original DataFrame:")print(df)print('Data from Users.csv:')df.to_csv('Users.csv', sep='\t', index=False,header=True)new_df = pd.read_csv('Users.csv')print(new_df) Output: Original DataFrame: Name Age 0 Amit 20 1 Cody 21 2 Drew 25 Data from Users.csv: Name\tAge 0 Amit\t20 1 Cody\t21 2 Drew\t25 gauravbabbar25 Picked Python pandas-basics Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Enumerate() in Python Rotate axis tick labels in Seaborn and Matplotlib Python Dictionary Deque in Python Stack in Python Queue in Python Defaultdict in Python Different ways to create Pandas Dataframe sum() function in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n21 Aug, 2020" }, { "code": null, "e": 278, "s": 53, "text": "Pandas is an open source library which is built on top of NumPy library. It allows user for fast analysis, data cleaning & preparation of data efficiently. Pandas is fast and it has high-performance & productivity for users." }, { "code": null, "e": 540, "s": 278, "text": "Most of the datasets you work with are called DataFrames. DataFrames is a 2-Dimensional labeled Data Structure with index for rows and columns, where each cell is used to store a value of any type. Basically, DataFrames are Dictionary based out of NumPy Arrays." }, { "code": null, "e": 618, "s": 540, "text": "Let’s see how to save a Pandas DataFrame as a CSV file using to_csv() method." }, { "code": null, "e": 661, "s": 618, "text": "Example #1: Save csv to working directory." }, { "code": "# importing pandas as pd import pandas as pd # list of name, degree, scorenme = [\"aparna\", \"pankaj\", \"sudhir\", \"Geeku\"]deg = [\"MBA\", \"BCA\", \"M.Tech\", \"MBA\"]scr = [90, 40, 80, 98] # dictionary of lists dict = {'name': nme, 'degree': deg, 'score': scr} df = pd.DataFrame(dict) # saving the dataframedf.to_csv('file1.csv')", "e": 992, "s": 661, "text": null }, { "code": null, "e": 1050, "s": 992, "text": "Output: Example #2: Saving CSV without headers and index." }, { "code": null, "e": 1059, "s": 1050, "text": "Chapters" }, { "code": null, "e": 1086, "s": 1059, "text": "descriptions off, selected" }, { "code": null, "e": 1136, "s": 1086, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1159, "s": 1136, "text": "captions off, selected" }, { "code": null, "e": 1167, "s": 1159, "text": "English" }, { "code": null, "e": 1191, "s": 1167, "text": "This is a modal window." }, { "code": null, "e": 1260, "s": 1191, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1282, "s": 1260, "text": "End of dialog window." }, { "code": "# importing pandas as pd import pandas as pd # list of name, degree, scorenme = [\"aparna\", \"pankaj\", \"sudhir\", \"Geeku\"]deg = [\"MBA\", \"BCA\", \"M.Tech\", \"MBA\"]scr = [90, 40, 80, 98] # dictionary of lists dict = {'name': nme, 'degree': deg, 'score': scr} df = pd.DataFrame(dict) # saving the dataframedf.to_csv('file2.csv', header=False, index=False)", "e": 1640, "s": 1282, "text": null }, { "code": null, "e": 1699, "s": 1640, "text": "Output: Example #3: Save csv file to a specified location." }, { "code": "# importing pandas as pd import pandas as pd # list of name, degree, scorenme = [\"aparna\", \"pankaj\", \"sudhir\", \"Geeku\"]deg = [\"MBA\", \"BCA\", \"M.Tech\", \"MBA\"]scr = [90, 40, 80, 98] # dictionary of lists dict = {'name': nme, 'degree': deg, 'score': scr} df = pd.DataFrame(dict) # saving the dataframedf.to_csv(r'C:\\Users\\Admin\\Desktop\\file3.csv', index=False)", "e": 2067, "s": 1699, "text": null }, { "code": null, "e": 2075, "s": 2067, "text": "Output:" }, { "code": null, "e": 2138, "s": 2075, "text": "Example #4: Write a DataFrame to CSV file using tab separator." }, { "code": "import pandas as pdimport numpy as npusers = {'Name': ['Amit', 'Cody', 'Drew'], 'Age': [20,21,25]}df = pd.DataFrame(users, columns=['Name','Age'])#create DataFrameprint(\"Original DataFrame:\")print(df)print('Data from Users.csv:')df.to_csv('Users.csv', sep='\\t', index=False,header=True)new_df = pd.read_csv('Users.csv')print(new_df)", "e": 2475, "s": 2138, "text": null }, { "code": null, "e": 2483, "s": 2475, "text": "Output:" }, { "code": null, "e": 2625, "s": 2483, "text": "Original DataFrame:\n Name Age\n0 Amit 20\n1 Cody 21\n2 Drew 25\nData from Users.csv:\n Name\\tAge\n0 Amit\\t20\n1 Cody\\t21\n2 Drew\\t25\n" }, { "code": null, "e": 2640, "s": 2625, "text": "gauravbabbar25" }, { "code": null, "e": 2647, "s": 2640, "text": "Picked" }, { "code": null, "e": 2668, "s": 2647, "text": "Python pandas-basics" }, { "code": null, "e": 2692, "s": 2668, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2706, "s": 2692, "text": "Python-pandas" }, { "code": null, "e": 2713, "s": 2706, "text": "Python" }, { "code": null, "e": 2811, "s": 2713, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2856, "s": 2811, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 2878, "s": 2856, "text": "Enumerate() in Python" }, { "code": null, "e": 2928, "s": 2878, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2946, "s": 2928, "text": "Python Dictionary" }, { "code": null, "e": 2962, "s": 2946, "text": "Deque in Python" }, { "code": null, "e": 2978, "s": 2962, "text": "Stack in Python" }, { "code": null, "e": 2994, "s": 2978, "text": "Queue in Python" }, { "code": null, "e": 3016, "s": 2994, "text": "Defaultdict in Python" }, { "code": null, "e": 3058, "s": 3016, "text": "Different ways to create Pandas Dataframe" } ]
Python | Check if given words appear together in a list of sentence
13 May, 2019 Given a list of sentences ‘sentence’ and a list of words ‘words’, write a Python program to find which sentence in the list of sentences consist of all words contained in ‘words’ and return them within a list. Examples: Input : sentence = ['I love tea', 'He hates tea', 'We love tea'] words = ['love', 'tea'] Output : ['I love tea', 'We love tea'] Input : sentence = ['python coder', 'geeksforgeeks', 'coder in geeksforgeeks'] words = ['coder', 'geeksforgeeks'] Output : ['coder in geeksforgeeks'] Approach #1 : Using List comprehension We first use list comprehension, to return a boolean value for each substring of the list of sentence and store it in ‘res’. Finally, return a list comprising of the desired sentences according to the boolean values in ‘res’. # Python3 program to Check if given words # appear together in a list of sentence def check(sentence, words): res = [all([k in s for k in words]) for s in sentence] return [sentence[i] for i in range(0, len(res)) if res[i]] # Driver codesentence = ['python coder', 'geeksforgeeks', 'coder in geeksforgeeks']words = ['coder', 'geeksforgeeks']print(check(sentence, words)) ['coder in geeksforgeeks'] Approach #2 : List comprehension (Alternative way) For each substring in list of sentences, it checks how many words are there in the current substring and stores it in a variable ‘k’. If the length of ‘k’ matches with length of list of words, just append it to ‘res’. # Python3 program to Check if given words # appear together in a list of sentence def check(sentence, words): res = [] for substring in sentence: k = [ w for w in words if w in substring ] if (len(k) == len(words) ): res.append(substring) return res # Driver codesentence = ['python coder', 'geeksforgeeks', 'coder in geeksforgeeks']words = ['coder', 'geeksforgeeks']print(check(sentence, words)) ['coder in geeksforgeeks'] Approach #3 : Python map() map() method applies a function on list of sentences and check if all words are contained in the list or not by splitting the list of words. It returns a boolean value for each substring of the list of sentence and store it in ‘res’. Finally, repeat the same steps as in approach #1. # Python3 program to Check if given words # appear together in a list of sentence def check(sentence, words): res = list(map(lambda x: all(map(lambda y:y in x.split(), words)), sentence)) return [sentence[i] for i in range(0, len(res)) if res[i]] # Driver codesentence = ['python coder', 'geeksforgeeks', 'coder in geeksforgeeks']words = ['coder', 'geeksforgeeks']print(check(sentence, words)) ['coder in geeksforgeeks'] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 53, "s": 25, "text": "\n13 May, 2019" }, { "code": null, "e": 263, "s": 53, "text": "Given a list of sentences ‘sentence’ and a list of words ‘words’, write a Python program to find which sentence in the list of sentences consist of all words contained in ‘words’ and return them within a list." }, { "code": null, "e": 273, "s": 263, "text": "Examples:" }, { "code": null, "e": 569, "s": 273, "text": "Input : sentence = ['I love tea', 'He hates tea', 'We love tea']\n words = ['love', 'tea']\nOutput : ['I love tea', 'We love tea']\n\nInput : sentence = ['python coder', 'geeksforgeeks', 'coder in geeksforgeeks']\n words = ['coder', 'geeksforgeeks']\nOutput : ['coder in geeksforgeeks']\n" }, { "code": null, "e": 609, "s": 569, "text": " Approach #1 : Using List comprehension" }, { "code": null, "e": 835, "s": 609, "text": "We first use list comprehension, to return a boolean value for each substring of the list of sentence and store it in ‘res’. Finally, return a list comprising of the desired sentences according to the boolean values in ‘res’." }, { "code": "# Python3 program to Check if given words # appear together in a list of sentence def check(sentence, words): res = [all([k in s for k in words]) for s in sentence] return [sentence[i] for i in range(0, len(res)) if res[i]] # Driver codesentence = ['python coder', 'geeksforgeeks', 'coder in geeksforgeeks']words = ['coder', 'geeksforgeeks']print(check(sentence, words))", "e": 1218, "s": 835, "text": null }, { "code": null, "e": 1246, "s": 1218, "text": "['coder in geeksforgeeks']\n" }, { "code": null, "e": 1298, "s": 1246, "text": " Approach #2 : List comprehension (Alternative way)" }, { "code": null, "e": 1516, "s": 1298, "text": "For each substring in list of sentences, it checks how many words are there in the current substring and stores it in a variable ‘k’. If the length of ‘k’ matches with length of list of words, just append it to ‘res’." }, { "code": "# Python3 program to Check if given words # appear together in a list of sentence def check(sentence, words): res = [] for substring in sentence: k = [ w for w in words if w in substring ] if (len(k) == len(words) ): res.append(substring) return res # Driver codesentence = ['python coder', 'geeksforgeeks', 'coder in geeksforgeeks']words = ['coder', 'geeksforgeeks']print(check(sentence, words))", "e": 1967, "s": 1516, "text": null }, { "code": null, "e": 1995, "s": 1967, "text": "['coder in geeksforgeeks']\n" }, { "code": null, "e": 2023, "s": 1995, "text": " Approach #3 : Python map()" }, { "code": null, "e": 2307, "s": 2023, "text": "map() method applies a function on list of sentences and check if all words are contained in the list or not by splitting the list of words. It returns a boolean value for each substring of the list of sentence and store it in ‘res’. Finally, repeat the same steps as in approach #1." }, { "code": "# Python3 program to Check if given words # appear together in a list of sentence def check(sentence, words): res = list(map(lambda x: all(map(lambda y:y in x.split(), words)), sentence)) return [sentence[i] for i in range(0, len(res)) if res[i]] # Driver codesentence = ['python coder', 'geeksforgeeks', 'coder in geeksforgeeks']words = ['coder', 'geeksforgeeks']print(check(sentence, words))", "e": 2754, "s": 2307, "text": null }, { "code": null, "e": 2782, "s": 2754, "text": "['coder in geeksforgeeks']\n" }, { "code": null, "e": 2803, "s": 2782, "text": "Python list-programs" }, { "code": null, "e": 2810, "s": 2803, "text": "Python" }, { "code": null, "e": 2826, "s": 2810, "text": "Python Programs" }, { "code": null, "e": 2924, "s": 2826, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2956, "s": 2924, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2983, "s": 2956, "text": "Python Classes and Objects" }, { "code": null, "e": 3004, "s": 2983, "text": "Python OOPs Concepts" }, { "code": null, "e": 3027, "s": 3004, "text": "Introduction To PYTHON" }, { "code": null, "e": 3083, "s": 3027, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3105, "s": 3083, "text": "Defaultdict in Python" }, { "code": null, "e": 3144, "s": 3105, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3182, "s": 3144, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3219, "s": 3182, "text": "Python Program for Fibonacci numbers" } ]
Functions in Rust
03 Mar, 2021 Functions are the block of reusable code that can perform similar related actions. You have already seen one of the most important functions in the language: the main function, which is the entry point of many programs. You’ve also seen the “fn” keyword, which allows you to declare new functions. Rust code uses snake case as the conventional style for function and variable names. In snake case, all letters are lowercase and underscore separate words. Syntax: fn functionname(arguments){ code } To create a function we need to use the fn keyword. The function name is written after the fn keyword Arguments are passed after function name inside parenthesis You can write function code in function block Example: We will look into a simple function in the below code Rust fn main() { greet("kushwanthreddy");} fn greet(name: &str) { println!("hello {} welcome to geeksforgeeks",name);} Output: hello kushwanthreddy welcome to geeksforgeeks In the above function declaration, we have written a greeting program that takes one argument and prints a welcome message. The parameter we have given to the greet function is a name(string datatype). We used the following approach: The main function has a greet function Greet function takes a name(string) as an argument Greet function prints the welcome message function in rust In the above example, we have used function without any arguments, arguments are the parameters that are special variables that are part of a function’s signature. Let us look into the below example which adds 2 numbers. Rust use std::io; fn main() { println!("enter a number:"); let mut stra = String::new(); io::stdin() .read_line(&mut stra) .expect("failed to read input."); println!("enter b number:"); let mut strb = String::new(); io::stdin() .read_line(&mut strb) .expect("failed to read input."); let a: i32 = stra.trim().parse().expect("invalid input"); let b: i32 = strb.trim().parse().expect("invalid input"); sum(a,b);} fn sum(x: i32, y: i32) { println!("sum = {}", x+y);} Output: enter a number: 1 enter b number: 2 sum = 3 As above greet program in the above program, sum function in this program also takes 2 arguments which are generally integers and output is the sum of the integers given in the argument. Here we will use the below approach: The program asks for input a The program asks for input b Sum program gets executed while taking a, b as arguments Sum program prints the sum of a, b function with arguments We will build a simple calculator using the function, function arguments, and conditional statements. For this we will use the below approach: The program asks for number a The program asks for number b The program asks to choose what to do with numbers whether their sum, difference, product, or reminder According to user input respective calculation is the calculator The sum function calculates the sum The sub function calculates the difference The mul function calculates the product The quo function finds out the quotient The rem function finds out the remainder For invalid argument program exits with a message “invalid” Rust use std::io;use std::process::exit; fn main() { println!("enter a number:"); let mut stra = String::new(); io::stdin() .read_line(&mut stra) .expect("failed to read input."); println!("enter b number:"); let mut strb = String::new(); io::stdin() .read_line(&mut strb) .expect("failed to read input."); let a: i32 = stra.trim().parse().expect("invalid input"); let b: i32 = strb.trim().parse().expect("invalid input"); println!("choose your calculation: \n1.sum \n2.difference \n3.product \n4.quotient \n5.remainder\n"); let mut choose = String::new(); io::stdin() .read_line(&mut choose) .expect("failed to read input."); let c: i32 = choose.trim().parse().expect("invalid input"); // Select Operation using conditionals if c==1{sum(a,b);} else if c==2{sub(a,b);} else if c==3{mul(a,b);} else if c==4{quo(a,b);} else if c==5{rem(a,b);} else{println!("Invalid argument");exit(1);}} // Sum functionfn sum(x: i32, y: i32) { println!("sum = {}", x+y);} // Difference functionfn sub(x: i32, y: i32) { println!("difference = {}", x-y);} // Product functionfn mul(x: i32, y: i32) { println!("product = {}", x*y);} // Division functionfn quo(x: i32, y: i32) { println!("quotient = {}", x/y);} // Remainder functionfn rem(x: i32, y: i32) { println!("remainder = {}", x%y);} Output: enter a number: 2 enter b number: 4 choose your calculation: 1.sum 2.difference 3.product 4.quotient 5.remainder 3 product = 8 Rust functions Rust Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Mar, 2021" }, { "code": null, "e": 483, "s": 28, "text": "Functions are the block of reusable code that can perform similar related actions. You have already seen one of the most important functions in the language: the main function, which is the entry point of many programs. You’ve also seen the “fn” keyword, which allows you to declare new functions. Rust code uses snake case as the conventional style for function and variable names. In snake case, all letters are lowercase and underscore separate words." }, { "code": null, "e": 491, "s": 483, "text": "Syntax:" }, { "code": null, "e": 528, "s": 491, "text": "fn functionname(arguments){\n code\n}" }, { "code": null, "e": 580, "s": 528, "text": "To create a function we need to use the fn keyword." }, { "code": null, "e": 630, "s": 580, "text": "The function name is written after the fn keyword" }, { "code": null, "e": 690, "s": 630, "text": "Arguments are passed after function name inside parenthesis" }, { "code": null, "e": 736, "s": 690, "text": "You can write function code in function block" }, { "code": null, "e": 745, "s": 736, "text": "Example:" }, { "code": null, "e": 799, "s": 745, "text": "We will look into a simple function in the below code" }, { "code": null, "e": 804, "s": 799, "text": "Rust" }, { "code": "fn main() { greet(\"kushwanthreddy\");} fn greet(name: &str) { println!(\"hello {} welcome to geeksforgeeks\",name);}", "e": 925, "s": 804, "text": null }, { "code": null, "e": 933, "s": 925, "text": "Output:" }, { "code": null, "e": 979, "s": 933, "text": "hello kushwanthreddy welcome to geeksforgeeks" }, { "code": null, "e": 1213, "s": 979, "text": "In the above function declaration, we have written a greeting program that takes one argument and prints a welcome message. The parameter we have given to the greet function is a name(string datatype). We used the following approach:" }, { "code": null, "e": 1252, "s": 1213, "text": "The main function has a greet function" }, { "code": null, "e": 1303, "s": 1252, "text": "Greet function takes a name(string) as an argument" }, { "code": null, "e": 1345, "s": 1303, "text": "Greet function prints the welcome message" }, { "code": null, "e": 1362, "s": 1345, "text": "function in rust" }, { "code": null, "e": 1583, "s": 1362, "text": "In the above example, we have used function without any arguments, arguments are the parameters that are special variables that are part of a function’s signature. Let us look into the below example which adds 2 numbers." }, { "code": null, "e": 1588, "s": 1583, "text": "Rust" }, { "code": "use std::io; fn main() { println!(\"enter a number:\"); let mut stra = String::new(); io::stdin() .read_line(&mut stra) .expect(\"failed to read input.\"); println!(\"enter b number:\"); let mut strb = String::new(); io::stdin() .read_line(&mut strb) .expect(\"failed to read input.\"); let a: i32 = stra.trim().parse().expect(\"invalid input\"); let b: i32 = strb.trim().parse().expect(\"invalid input\"); sum(a,b);} fn sum(x: i32, y: i32) { println!(\"sum = {}\", x+y);}", "e": 2113, "s": 1588, "text": null }, { "code": null, "e": 2121, "s": 2113, "text": "Output:" }, { "code": null, "e": 2166, "s": 2121, "text": "enter a number: 1\nenter b number: 2\n\nsum = 3" }, { "code": null, "e": 2390, "s": 2166, "text": "As above greet program in the above program, sum function in this program also takes 2 arguments which are generally integers and output is the sum of the integers given in the argument. Here we will use the below approach:" }, { "code": null, "e": 2419, "s": 2390, "text": "The program asks for input a" }, { "code": null, "e": 2448, "s": 2419, "text": "The program asks for input b" }, { "code": null, "e": 2505, "s": 2448, "text": "Sum program gets executed while taking a, b as arguments" }, { "code": null, "e": 2540, "s": 2505, "text": "Sum program prints the sum of a, b" }, { "code": null, "e": 2564, "s": 2540, "text": "function with arguments" }, { "code": null, "e": 2707, "s": 2564, "text": "We will build a simple calculator using the function, function arguments, and conditional statements. For this we will use the below approach:" }, { "code": null, "e": 2737, "s": 2707, "text": "The program asks for number a" }, { "code": null, "e": 2767, "s": 2737, "text": "The program asks for number b" }, { "code": null, "e": 2870, "s": 2767, "text": "The program asks to choose what to do with numbers whether their sum, difference, product, or reminder" }, { "code": null, "e": 2935, "s": 2870, "text": "According to user input respective calculation is the calculator" }, { "code": null, "e": 2971, "s": 2935, "text": "The sum function calculates the sum" }, { "code": null, "e": 3014, "s": 2971, "text": "The sub function calculates the difference" }, { "code": null, "e": 3054, "s": 3014, "text": "The mul function calculates the product" }, { "code": null, "e": 3094, "s": 3054, "text": "The quo function finds out the quotient" }, { "code": null, "e": 3135, "s": 3094, "text": "The rem function finds out the remainder" }, { "code": null, "e": 3195, "s": 3135, "text": "For invalid argument program exits with a message “invalid”" }, { "code": null, "e": 3200, "s": 3195, "text": "Rust" }, { "code": "use std::io;use std::process::exit; fn main() { println!(\"enter a number:\"); let mut stra = String::new(); io::stdin() .read_line(&mut stra) .expect(\"failed to read input.\"); println!(\"enter b number:\"); let mut strb = String::new(); io::stdin() .read_line(&mut strb) .expect(\"failed to read input.\"); let a: i32 = stra.trim().parse().expect(\"invalid input\"); let b: i32 = strb.trim().parse().expect(\"invalid input\"); println!(\"choose your calculation: \\n1.sum \\n2.difference \\n3.product \\n4.quotient \\n5.remainder\\n\"); let mut choose = String::new(); io::stdin() .read_line(&mut choose) .expect(\"failed to read input.\"); let c: i32 = choose.trim().parse().expect(\"invalid input\"); // Select Operation using conditionals if c==1{sum(a,b);} else if c==2{sub(a,b);} else if c==3{mul(a,b);} else if c==4{quo(a,b);} else if c==5{rem(a,b);} else{println!(\"Invalid argument\");exit(1);}} // Sum functionfn sum(x: i32, y: i32) { println!(\"sum = {}\", x+y);} // Difference functionfn sub(x: i32, y: i32) { println!(\"difference = {}\", x-y);} // Product functionfn mul(x: i32, y: i32) { println!(\"product = {}\", x*y);} // Division functionfn quo(x: i32, y: i32) { println!(\"quotient = {}\", x/y);} // Remainder functionfn rem(x: i32, y: i32) { println!(\"remainder = {}\", x%y);}", "e": 4679, "s": 3200, "text": null }, { "code": null, "e": 4687, "s": 4679, "text": "Output:" }, { "code": null, "e": 5515, "s": 4687, "text": "enter a number: \n2 \nenter b number: \n4 \nchoose your calculation: \n1.sum \n2.difference \n3.product \n4.quotient \n5.remainder \n \n3 \nproduct = 8" }, { "code": null, "e": 5530, "s": 5515, "text": "Rust functions" }, { "code": null, "e": 5535, "s": 5530, "text": "Rust" } ]
Python String Title method
02 Dec, 2020 The title() function in python is the Python String Method which is used to convert the first character in each word to Uppercase and remaining characters to Lowercase in the string and returns a new string. Syntax: str.title() parameters:str is a valid string which we need to convert. return: This function returns a string which has first letter in each word is uppercase and all remaining letters are lowercase. Python # Python title() Method Example str1 = 'geeKs foR geEks'str2 = str1.title()print 'First Output after Title() method is = ', str2 # observe the original stringprint 'Converted String is = ', str1.title()print 'Original String is = ', str1 # Performing title() function directlystr3 = 'ASIPU pawan kuMAr'.title()print 'Second Output after Title() method is = ', str3 str4 = 'stutya kUMari sHAW'.title()print 'Third Output after Title() method is = ', str4 str5 = '6041'.title()print 'Fourth Output after Title() method is = ', str5 Output: First Output after title() method is = Geeks For Geeks Converted String is = Geeks For Geeks Original String is = geeKs foR geEks Second Output after title() method is = Asipu Pawan Kumar Third Output after title() method is = Stutya Kumari Shaw Fourth Output after title() method is = 6041 preyash2047 Python-Built-in-functions Python-Library python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ?
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Dec, 2020" }, { "code": null, "e": 261, "s": 52, "text": "The title() function in python is the Python String Method which is used to convert the first character in each word to Uppercase and remaining characters to Lowercase in the string and returns a new string. " }, { "code": null, "e": 270, "s": 261, "text": "Syntax: " }, { "code": null, "e": 472, "s": 270, "text": "str.title()\nparameters:str is a valid string which we need to convert.\nreturn: This function returns a string which \nhas first letter in each word is uppercase and all \nremaining letters are lowercase." }, { "code": null, "e": 481, "s": 474, "text": "Python" }, { "code": "# Python title() Method Example str1 = 'geeKs foR geEks'str2 = str1.title()print 'First Output after Title() method is = ', str2 # observe the original stringprint 'Converted String is = ', str1.title()print 'Original String is = ', str1 # Performing title() function directlystr3 = 'ASIPU pawan kuMAr'.title()print 'Second Output after Title() method is = ', str3 str4 = 'stutya kUMari sHAW'.title()print 'Third Output after Title() method is = ', str4 str5 = '6041'.title()print 'Fourth Output after Title() method is = ', str5", "e": 1015, "s": 481, "text": null }, { "code": null, "e": 1025, "s": 1015, "text": "Output: " }, { "code": null, "e": 1322, "s": 1025, "text": "First Output after title() method is = Geeks For Geeks\nConverted String is = Geeks For Geeks\nOriginal String is = geeKs foR geEks\nSecond Output after title() method is = Asipu Pawan Kumar\nThird Output after title() method is = Stutya Kumari Shaw\nFourth Output after title() method is = 6041" }, { "code": null, "e": 1336, "s": 1324, "text": "preyash2047" }, { "code": null, "e": 1362, "s": 1336, "text": "Python-Built-in-functions" }, { "code": null, "e": 1377, "s": 1362, "text": "Python-Library" }, { "code": null, "e": 1391, "s": 1377, "text": "python-string" }, { "code": null, "e": 1398, "s": 1391, "text": "Python" }, { "code": null, "e": 1496, "s": 1398, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1524, "s": 1496, "text": "Read JSON file using Python" }, { "code": null, "e": 1574, "s": 1524, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 1596, "s": 1574, "text": "Python map() function" }, { "code": null, "e": 1640, "s": 1596, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 1658, "s": 1640, "text": "Python Dictionary" }, { "code": null, "e": 1700, "s": 1658, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1723, "s": 1700, "text": "Taking input in Python" }, { "code": null, "e": 1745, "s": 1723, "text": "Enumerate() in Python" }, { "code": null, "e": 1780, "s": 1745, "text": "Read a file line by line in Python" } ]
CSS | :target Selector
21 Dec, 2018 The target selector is used to represent a unique element (the target element) with an id matching the URL’s fragment. It can be used to style the current active target element. URLs with a # followed by an anchor name link to a certain element within a document. The element being linked to is the target element. Syntax: :target { // CSS Property } Example 1: <!DOCTYPE html><html> <head> <title>CSS | :target Selector</title> <style> /* CSS property of target selector */ :target { border: 2px solid #D4D4D4; background-color: green; color: white; padding: 10px; font-size: 20px; } </style> </head> <body style = "text-align:center"> <h2> :target selector </h2> <p> <a href="#geek"> Jump to Algorithms </a> </p> <p id="geek"> <b>Algorithms</b> </p> </body></html> Output:Before Click on the link: After Click on the link: Example 2: <!DOCTYPE html><html> <head> <title>:target Selector</title> <style> .tab div { display: none; } .tab div:target { display: block; color: white; background: green; padding: 5px; margin: 20px 5px; } </style> </head> <body style = "text-align:center"> <h2> :target selector </h2> <div class = "tab"> <a href = "#geek">Geeks Classes</a> <div id = "geek"> <h3>Welcome to Geeks Classes.</h3> <p>Hello World!</p> </div> </div> </body></html> Output:Before Click on the link: After Click on the link: Supported Browsers: The browser supported by :target Selector are listed below: Apple Safari 3.2 Google Chrome 4.0 Firefox 3.5 Opera 9.6 Internet Explorer 9.0 CSS-Selectors Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Dec, 2018" }, { "code": null, "e": 343, "s": 28, "text": "The target selector is used to represent a unique element (the target element) with an id matching the URL’s fragment. It can be used to style the current active target element. URLs with a # followed by an anchor name link to a certain element within a document. The element being linked to is the target element." }, { "code": null, "e": 351, "s": 343, "text": "Syntax:" }, { "code": null, "e": 385, "s": 351, "text": ":target {\n // CSS Property\n} \n" }, { "code": null, "e": 396, "s": 385, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS | :target Selector</title> <style> /* CSS property of target selector */ :target { border: 2px solid #D4D4D4; background-color: green; color: white; padding: 10px; font-size: 20px; } </style> </head> <body style = \"text-align:center\"> <h2> :target selector </h2> <p> <a href=\"#geek\"> Jump to Algorithms </a> </p> <p id=\"geek\"> <b>Algorithms</b> </p> </body></html> ", "e": 1091, "s": 396, "text": null }, { "code": null, "e": 1124, "s": 1091, "text": "Output:Before Click on the link:" }, { "code": null, "e": 1149, "s": 1124, "text": "After Click on the link:" }, { "code": null, "e": 1160, "s": 1149, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <title>:target Selector</title> <style> .tab div { display: none; } .tab div:target { display: block; color: white; background: green; padding: 5px; margin: 20px 5px; } </style> </head> <body style = \"text-align:center\"> <h2> :target selector </h2> <div class = \"tab\"> <a href = \"#geek\">Geeks Classes</a> <div id = \"geek\"> <h3>Welcome to Geeks Classes.</h3> <p>Hello World!</p> </div> </div> </body></html> ", "e": 1902, "s": 1160, "text": null }, { "code": null, "e": 1935, "s": 1902, "text": "Output:Before Click on the link:" }, { "code": null, "e": 1960, "s": 1935, "text": "After Click on the link:" }, { "code": null, "e": 2040, "s": 1960, "text": "Supported Browsers: The browser supported by :target Selector are listed below:" }, { "code": null, "e": 2057, "s": 2040, "text": "Apple Safari 3.2" }, { "code": null, "e": 2075, "s": 2057, "text": "Google Chrome 4.0" }, { "code": null, "e": 2087, "s": 2075, "text": "Firefox 3.5" }, { "code": null, "e": 2097, "s": 2087, "text": "Opera 9.6" }, { "code": null, "e": 2119, "s": 2097, "text": "Internet Explorer 9.0" }, { "code": null, "e": 2133, "s": 2119, "text": "CSS-Selectors" }, { "code": null, "e": 2140, "s": 2133, "text": "Picked" }, { "code": null, "e": 2144, "s": 2140, "text": "CSS" }, { "code": null, "e": 2161, "s": 2144, "text": "Web Technologies" } ]
SUBSTRING() function in MySQL
22 Sep, 2020 SUBSTRING() :function in MySQL is used to derive substring from any given string .It extracts a string with a specified length, starting from a given location in an input string. The purpose of substring is to return a specific portion of the string. Syntax : SUBSTRING(string, start, length) OR SUBSTRING(string FROM start FOR length) Parameters :This method accepts three-parameter as mentioned above and described below. string –Input String from which to extract. start –The starting position. If it is a positive number, this function extracts from the beginning of the string. If it is a negative number, this function extracts from the end of the string. length –It is optional. It identifies the number of characters to extract. If it is not given The whole string is returned from the starting position. Example-1 :Deriving substring from a given string without giving length parameter. SELECT SUBSTRING("GeeksForGeeks", 3) AS Sub_String; Output : Example-2 :Deriving substring from a given string when length parameter is given. SELECT SUBSTRING("GeeksForGeeks", 3, 8) AS Sub_String; Output : Example-3 :Deriving substring from a given string when starting position is -ve, i.e: starting from end. SELECT SUBSTRING("GeeksForGeeks", -3 ) AS Sub_String; Output : Example-4 :Extracting all substring from the text column in a Table. Table : Student_Details SELECT SUBSTRING( Student_Name, 2 ) AS Sub_String FROM Student_Details ; Output : mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Sub queries in From Clause Window functions in SQL SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter What is Temporary Table in SQL? SQL using Python SQL Query to Convert VARCHAR to INT SQL Query to Convert Rows to Columns in SQL Server SQL | DROP, TRUNCATE Introduction to NoSQL
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Sep, 2020" }, { "code": null, "e": 279, "s": 28, "text": "SUBSTRING() :function in MySQL is used to derive substring from any given string .It extracts a string with a specified length, starting from a given location in an input string. The purpose of substring is to return a specific portion of the string." }, { "code": null, "e": 288, "s": 279, "text": "Syntax :" }, { "code": null, "e": 365, "s": 288, "text": "SUBSTRING(string, start, length)\nOR\nSUBSTRING(string FROM start FOR length)\n" }, { "code": null, "e": 453, "s": 365, "text": "Parameters :This method accepts three-parameter as mentioned above and described below." }, { "code": null, "e": 497, "s": 453, "text": "string –Input String from which to extract." }, { "code": null, "e": 691, "s": 497, "text": "start –The starting position. If it is a positive number, this function extracts from the beginning of the string. If it is a negative number, this function extracts from the end of the string." }, { "code": null, "e": 842, "s": 691, "text": "length –It is optional. It identifies the number of characters to extract. If it is not given The whole string is returned from the starting position." }, { "code": null, "e": 925, "s": 842, "text": "Example-1 :Deriving substring from a given string without giving length parameter." }, { "code": null, "e": 978, "s": 925, "text": "SELECT SUBSTRING(\"GeeksForGeeks\", 3) AS Sub_String;\n" }, { "code": null, "e": 987, "s": 978, "text": "Output :" }, { "code": null, "e": 1069, "s": 987, "text": "Example-2 :Deriving substring from a given string when length parameter is given." }, { "code": null, "e": 1126, "s": 1069, "text": "SELECT SUBSTRING(\"GeeksForGeeks\", 3, 8) AS Sub_String; \n" }, { "code": null, "e": 1135, "s": 1126, "text": "Output :" }, { "code": null, "e": 1240, "s": 1135, "text": "Example-3 :Deriving substring from a given string when starting position is -ve, i.e: starting from end." }, { "code": null, "e": 1298, "s": 1240, "text": " \nSELECT SUBSTRING(\"GeeksForGeeks\", -3 ) AS Sub_String; \n" }, { "code": null, "e": 1307, "s": 1298, "text": "Output :" }, { "code": null, "e": 1376, "s": 1307, "text": "Example-4 :Extracting all substring from the text column in a Table." }, { "code": null, "e": 1400, "s": 1376, "text": "Table : Student_Details" }, { "code": null, "e": 1474, "s": 1400, "text": "SELECT SUBSTRING( Student_Name, 2 ) AS Sub_String FROM Student_Details ;\n" }, { "code": null, "e": 1483, "s": 1474, "text": "Output :" }, { "code": null, "e": 1489, "s": 1483, "text": "mysql" }, { "code": null, "e": 1493, "s": 1489, "text": "SQL" }, { "code": null, "e": 1497, "s": 1493, "text": "SQL" }, { "code": null, "e": 1595, "s": 1497, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1661, "s": 1595, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1694, "s": 1661, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 1718, "s": 1694, "text": "Window functions in SQL" }, { "code": null, "e": 1796, "s": 1718, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 1828, "s": 1796, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 1845, "s": 1828, "text": "SQL using Python" }, { "code": null, "e": 1881, "s": 1845, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 1932, "s": 1881, "text": "SQL Query to Convert Rows to Columns in SQL Server" }, { "code": null, "e": 1953, "s": 1932, "text": "SQL | DROP, TRUNCATE" } ]
Groovy - any() & every()
Method any iterates through each element of a collection checking whether a Boolean predicate is valid for at least one element. boolean any(Closure closure) boolean every(Closure closure) The condition to be met by the collection element is specified in the closure that must be some Boolean expression. The find method returns a Boolean value. Following is an example of the usage of this method − class Example { static void main(String[] args) { def lst = [1,2,3,4]; def value; // Is there any value above 2 value = lst.any{element -> element > 2} println(value); // Is there any value above 4 value = lst.any{element -> element > 4} println(value); } } When we run the above program, we will get the following result − true false Following is an example of the usage of this method of the every method − class Example { static void main(String[] args) { def lst = [1,2,3,4]; def value; // Are all value above 2 value = lst.every{element -> element > 2} println(value); // Are all value above 4 value = lst.every{element -> element > 4} println(value); def largelst = [4,5,6]; // Are all value above 2 value = largelst.every{element -> element > 2} println(value); } } When we run the above program, we will get the following result −
[ { "code": null, "e": 2501, "s": 2372, "text": "Method any iterates through each element of a collection checking whether a Boolean predicate is valid for at least one element." }, { "code": null, "e": 2563, "s": 2501, "text": "boolean any(Closure closure) \nboolean every(Closure closure)\n" }, { "code": null, "e": 2679, "s": 2563, "text": "The condition to be met by the collection element is specified in the closure that must be some Boolean expression." }, { "code": null, "e": 2720, "s": 2679, "text": "The find method returns a Boolean value." }, { "code": null, "e": 2774, "s": 2720, "text": "Following is an example of the usage of this method −" }, { "code": null, "e": 3094, "s": 2774, "text": "class Example {\n static void main(String[] args) {\n def lst = [1,2,3,4];\n def value;\n\t\t\n // Is there any value above 2\n value = lst.any{element -> element > 2}\n println(value);\n\t\t\n // Is there any value above 4\n value = lst.any{element -> element > 4}\n println(value); \n } \n}" }, { "code": null, "e": 3160, "s": 3094, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 3173, "s": 3160, "text": "true \nfalse\n" }, { "code": null, "e": 3247, "s": 3173, "text": "Following is an example of the usage of this method of the every method −" }, { "code": null, "e": 3702, "s": 3247, "text": "class Example {\n static void main(String[] args) {\n def lst = [1,2,3,4];\n def value;\n\t\t\n // Are all value above 2\n value = lst.every{element -> element > 2}\n println(value);\n\t\t\n // Are all value above 4 \n value = lst.every{element -> element > 4}\n println(value); \n def largelst = [4,5,6];\n\t\t\n // Are all value above 2\n value = largelst.every{element -> element > 2}\n println(value);\n } \n}" } ]
Java.io.BufferedOutputStream class in Java
24 Jan, 2017 Java.io.BufferedInputStream class in Java Java.io.BufferedOutputStream class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written. Fields protected byte[] buf: The internal buffer where data is stored. protected int count: The number of valid bytes in the buffer. Constructor and Description BufferedOutputStream(OutputStream out) : Creates a new buffered output stream to write data to the specified underlying output stream. BufferedOutputStream(OutputStream out, int size) : Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size. Methods: void flush() : Flushes this buffered output stream.Syntax :public void flush() throws IOException Overrides: flush in class FilterOutputStream Throws: IOException Syntax :public void flush() throws IOException Overrides: flush in class FilterOutputStream Throws: IOException void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array starting at offset off to this buffered output stream.Syntax : Parameters: b - the data. off - the start offset in the data. len - the number of bytes to write. Throws: IOException Syntax : Parameters: b - the data. off - the start offset in the data. len - the number of bytes to write. Throws: IOException void write(int b) : Writes the specified byte to this buffered output stream.Syntax : Parameters: b - the byte to be written. Throws: IOException Syntax : Parameters: b - the byte to be written. Throws: IOException Program: //Java program demonstrating BufferedOutputStream import java.io.*; class BufferedOutputStreamDemo{ public static void main(String args[])throws Exception { FileOutputStream fout = new FileOutputStream("f1.txt"); //creating bufferdOutputStream obj BufferedOutputStream bout = new BufferedOutputStream(fout); //illustrating write() method for(int i = 65; i < 75; i++) { bout.write(i); } byte b[] = { 75, 76, 77, 78, 79, 80 }; bout.write(b); //illustrating flush() method bout.flush(); //illustrating close() method bout.close(); fout.close(); }} Output : ABCDEFGHIJKLMNOP This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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. Java-I/O Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Queue Interface In Java Multidimensional Arrays in Java HashMap in Java with Examples Math pow() method in Java with Example PriorityQueue in Java Stack Class in Java List Interface in Java with Examples Initialize an ArrayList in Java ArrayList in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Jan, 2017" }, { "code": null, "e": 95, "s": 53, "text": "Java.io.BufferedInputStream class in Java" }, { "code": null, "e": 350, "s": 95, "text": "Java.io.BufferedOutputStream class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written." }, { "code": null, "e": 357, "s": 350, "text": "Fields" }, { "code": null, "e": 421, "s": 357, "text": "protected byte[] buf: The internal buffer where data is stored." }, { "code": null, "e": 483, "s": 421, "text": "protected int count: The number of valid bytes in the buffer." }, { "code": null, "e": 511, "s": 483, "text": "Constructor and Description" }, { "code": null, "e": 646, "s": 511, "text": "BufferedOutputStream(OutputStream out) : Creates a new buffered output stream to write data to the specified underlying output stream." }, { "code": null, "e": 822, "s": 646, "text": "BufferedOutputStream(OutputStream out, int size) : Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size." }, { "code": null, "e": 831, "s": 822, "text": "Methods:" }, { "code": null, "e": 1006, "s": 831, "text": "void flush() : Flushes this buffered output stream.Syntax :public void flush()\n throws IOException\nOverrides:\nflush in class FilterOutputStream\nThrows:\nIOException\n" }, { "code": null, "e": 1130, "s": 1006, "text": "Syntax :public void flush()\n throws IOException\nOverrides:\nflush in class FilterOutputStream\nThrows:\nIOException\n" }, { "code": null, "e": 1400, "s": 1130, "text": "void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array starting at offset off to this buffered output stream.Syntax :\nParameters:\nb - the data.\noff - the start offset in the data.\nlen - the number of bytes to write.\nThrows:\nIOException\n" }, { "code": null, "e": 1528, "s": 1400, "text": "Syntax :\nParameters:\nb - the data.\noff - the start offset in the data.\nlen - the number of bytes to write.\nThrows:\nIOException\n" }, { "code": null, "e": 1675, "s": 1528, "text": "void write(int b) : Writes the specified byte to this buffered output stream.Syntax :\nParameters:\nb - the byte to be written.\nThrows:\nIOException\n" }, { "code": null, "e": 1745, "s": 1675, "text": "Syntax :\nParameters:\nb - the byte to be written.\nThrows:\nIOException\n" }, { "code": null, "e": 1754, "s": 1745, "text": "Program:" }, { "code": "//Java program demonstrating BufferedOutputStream import java.io.*; class BufferedOutputStreamDemo{ public static void main(String args[])throws Exception { FileOutputStream fout = new FileOutputStream(\"f1.txt\"); //creating bufferdOutputStream obj BufferedOutputStream bout = new BufferedOutputStream(fout); //illustrating write() method for(int i = 65; i < 75; i++) { bout.write(i); } byte b[] = { 75, 76, 77, 78, 79, 80 }; bout.write(b); //illustrating flush() method bout.flush(); //illustrating close() method bout.close(); fout.close(); }}", "e": 2453, "s": 1754, "text": null }, { "code": null, "e": 2462, "s": 2453, "text": "Output :" }, { "code": null, "e": 2479, "s": 2462, "text": "ABCDEFGHIJKLMNOP" }, { "code": null, "e": 2781, "s": 2479, "text": "This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2906, "s": 2781, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2915, "s": 2906, "text": "Java-I/O" }, { "code": null, "e": 2920, "s": 2915, "text": "Java" }, { "code": null, "e": 2925, "s": 2920, "text": "Java" }, { "code": null, "e": 3023, "s": 2925, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3042, "s": 3023, "text": "Interfaces in Java" }, { "code": null, "e": 3066, "s": 3042, "text": "Queue Interface In Java" }, { "code": null, "e": 3098, "s": 3066, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3128, "s": 3098, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3167, "s": 3128, "text": "Math pow() method in Java with Example" }, { "code": null, "e": 3189, "s": 3167, "text": "PriorityQueue in Java" }, { "code": null, "e": 3209, "s": 3189, "text": "Stack Class in Java" }, { "code": null, "e": 3246, "s": 3209, "text": "List Interface in Java with Examples" }, { "code": null, "e": 3278, "s": 3246, "text": "Initialize an ArrayList in Java" } ]
PyQt5 – checkState() method for Check Box
22 Apr, 2020 There are basically two states in check box that are checked or unchecked, although using setTristate method we can add an intermediate state. checkState method is used to check the state of the check box, it returns CheckState object but when we print it output will be as follows: 0 for un-checked state 2 for checked state 1 for intermediate state Syntax : checkbox.checkState() Argument : It takes no argument. Return : It returns CheckState object Below is the implementation. # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating the check-box checkbox = QCheckBox('Geek ?', self) # setting geometry of check box checkbox.setGeometry(200, 150, 100, 40) # getting the checked state check = checkbox.checkState() # printing the state print("Before check status : ", check) # checking the check box checkbox.setChecked(True) # getting the checked state check = checkbox.checkState() # printing the state print("After check status : ", check) # exiting the program sys.exit() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Before check status : 0 After check status : 2 Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 171, "s": 28, "text": "There are basically two states in check box that are checked or unchecked, although using setTristate method we can add an intermediate state." }, { "code": null, "e": 311, "s": 171, "text": "checkState method is used to check the state of the check box, it returns CheckState object but when we print it output will be as follows:" }, { "code": null, "e": 334, "s": 311, "text": "0 for un-checked state" }, { "code": null, "e": 354, "s": 334, "text": "2 for checked state" }, { "code": null, "e": 379, "s": 354, "text": "1 for intermediate state" }, { "code": null, "e": 410, "s": 379, "text": "Syntax : checkbox.checkState()" }, { "code": null, "e": 443, "s": 410, "text": "Argument : It takes no argument." }, { "code": null, "e": 481, "s": 443, "text": "Return : It returns CheckState object" }, { "code": null, "e": 510, "s": 481, "text": "Below is the implementation." }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating the check-box checkbox = QCheckBox('Geek ?', self) # setting geometry of check box checkbox.setGeometry(200, 150, 100, 40) # getting the checked state check = checkbox.checkState() # printing the state print(\"Before check status : \", check) # checking the check box checkbox.setChecked(True) # getting the checked state check = checkbox.checkState() # printing the state print(\"After check status : \", check) # exiting the program sys.exit() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1756, "s": 510, "text": null }, { "code": null, "e": 1765, "s": 1756, "text": "Output :" }, { "code": null, "e": 1814, "s": 1765, "text": "Before check status : 0\nAfter check status : 2" }, { "code": null, "e": 1825, "s": 1814, "text": "Python-gui" }, { "code": null, "e": 1837, "s": 1825, "text": "Python-PyQt" }, { "code": null, "e": 1844, "s": 1837, "text": "Python" }, { "code": null, "e": 1942, "s": 1844, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1960, "s": 1942, "text": "Python Dictionary" }, { "code": null, "e": 2002, "s": 1960, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2037, "s": 2002, "text": "Read a file line by line in Python" }, { "code": null, "e": 2063, "s": 2037, "text": "Python String | replace()" }, { "code": null, "e": 2095, "s": 2063, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2124, "s": 2095, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2151, "s": 2124, "text": "Python Classes and Objects" }, { "code": null, "e": 2172, "s": 2151, "text": "Python OOPs Concepts" }, { "code": null, "e": 2202, "s": 2172, "text": "Iterate over a list in Python" } ]
Dividing a Large file into Separate Modules in C/C++, Java and Python
18 Jan, 2019 If you ever wanted to write a large program or software, the most common rookie mistake is to jump in directly and try to write all the necessary code into a single program and later try to debug or extend later. This kind of approach is doomed to fail and would usually require re-writing from scratch. So in order to tackle this scenario, we can try to divide the problem into multiple subproblems and then try to tackle it one by one. Doing so, not only makes our task easier but also allows us to achieve Abstraction from the high-level programmer and also promotes Re-usability of code. If you check any Open-Source project from either GitHub or GitLab or any other site of the likes, we can see how the large program is “decentralized” into many numbers of sub-modules where each individual module contributes to a specific critical function of the program and also various members of the Open Source Community come together for contributing or maintaining such file(s) or repository. Now, the big question lies in how to “break-down” not theoretically but PROGRAMMATICALLY. We will see some various types of such divisions in popular languages such as C/C++, Python & Java. Jump to C/C++ Jump to Python Jump to Java For Illustrative Purposes, Let us assume we have all the basic Linked List insertions inside one single program. Since there are many methods (functions), we cannot clutter the program by writing all the method definitions above the obligatory main function. But even if we did, there can arise the problem of ordering the methods, where one method needs to be before another and so on. So to solve this problem, we can declare all the prototypes at the beginning of the program, followed by the main method and below it, we can define them in any particular order: Program: FullLinkedList.c // Full Linked List Insertions #include <stdio.h>#include <stdlib.h> //--------------------------------// Declarations - START://-------------------------------- struct Node;struct Node* create_node(int data);void b_insert(struct Node** head, int data);void n_insert(struct Node** head, int data, int pos);void e_insert(struct Node** head, int data);void display(struct Node* temp); //--------------------------------// Declarations - END://-------------------------------- int main(){ struct Node* head = NULL; int ch, data, pos; printf("Linked List: \n"); while (1) { printf("1.Insert at Beginning"); printf("\n2.Insert at Nth Position"); printf("\n3.Insert At Ending"); printf("\n4.Display"); printf("\n0.Exit"); printf("\nEnter your choice: "); scanf("%d", &ch); switch (ch) { case 1: printf("Enter the data: "); scanf("%d", &data); b_insert(&head, data); break; case 2: printf("Enter the data: "); scanf("%d", &data); printf("Enter the Position: "); scanf("%d", &pos); n_insert(&head, data, pos); break; case 3: printf("Enter the data: "); scanf("%d", &data); e_insert(&head, data); break; case 4: display(head); break; case 0: return 0; default: printf("Wrong Choice"); } }} //--------------------------------// Definitions - START://-------------------------------- struct Node { int data; struct Node* next;}; struct Node* create_node(int data){ struct Node* temp = (struct Node*) malloc(sizeof(struct Node)); temp->data = data; temp->next = NULL; return temp;} void b_insert(struct Node** head, int data){ struct Node* new_node = create_node(data); new_node->next = *head; *head = new_node;} void n_insert(struct Node** head, int data, int pos){ if (*head == NULL) { b_insert(head, data); return; } struct Node* new_node = create_node(data); struct Node* temp = *head; for (int i = 0; i < pos - 2; ++i) temp = temp->next; new_node->next = temp->next; temp->next = new_node;} void e_insert(struct Node** head, int data){ if (*head == NULL) { b_insert(head, data); return; } struct Node* temp = *head; while (temp->next != NULL) temp = temp->next; struct Node* new_node = create_node(data); temp->next = new_node;} void display(struct Node* temp){ printf("The elements are:\n"); while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n");} //--------------------------------// Definitions - END//-------------------------------- Compiling the code: We can compile the above program by: gcc linkedlist.c -o linkedlist And it works! Underlying problems in the above code:We can already see the underlying problem(s) with the program, the code is not at all easy to work with, neither individually nor in a group. If someone would want to work with the above program, then some of the many problems faced by that person are: Need to go through the Full source file to improve or enhance some functionality.Cannot easily re-use the program as a framework for other project(s).Code is very cluttered and not at all appealing making it Very Difficult to navigate through the code. Need to go through the Full source file to improve or enhance some functionality. Cannot easily re-use the program as a framework for other project(s). Code is very cluttered and not at all appealing making it Very Difficult to navigate through the code. In case of group project or large programs, the above approach is guaranteed to enhance the overall expenditure, energy and failure rate. The Correct Approach: We see these lines starting in every C/C++ program which starts with “#include ”.This means to include all the functions declared under the “library” header (.h files) and defined possibly in library.c/cpp files. These lines are processed by pre-processor during compilation. We can manually try to create such a library for our own purpose. Important things to remember: “.h” files contain only Prototype declarations (such as Functions, Structures) and global variables.“.c/.cpp” files contain the real implementation (Definitions of declaration in the header files)When compiling all the source files together, make sure there are no multiple definitions of a same functions, variable etc. for the same project. (VERY IMPORTANT)Use static functions to restrict to the file where they are declared.Use extern keyword to use variable(s) that reference external files.If using C++, be careful about namespaces always use namespace_name::function() to avoid collision. “.h” files contain only Prototype declarations (such as Functions, Structures) and global variables. “.c/.cpp” files contain the real implementation (Definitions of declaration in the header files) When compiling all the source files together, make sure there are no multiple definitions of a same functions, variable etc. for the same project. (VERY IMPORTANT) Use static functions to restrict to the file where they are declared. Use extern keyword to use variable(s) that reference external files. If using C++, be careful about namespaces always use namespace_name::function() to avoid collision. Dividing the program into smaller codes:Looking into the above program, we can see how this large program can be divided into suitable small parts and then easily worked on. The above program has essentially 2 main functions:1) Create, Insert and store data into Nodes.2) Display the Nodes So I can divide the program accordingly such that:1) Main File -> Driver program, Nice Wrapper of the Insertion Modules and where we use the additional files.2) Insert -> The Real Implementation Lies here. Keeping the mentioned Important Points in mind, the program is divided as: linkedlist.c -> Contains Driver Programinsert.c -> Contains Code for insertion linkedlist.h -> Contains the necessary Node declarationsinsert.h -> Contains the necessary Node Insertion Declarations In each header file, we start with: #ifndef FILENAME_H #define FILENAME_H Declarations... #endif The reason we write our declarations in between the #ifndef, #define and #endif is to prevent multiple declarations of identifiers such as data types, variables etc. when the same header file is invoked in new file belonging to the same project. For this Sample Program: insert.h -> Contains Node insertion’s declaration and also declaration of Node itself. One very important thing to remember is that compiler can see declarations in header file but if you try to write code INVOLVING definition of the declaration declared elsewhere, it will lead to error since compiler compiles each .c file individually before the proceeding to the linking stage. linkedlist.h -> A helper file that contains Node and it’s Display declarations that is to be included for files that uses them. insert.c -> Include the Node declaration via #include “linkedlist.h” which contains the declaration and also all other definitions of methods declared under insert.h. linkedlist.c -> Simple Wrapper containing an infinite loop prompting user to Insert Integer data at required position(s), and also contains the method that displays the list. One final thing to keep in mind is that, mindless including files into each other may result in multiple re-definition(s) and result in error. Keeping the above in mind should you carefully divide into suitable sub programs. linkedlist.h insert.h insert.c linkedlist.c // linkedlist.h #ifndef LINKED_LIST_H#define LINKED_LIST_H struct Node { int data; struct Node* next;}; void display(struct Node* temp); #endif // insert.h #ifndef INSERT_H#define INSERT_H struct Node;struct Node* create_node(int data);void b_insert(struct Node** head, int data);void n_insert(struct Node** head, int data, int pos);void e_insert(struct Node** head, int data); #endif // insert.c #include "linkedlist.h"// "" to tell the preprocessor to look// into the current directory and// standard library files later. #include <stdlib.h> struct Node* create_node(int data){ struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = data; temp->next = NULL; return temp;} void b_insert(struct Node** head, int data){ struct Node* new_node = create_node(data); new_node->next = *head; *head = new_node;} void n_insert(struct Node** head, int data, int pos){ if (*head == NULL) { b_insert(head, data); return; } struct Node* new_node = create_node(data); struct Node* temp = *head; for (int i = 0; i < pos - 2; ++i) temp = temp->next; new_node->next = temp->next; temp->next = new_node;} void e_insert(struct Node** head, int data){ if (*head == NULL) { b_insert(head, data); return; } struct Node* temp = *head; while (temp->next != NULL) temp = temp->next; struct Node* new_node = create_node(data); temp->next = new_node;} // linkedlist.c// Driver Program #include "insert.h"#include "linkedlist.h"#include <stdio.h> void display(struct Node* temp){ printf("The elements are:\n"); while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n");} int main(){ struct Node* head = NULL; int ch, data, pos; printf("Linked List: \n"); while (1) { printf("1.Insert at Beginning"); printf("\n2.Insert at Nth Position"); printf("\n3.Insert At Ending"); printf("\n4.Display"); printf("\n0.Exit"); printf("\nEnter your choice: "); scanf("%d", &ch); switch (ch) { case 1: printf("Enter the data: "); scanf("%d", &data); b_insert(&head, data); break; case 2: printf("Enter the data: "); scanf("%d", &data); printf("Enter the Position: "); scanf("%d", &pos); n_insert(&head, data, pos); break; case 3: printf("Enter the data: "); scanf("%d", &data); e_insert(&head, data); break; case 4: display(head); break; case 0: return 0; default: printf("Wrong Choice"); } }} Finally, we save all of them and compile as follows. gcc insert.c linkedlist.c -o linkedlist Voila, it compiled successfully, let’s just do a quick sanity check, just in case: Output: It remains mostly same for C++ keeping aside usual language feature/implementation changes. Here it is not so difficult. Usually, the first thing to do is to create a virtual environment. It is a must in order to prevent breaking of a bunch of scripts due to various version dependencies and such. For eg, You might want to use Version 1.0 of some module for one project, but this latest version deprecated a feature that is available in 0.9 and you prefer to use the old version for this new project or simply you want to upgrade libraries without breaking old and existing projects. The solution is an isolated environment for each separate project/script(s). How to instatll Virtual Env:Use pip or pip3 to install virtualenv if not installed already: pip install virtualenv Setting up Isolated Environment for each project/script:Next Navigate to some directory to store your projects and then: virtualenv app_Name # (Or)virtualenv -p /path/to/py3(or)2.7 app_name # For specific interpreter dependencysource app_name/bin/activate # Start Workingdeactivate # To Quit Now you can use pip to install all the desired modules and they act as standalone to this isolated project and you don’t need to worry of system wide script breaking. eg: With virtual env and source activated, pip install pip install pandas==0.22.0 One important thing to do is to create an explicit empty file named: __init__.py This is done in order to treat the directory as containing package(s) and access sub modules inside the directory. If you don’t create such a file, Python will not explicitly look for sub-modules inside the project directory and any attempt to access them gives an error. Importing the previously saved modules into new files:Now you can start importing the previously saved modules into new files in either of the ways: import modulefrom module import submodule # (or) from module.submodule import subsubmodule1, subsubmodule2from module import * # (or) from module.submodule import * The First line allows you to access references via module.feature() or module.variable.The Second line allows you to access reference the mentioned specific module directly. eg: feature()The Third line allows you to access all references directly. eg: feature1(), feature2() etc. Example of a single cluttered File: Point.py # point.py class Point: def __init__(self): self.x = int(input ("Enter the x-coordinate: ")) self.y = int(input ("Enter the y-coordinate: ")) def distance (self, other): return ((self.x - other.x)**2 + (self.y - other.y)**2) ** 0.5 if __name__ == "__main__": print("Point 1") p1 = Point () print("\nPoint 2") p2 = Point () print( "Distance between the 2 points is {:.4f}".format (p1.distance(p2))) The weird looking ‘if __name__ == “__main__”:‘ is used to prevent execution of the code under it when imported in other modules. We can simply abstract the Point Implementation to a separate file and use a Main File to fulfill our exact requirement. Dividing the code into smaller parts:The Program can be divided such that:1) Main File -> Driver program, Create, Manipulate and use Objects.2) Point File -> All the methods we can define using a Point in the Cartesian plane. This sample program contains: Helper.py -> Which consists of a Point class that contains methods such as distance and also it consists of init method which helps auto-initialize the required x and y variables. Main.py -> Main Program that creates 2 objects and finds the distance between them. Helper.py Main.py # Helper.py class Point: def __init__(self): self.x = int(input ("Enter the x-coordinate: ")) self.y = int(input ("Enter the y-coordinate: ")) def distance (self, other): return ((self.x - other.x)**2 + (self.y - other.y)**2) ** 0.5 # Main.py from Helper import Point def main (): print("Point 1") p1 = Point () print("\nPoint 2") p2 = Point () print( "Distance between the 2 points is {:.4f}".format (p1.distance(p2))) main () Output: It is similar to Python. Navigate to the new directory to save the project files and in all of the sub program write: package app_name; On the starting line, and create a class as usual.Import the module into new java program by again writing: package app_name and simply reference that particular module.function() as they belong to same package (are stored in same directory) and java implicitly adds the following lines but if you need to import new module(s) from different package(s) then do so by: import package.*; import package.classname; import static package.*; Fully Qualified Name // eg: package.classname ob = new classname (); The 1st and 2nd ways of look similar to python’s from...import syntax but you have to explicitly state the class. In order to achieve such a not recommended but pythonic way of from...import syntax style, you have to use the 3rd method i.e., import static to achieve similar results but you have to resort to using fully qualified name to prevent collisions and clear up human misunderstandings anyway. Example of a single cluttered File: Check.java // Check.java import java.util.*; class Math { static int check(int a, int b) { return a > b ? 'a' : 'b'; }} class Main { public static void main(String args[]) { Scanner s = new Scanner(System.in); System.out.print("Enter value of a: "); int a = s.nextInt(); System.out.print("Enter value of b: "); int b = s.nextInt(); if (a == b) System.out.println("Both Values are Equal"); else System.out.printf("%c's value is Greater\n", Math.check(a, b)); }} Once again there is scope of division and abstraction. We can create Multiple standalone files that deal with the numerics and here for the example, We can divide Dividing the code into smaller parts:The Program can be divided such that:1) Main File -> Driver program, Write the Manipulative code here.2) Math File -> All the methods regarding Mathematics (here Partially implemented Check Function). The Sample Program contains: Math.java -> Which belongs to foo package and a Math class that consists of method check which can only compare 2 nos. excluding inequality. Main.java -> Main Program takes 2 numbers as input and prints the greater of 2. Math.java Main.java // Math.java package foo; public class Math { public static int check(int a, int b) { return a > b ? 'A' : 'B'; }} // Main.java// Driver Program package foo; import java.util.*; class Main { public static void main(String args[]) { Scanner s = new Scanner(System.in); System.out.print("Enter value of a: "); int a = s.nextInt(); System.out.print("Enter value of b: "); int b = s.nextInt(); if (a == b) System.out.println("Both Values are Equal"); else System.out.printf("%c's value is Greater\n", Math.check(a, b)); }} Compilation: javac -d /path file1.java file2.java Sometimes you might want to set your classpath to point to somewhere, use the: set classpath= path/to/location // (or) pass the switch for both java and javac asjavac -cp /path/to/location file.java // (or)java -classpath /path/to/location file By default it points to current directory i.e., “.” Executing the code: java packagename.Main // Here in the example it is: “java foo.Main” Output: Technical Scripter 2018 Algorithms C Language C++ Java Python Technical Scripter Java Algorithms CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Jan, 2019" }, { "code": null, "e": 267, "s": 54, "text": "If you ever wanted to write a large program or software, the most common rookie mistake is to jump in directly and try to write all the necessary code into a single program and later try to debug or extend later." }, { "code": null, "e": 358, "s": 267, "text": "This kind of approach is doomed to fail and would usually require re-writing from scratch." }, { "code": null, "e": 492, "s": 358, "text": "So in order to tackle this scenario, we can try to divide the problem into multiple subproblems and then try to tackle it one by one." }, { "code": null, "e": 646, "s": 492, "text": "Doing so, not only makes our task easier but also allows us to achieve Abstraction from the high-level programmer and also promotes Re-usability of code." }, { "code": null, "e": 1045, "s": 646, "text": "If you check any Open-Source project from either GitHub or GitLab or any other site of the likes, we can see how the large program is “decentralized” into many numbers of sub-modules where each individual module contributes to a specific critical function of the program and also various members of the Open Source Community come together for contributing or maintaining such file(s) or repository." }, { "code": null, "e": 1135, "s": 1045, "text": "Now, the big question lies in how to “break-down” not theoretically but PROGRAMMATICALLY." }, { "code": null, "e": 1235, "s": 1135, "text": "We will see some various types of such divisions in popular languages such as C/C++, Python & Java." }, { "code": null, "e": 1249, "s": 1235, "text": "Jump to C/C++" }, { "code": null, "e": 1264, "s": 1249, "text": "Jump to Python" }, { "code": null, "e": 1277, "s": 1264, "text": "Jump to Java" }, { "code": null, "e": 1304, "s": 1277, "text": "For Illustrative Purposes," }, { "code": null, "e": 1664, "s": 1304, "text": "Let us assume we have all the basic Linked List insertions inside one single program. Since there are many methods (functions), we cannot clutter the program by writing all the method definitions above the obligatory main function. But even if we did, there can arise the problem of ordering the methods, where one method needs to be before another and so on." }, { "code": null, "e": 1843, "s": 1664, "text": "So to solve this problem, we can declare all the prototypes at the beginning of the program, followed by the main method and below it, we can define them in any particular order:" }, { "code": null, "e": 1852, "s": 1843, "text": "Program:" }, { "code": null, "e": 1869, "s": 1852, "text": "FullLinkedList.c" }, { "code": "// Full Linked List Insertions #include <stdio.h>#include <stdlib.h> //--------------------------------// Declarations - START://-------------------------------- struct Node;struct Node* create_node(int data);void b_insert(struct Node** head, int data);void n_insert(struct Node** head, int data, int pos);void e_insert(struct Node** head, int data);void display(struct Node* temp); //--------------------------------// Declarations - END://-------------------------------- int main(){ struct Node* head = NULL; int ch, data, pos; printf(\"Linked List: \\n\"); while (1) { printf(\"1.Insert at Beginning\"); printf(\"\\n2.Insert at Nth Position\"); printf(\"\\n3.Insert At Ending\"); printf(\"\\n4.Display\"); printf(\"\\n0.Exit\"); printf(\"\\nEnter your choice: \"); scanf(\"%d\", &ch); switch (ch) { case 1: printf(\"Enter the data: \"); scanf(\"%d\", &data); b_insert(&head, data); break; case 2: printf(\"Enter the data: \"); scanf(\"%d\", &data); printf(\"Enter the Position: \"); scanf(\"%d\", &pos); n_insert(&head, data, pos); break; case 3: printf(\"Enter the data: \"); scanf(\"%d\", &data); e_insert(&head, data); break; case 4: display(head); break; case 0: return 0; default: printf(\"Wrong Choice\"); } }} //--------------------------------// Definitions - START://-------------------------------- struct Node { int data; struct Node* next;}; struct Node* create_node(int data){ struct Node* temp = (struct Node*) malloc(sizeof(struct Node)); temp->data = data; temp->next = NULL; return temp;} void b_insert(struct Node** head, int data){ struct Node* new_node = create_node(data); new_node->next = *head; *head = new_node;} void n_insert(struct Node** head, int data, int pos){ if (*head == NULL) { b_insert(head, data); return; } struct Node* new_node = create_node(data); struct Node* temp = *head; for (int i = 0; i < pos - 2; ++i) temp = temp->next; new_node->next = temp->next; temp->next = new_node;} void e_insert(struct Node** head, int data){ if (*head == NULL) { b_insert(head, data); return; } struct Node* temp = *head; while (temp->next != NULL) temp = temp->next; struct Node* new_node = create_node(data); temp->next = new_node;} void display(struct Node* temp){ printf(\"The elements are:\\n\"); while (temp != NULL) { printf(\"%d \", temp->data); temp = temp->next; } printf(\"\\n\");} //--------------------------------// Definitions - END//--------------------------------", "e": 4749, "s": 1869, "text": null }, { "code": null, "e": 4806, "s": 4749, "text": "Compiling the code: We can compile the above program by:" }, { "code": null, "e": 4837, "s": 4806, "text": "gcc linkedlist.c -o linkedlist" }, { "code": null, "e": 4851, "s": 4837, "text": "And it works!" }, { "code": null, "e": 5031, "s": 4851, "text": "Underlying problems in the above code:We can already see the underlying problem(s) with the program, the code is not at all easy to work with, neither individually nor in a group." }, { "code": null, "e": 5142, "s": 5031, "text": "If someone would want to work with the above program, then some of the many problems faced by that person are:" }, { "code": null, "e": 5395, "s": 5142, "text": "Need to go through the Full source file to improve or enhance some functionality.Cannot easily re-use the program as a framework for other project(s).Code is very cluttered and not at all appealing making it Very Difficult to navigate through the code." }, { "code": null, "e": 5477, "s": 5395, "text": "Need to go through the Full source file to improve or enhance some functionality." }, { "code": null, "e": 5547, "s": 5477, "text": "Cannot easily re-use the program as a framework for other project(s)." }, { "code": null, "e": 5650, "s": 5547, "text": "Code is very cluttered and not at all appealing making it Very Difficult to navigate through the code." }, { "code": null, "e": 5788, "s": 5650, "text": "In case of group project or large programs, the above approach is guaranteed to enhance the overall expenditure, energy and failure rate." }, { "code": null, "e": 5810, "s": 5788, "text": "The Correct Approach:" }, { "code": null, "e": 6023, "s": 5810, "text": "We see these lines starting in every C/C++ program which starts with “#include ”.This means to include all the functions declared under the “library” header (.h files) and defined possibly in library.c/cpp files." }, { "code": null, "e": 6086, "s": 6023, "text": "These lines are processed by pre-processor during compilation." }, { "code": null, "e": 6152, "s": 6086, "text": "We can manually try to create such a library for our own purpose." }, { "code": null, "e": 6182, "s": 6152, "text": "Important things to remember:" }, { "code": null, "e": 6778, "s": 6182, "text": "“.h” files contain only Prototype declarations (such as Functions, Structures) and global variables.“.c/.cpp” files contain the real implementation (Definitions of declaration in the header files)When compiling all the source files together, make sure there are no multiple definitions of a same functions, variable etc. for the same project. (VERY IMPORTANT)Use static functions to restrict to the file where they are declared.Use extern keyword to use variable(s) that reference external files.If using C++, be careful about namespaces always use namespace_name::function() to avoid collision." }, { "code": null, "e": 6879, "s": 6778, "text": "“.h” files contain only Prototype declarations (such as Functions, Structures) and global variables." }, { "code": null, "e": 6976, "s": 6879, "text": "“.c/.cpp” files contain the real implementation (Definitions of declaration in the header files)" }, { "code": null, "e": 7140, "s": 6976, "text": "When compiling all the source files together, make sure there are no multiple definitions of a same functions, variable etc. for the same project. (VERY IMPORTANT)" }, { "code": null, "e": 7210, "s": 7140, "text": "Use static functions to restrict to the file where they are declared." }, { "code": null, "e": 7279, "s": 7210, "text": "Use extern keyword to use variable(s) that reference external files." }, { "code": null, "e": 7379, "s": 7279, "text": "If using C++, be careful about namespaces always use namespace_name::function() to avoid collision." }, { "code": null, "e": 7553, "s": 7379, "text": "Dividing the program into smaller codes:Looking into the above program, we can see how this large program can be divided into suitable small parts and then easily worked on." }, { "code": null, "e": 7669, "s": 7553, "text": "The above program has essentially 2 main functions:1) Create, Insert and store data into Nodes.2) Display the Nodes" }, { "code": null, "e": 7875, "s": 7669, "text": "So I can divide the program accordingly such that:1) Main File -> Driver program, Nice Wrapper of the Insertion Modules and where we use the additional files.2) Insert -> The Real Implementation Lies here." }, { "code": null, "e": 7950, "s": 7875, "text": "Keeping the mentioned Important Points in mind, the program is divided as:" }, { "code": null, "e": 8029, "s": 7950, "text": "linkedlist.c -> Contains Driver Programinsert.c -> Contains Code for insertion" }, { "code": null, "e": 8148, "s": 8029, "text": "linkedlist.h -> Contains the necessary Node declarationsinsert.h -> Contains the necessary Node Insertion Declarations" }, { "code": null, "e": 8184, "s": 8148, "text": "In each header file, we start with:" }, { "code": null, "e": 8251, "s": 8184, "text": "#ifndef FILENAME_H \n#define FILENAME_H \n\nDeclarations...\n\n#endif\n" }, { "code": null, "e": 8497, "s": 8251, "text": "The reason we write our declarations in between the #ifndef, #define and #endif is to prevent multiple declarations of identifiers such as data types, variables etc. when the same header file is invoked in new file belonging to the same project." }, { "code": null, "e": 8522, "s": 8497, "text": "For this Sample Program:" }, { "code": null, "e": 8609, "s": 8522, "text": "insert.h -> Contains Node insertion’s declaration and also declaration of Node itself." }, { "code": null, "e": 8904, "s": 8609, "text": "One very important thing to remember is that compiler can see declarations in header file but if you try to write code INVOLVING definition of the declaration declared elsewhere, it will lead to error since compiler compiles each .c file individually before the proceeding to the linking stage." }, { "code": null, "e": 9032, "s": 8904, "text": "linkedlist.h -> A helper file that contains Node and it’s Display declarations that is to be included for files that uses them." }, { "code": null, "e": 9199, "s": 9032, "text": "insert.c -> Include the Node declaration via #include “linkedlist.h” which contains the declaration and also all other definitions of methods declared under insert.h." }, { "code": null, "e": 9374, "s": 9199, "text": "linkedlist.c -> Simple Wrapper containing an infinite loop prompting user to Insert Integer data at required position(s), and also contains the method that displays the list." }, { "code": null, "e": 9517, "s": 9374, "text": "One final thing to keep in mind is that, mindless including files into each other may result in multiple re-definition(s) and result in error." }, { "code": null, "e": 9599, "s": 9517, "text": "Keeping the above in mind should you carefully divide into suitable sub programs." }, { "code": null, "e": 9612, "s": 9599, "text": "linkedlist.h" }, { "code": null, "e": 9621, "s": 9612, "text": "insert.h" }, { "code": null, "e": 9630, "s": 9621, "text": "insert.c" }, { "code": null, "e": 9643, "s": 9630, "text": "linkedlist.c" }, { "code": "// linkedlist.h #ifndef LINKED_LIST_H#define LINKED_LIST_H struct Node { int data; struct Node* next;}; void display(struct Node* temp); #endif", "e": 9797, "s": 9643, "text": null }, { "code": "// insert.h #ifndef INSERT_H#define INSERT_H struct Node;struct Node* create_node(int data);void b_insert(struct Node** head, int data);void n_insert(struct Node** head, int data, int pos);void e_insert(struct Node** head, int data); #endif", "e": 10041, "s": 9797, "text": null }, { "code": "// insert.c #include \"linkedlist.h\"// \"\" to tell the preprocessor to look// into the current directory and// standard library files later. #include <stdlib.h> struct Node* create_node(int data){ struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = data; temp->next = NULL; return temp;} void b_insert(struct Node** head, int data){ struct Node* new_node = create_node(data); new_node->next = *head; *head = new_node;} void n_insert(struct Node** head, int data, int pos){ if (*head == NULL) { b_insert(head, data); return; } struct Node* new_node = create_node(data); struct Node* temp = *head; for (int i = 0; i < pos - 2; ++i) temp = temp->next; new_node->next = temp->next; temp->next = new_node;} void e_insert(struct Node** head, int data){ if (*head == NULL) { b_insert(head, data); return; } struct Node* temp = *head; while (temp->next != NULL) temp = temp->next; struct Node* new_node = create_node(data); temp->next = new_node;}", "e": 11129, "s": 10041, "text": null }, { "code": "// linkedlist.c// Driver Program #include \"insert.h\"#include \"linkedlist.h\"#include <stdio.h> void display(struct Node* temp){ printf(\"The elements are:\\n\"); while (temp != NULL) { printf(\"%d \", temp->data); temp = temp->next; } printf(\"\\n\");} int main(){ struct Node* head = NULL; int ch, data, pos; printf(\"Linked List: \\n\"); while (1) { printf(\"1.Insert at Beginning\"); printf(\"\\n2.Insert at Nth Position\"); printf(\"\\n3.Insert At Ending\"); printf(\"\\n4.Display\"); printf(\"\\n0.Exit\"); printf(\"\\nEnter your choice: \"); scanf(\"%d\", &ch); switch (ch) { case 1: printf(\"Enter the data: \"); scanf(\"%d\", &data); b_insert(&head, data); break; case 2: printf(\"Enter the data: \"); scanf(\"%d\", &data); printf(\"Enter the Position: \"); scanf(\"%d\", &pos); n_insert(&head, data, pos); break; case 3: printf(\"Enter the data: \"); scanf(\"%d\", &data); e_insert(&head, data); break; case 4: display(head); break; case 0: return 0; default: printf(\"Wrong Choice\"); } }}", "e": 12445, "s": 11129, "text": null }, { "code": null, "e": 12498, "s": 12445, "text": "Finally, we save all of them and compile as follows." }, { "code": null, "e": 12538, "s": 12498, "text": "gcc insert.c linkedlist.c -o linkedlist" }, { "code": null, "e": 12621, "s": 12538, "text": "Voila, it compiled successfully, let’s just do a quick sanity check, just in case:" }, { "code": null, "e": 12629, "s": 12621, "text": "Output:" }, { "code": null, "e": 12721, "s": 12629, "text": "It remains mostly same for C++ keeping aside usual language feature/implementation changes." }, { "code": null, "e": 13291, "s": 12721, "text": "Here it is not so difficult. Usually, the first thing to do is to create a virtual environment. It is a must in order to prevent breaking of a bunch of scripts due to various version dependencies and such. For eg, You might want to use Version 1.0 of some module for one project, but this latest version deprecated a feature that is available in 0.9 and you prefer to use the old version for this new project or simply you want to upgrade libraries without breaking old and existing projects. The solution is an isolated environment for each separate project/script(s)." }, { "code": null, "e": 13383, "s": 13291, "text": "How to instatll Virtual Env:Use pip or pip3 to install virtualenv if not installed already:" }, { "code": null, "e": 13406, "s": 13383, "text": "pip install virtualenv" }, { "code": null, "e": 13527, "s": 13406, "text": "Setting up Isolated Environment for each project/script:Next Navigate to some directory to store your projects and then:" }, { "code": null, "e": 13698, "s": 13527, "text": "virtualenv app_Name # (Or)virtualenv -p /path/to/py3(or)2.7 app_name # For specific interpreter dependencysource app_name/bin/activate # Start Workingdeactivate # To Quit" }, { "code": null, "e": 13908, "s": 13698, "text": "Now you can use pip to install all the desired modules and they act as standalone to this isolated project and you don’t need to worry of system wide script breaking. eg: With virtual env and source activated," }, { "code": null, "e": 13947, "s": 13908, "text": "pip install pip install pandas==0.22.0" }, { "code": null, "e": 14016, "s": 13947, "text": "One important thing to do is to create an explicit empty file named:" }, { "code": null, "e": 14028, "s": 14016, "text": "__init__.py" }, { "code": null, "e": 14300, "s": 14028, "text": "This is done in order to treat the directory as containing package(s) and access sub modules inside the directory. If you don’t create such a file, Python will not explicitly look for sub-modules inside the project directory and any attempt to access them gives an error." }, { "code": null, "e": 14449, "s": 14300, "text": "Importing the previously saved modules into new files:Now you can start importing the previously saved modules into new files in either of the ways:" }, { "code": null, "e": 14614, "s": 14449, "text": "import modulefrom module import submodule # (or) from module.submodule import subsubmodule1, subsubmodule2from module import * # (or) from module.submodule import *" }, { "code": null, "e": 14894, "s": 14614, "text": "The First line allows you to access references via module.feature() or module.variable.The Second line allows you to access reference the mentioned specific module directly. eg: feature()The Third line allows you to access all references directly. eg: feature1(), feature2() etc." }, { "code": null, "e": 14930, "s": 14894, "text": "Example of a single cluttered File:" }, { "code": null, "e": 14939, "s": 14930, "text": "Point.py" }, { "code": "# point.py class Point: def __init__(self): self.x = int(input (\"Enter the x-coordinate: \")) self.y = int(input (\"Enter the y-coordinate: \")) def distance (self, other): return ((self.x - other.x)**2 + (self.y - other.y)**2) ** 0.5 if __name__ == \"__main__\": print(\"Point 1\") p1 = Point () print(\"\\nPoint 2\") p2 = Point () print( \"Distance between the 2 points is {:.4f}\".format (p1.distance(p2)))", "e": 15393, "s": 14939, "text": null }, { "code": null, "e": 15522, "s": 15393, "text": "The weird looking ‘if __name__ == “__main__”:‘ is used to prevent execution of the code under it when imported in other modules." }, { "code": null, "e": 15643, "s": 15522, "text": "We can simply abstract the Point Implementation to a separate file and use a Main File to fulfill our exact requirement." }, { "code": null, "e": 15869, "s": 15643, "text": "Dividing the code into smaller parts:The Program can be divided such that:1) Main File -> Driver program, Create, Manipulate and use Objects.2) Point File -> All the methods we can define using a Point in the Cartesian plane." }, { "code": null, "e": 15899, "s": 15869, "text": "This sample program contains:" }, { "code": null, "e": 16079, "s": 15899, "text": "Helper.py -> Which consists of a Point class that contains methods such as distance and also it consists of init method which helps auto-initialize the required x and y variables." }, { "code": null, "e": 16163, "s": 16079, "text": "Main.py -> Main Program that creates 2 objects and finds the distance between them." }, { "code": null, "e": 16173, "s": 16163, "text": "Helper.py" }, { "code": null, "e": 16181, "s": 16173, "text": "Main.py" }, { "code": "# Helper.py class Point: def __init__(self): self.x = int(input (\"Enter the x-coordinate: \")) self.y = int(input (\"Enter the y-coordinate: \")) def distance (self, other): return ((self.x - other.x)**2 + (self.y - other.y)**2) ** 0.5 ", "e": 16447, "s": 16181, "text": null }, { "code": "# Main.py from Helper import Point def main (): print(\"Point 1\") p1 = Point () print(\"\\nPoint 2\") p2 = Point () print( \"Distance between the 2 points is {:.4f}\".format (p1.distance(p2))) main ()", "e": 16665, "s": 16447, "text": null }, { "code": null, "e": 16673, "s": 16665, "text": "Output:" }, { "code": null, "e": 16791, "s": 16673, "text": "It is similar to Python. Navigate to the new directory to save the project files and in all of the sub program write:" }, { "code": null, "e": 16809, "s": 16791, "text": "package app_name;" }, { "code": null, "e": 17177, "s": 16809, "text": "On the starting line, and create a class as usual.Import the module into new java program by again writing: package app_name and simply reference that particular module.function() as they belong to same package (are stored in same directory) and java implicitly adds the following lines but if you need to import new module(s) from different package(s) then do so by:" }, { "code": null, "e": 17325, "s": 17177, "text": "import package.*; \nimport package.classname; \nimport static package.*;\nFully Qualified Name \n// eg: package.classname ob = new classname ();\n" }, { "code": null, "e": 17728, "s": 17325, "text": "The 1st and 2nd ways of look similar to python’s from...import syntax but you have to explicitly state the class. In order to achieve such a not recommended but pythonic way of from...import syntax style, you have to use the 3rd method i.e., import static to achieve similar results but you have to resort to using fully qualified name to prevent collisions and clear up human misunderstandings anyway." }, { "code": null, "e": 17764, "s": 17728, "text": "Example of a single cluttered File:" }, { "code": null, "e": 17775, "s": 17764, "text": "Check.java" }, { "code": "// Check.java import java.util.*; class Math { static int check(int a, int b) { return a > b ? 'a' : 'b'; }} class Main { public static void main(String args[]) { Scanner s = new Scanner(System.in); System.out.print(\"Enter value of a: \"); int a = s.nextInt(); System.out.print(\"Enter value of b: \"); int b = s.nextInt(); if (a == b) System.out.println(\"Both Values are Equal\"); else System.out.printf(\"%c's value is Greater\\n\", Math.check(a, b)); }}", "e": 18361, "s": 17775, "text": null }, { "code": null, "e": 18524, "s": 18361, "text": "Once again there is scope of division and abstraction. We can create Multiple standalone files that deal with the numerics and here for the example, We can divide" }, { "code": null, "e": 18762, "s": 18524, "text": "Dividing the code into smaller parts:The Program can be divided such that:1) Main File -> Driver program, Write the Manipulative code here.2) Math File -> All the methods regarding Mathematics (here Partially implemented Check Function)." }, { "code": null, "e": 18791, "s": 18762, "text": "The Sample Program contains:" }, { "code": null, "e": 18932, "s": 18791, "text": "Math.java -> Which belongs to foo package and a Math class that consists of method check which can only compare 2 nos. excluding inequality." }, { "code": null, "e": 19012, "s": 18932, "text": "Main.java -> Main Program takes 2 numbers as input and prints the greater of 2." }, { "code": null, "e": 19022, "s": 19012, "text": "Math.java" }, { "code": null, "e": 19032, "s": 19022, "text": "Main.java" }, { "code": "// Math.java package foo; public class Math { public static int check(int a, int b) { return a > b ? 'A' : 'B'; }}", "e": 19165, "s": 19032, "text": null }, { "code": "// Main.java// Driver Program package foo; import java.util.*; class Main { public static void main(String args[]) { Scanner s = new Scanner(System.in); System.out.print(\"Enter value of a: \"); int a = s.nextInt(); System.out.print(\"Enter value of b: \"); int b = s.nextInt(); if (a == b) System.out.println(\"Both Values are Equal\"); else System.out.printf(\"%c's value is Greater\\n\", Math.check(a, b)); }}", "e": 19689, "s": 19165, "text": null }, { "code": null, "e": 19702, "s": 19689, "text": "Compilation:" }, { "code": null, "e": 19740, "s": 19702, "text": "javac -d /path file1.java file2.java " }, { "code": null, "e": 19819, "s": 19740, "text": "Sometimes you might want to set your classpath to point to somewhere, use the:" }, { "code": null, "e": 19851, "s": 19819, "text": "set classpath= path/to/location" }, { "code": null, "e": 19939, "s": 19851, "text": "// (or) pass the switch for both java and javac asjavac -cp /path/to/location file.java" }, { "code": null, "e": 19985, "s": 19939, "text": "// (or)java -classpath /path/to/location file" }, { "code": null, "e": 20037, "s": 19985, "text": "By default it points to current directory i.e., “.”" }, { "code": null, "e": 20057, "s": 20037, "text": "Executing the code:" }, { "code": null, "e": 20125, "s": 20057, "text": "java packagename.Main // Here in the example it is: “java foo.Main”" }, { "code": null, "e": 20133, "s": 20125, "text": "Output:" }, { "code": null, "e": 20157, "s": 20133, "text": "Technical Scripter 2018" }, { "code": null, "e": 20168, "s": 20157, "text": "Algorithms" }, { "code": null, "e": 20179, "s": 20168, "text": "C Language" }, { "code": null, "e": 20183, "s": 20179, "text": "C++" }, { "code": null, "e": 20188, "s": 20183, "text": "Java" }, { "code": null, "e": 20195, "s": 20188, "text": "Python" }, { "code": null, "e": 20214, "s": 20195, "text": "Technical Scripter" }, { "code": null, "e": 20219, "s": 20214, "text": "Java" }, { "code": null, "e": 20230, "s": 20219, "text": "Algorithms" }, { "code": null, "e": 20234, "s": 20230, "text": "CPP" } ]
How to verify Pyspark dataframe column type ?
23 May, 2021 While working with a big Dataframe, Dataframe consists of any number of columns that are having different datatypes. For pre-processing the data to apply operations on it, we have to know the dimensions of the Dataframe and datatypes of the columns which are present in the Dataframe. In this article, we are going to know how to verify the column type of the Dataframe. For verifying the column type we are using dtypes function. The dtypes function is used to return the list of tuples that contain the Name of the column and column type. Syntax: df.dtypes() where, df is the Dataframe At first, we will create a dataframe and then see some examples and implementation. Python # importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("Product_details.com") \ .getOrCreate() return spk def create_df(spark,data,schema): df1 = spark.createDataFrame(data,schema) return df1 if __name__ == "__main__": # calling function to create SparkSession spark = create_session() input_data = [("Mobile",112345,4.0,12499), ("LED TV",114567,4.2,49999), ("Refrigerator",123543,4.4,13899), ("Washing Machine",113465,3.9,6999), ("T-shirt",124378,4.1,1999), ("Jeans",126754,3.7,3999), ("Running Shoes",134565,4.7,1499), ("Face Mask",145234,4.6,999)] schema = ["Name","ID","Rating","Price"] # calling function to create dataframe df = create_df(spark,input_data,schema) # visualizing the dataframe df.show() Output: Example 1: Verify the column type of the Dataframe using dtypes() function In the below example code, we have created the Dataframe then for getting the column types of all the columns present in the Dataframe we have used dtypes function by writing df.dtypes using with f string while finding the datatypes of all the columns we have printed also. This gives a list of tuples that contains the name and datatype of the columns. Python # finding data type of the all the # column using dtype function and # printingprint(f'Data types of all the columns is : {df.dtypes}') # visualizing the dataframedf.show() Output: Example 2: Verify the specific column datatype of the Dataframe In the below code after creating the Dataframe we are finding the Datatype of the particular column using dtypes() function by writing dict(df.dtypes)[‘Rating’], here we are using dict because as we see in the above example df.dtypes return the list of tuples that contains the name and datatype of the column. So using dict we are typecasting tuple into the dictionary. As we know in the dictionary the data is stored in key and value pair, while writing dict(df.dtypes)[‘Rating’] we are giving the key i.e, ‘Rating’ and extracting its value of that is double, which is the datatype of the column. So in this way, we can find out the datatype of column type while passing the specific name of the column. Python # finding data type of the Rating # column using dtype functiondata_type = dict(df.dtypes)['Rating'] # printingprint(f'Data type of Rating is : {data_type}') # visualizing the dataframedf.show() Output: Example 3: Verify the column type of the Dataframe using for loop After creating the Dataframe, for finding the datatypes of the column with column name we are using df.dtypes which gives us the list of tuples. While iterating we are getting the column name and column type as a tuple then printing the name of the column and column type using print(col[0],”,”,col[1]). In this way, we are getting every column name and column type using by iterating. Python print("Datatype of the columns with column names are:") # finding datatype of all column with# column name using for loopfor col in df.dtypes: # printing the column and datatype # of that column print(col[0],",",col[1]) # visualizing the dataframedf.show() Output: Example 4: Verify the column type of the Dataframe using schema After creating the Dataframe for verifying the column type we are using printSchema() function by writing df.printSchema() through this function schema of the Dataframe is printed which contains the datatype of each and every column present in Dataframe. So, using printSchema() function also we can easily verify the column type of the PySpark Dataframe. Python # printing the schema of the Dataframe# using printscheam functiondf.printSchema() # visualizing the dataframedf.show() Output: Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2021" }, { "code": null, "e": 313, "s": 28, "text": "While working with a big Dataframe, Dataframe consists of any number of columns that are having different datatypes. For pre-processing the data to apply operations on it, we have to know the dimensions of the Dataframe and datatypes of the columns which are present in the Dataframe." }, { "code": null, "e": 569, "s": 313, "text": "In this article, we are going to know how to verify the column type of the Dataframe. For verifying the column type we are using dtypes function. The dtypes function is used to return the list of tuples that contain the Name of the column and column type." }, { "code": null, "e": 589, "s": 569, "text": "Syntax: df.dtypes()" }, { "code": null, "e": 616, "s": 589, "text": "where, df is the Dataframe" }, { "code": null, "e": 701, "s": 616, "text": "At first, we will create a dataframe and then see some examples and implementation. " }, { "code": null, "e": 708, "s": 701, "text": "Python" }, { "code": "# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"Product_details.com\") \\ .getOrCreate() return spk def create_df(spark,data,schema): df1 = spark.createDataFrame(data,schema) return df1 if __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() input_data = [(\"Mobile\",112345,4.0,12499), (\"LED TV\",114567,4.2,49999), (\"Refrigerator\",123543,4.4,13899), (\"Washing Machine\",113465,3.9,6999), (\"T-shirt\",124378,4.1,1999), (\"Jeans\",126754,3.7,3999), (\"Running Shoes\",134565,4.7,1499), (\"Face Mask\",145234,4.6,999)] schema = [\"Name\",\"ID\",\"Rating\",\"Price\"] # calling function to create dataframe df = create_df(spark,input_data,schema) # visualizing the dataframe df.show()", "e": 1654, "s": 708, "text": null }, { "code": null, "e": 1662, "s": 1654, "text": "Output:" }, { "code": null, "e": 1737, "s": 1662, "text": "Example 1: Verify the column type of the Dataframe using dtypes() function" }, { "code": null, "e": 2091, "s": 1737, "text": "In the below example code, we have created the Dataframe then for getting the column types of all the columns present in the Dataframe we have used dtypes function by writing df.dtypes using with f string while finding the datatypes of all the columns we have printed also. This gives a list of tuples that contains the name and datatype of the columns." }, { "code": null, "e": 2098, "s": 2091, "text": "Python" }, { "code": "# finding data type of the all the # column using dtype function and # printingprint(f'Data types of all the columns is : {df.dtypes}') # visualizing the dataframedf.show()", "e": 2272, "s": 2098, "text": null }, { "code": null, "e": 2280, "s": 2272, "text": "Output:" }, { "code": null, "e": 2344, "s": 2280, "text": "Example 2: Verify the specific column datatype of the Dataframe" }, { "code": null, "e": 2715, "s": 2344, "text": "In the below code after creating the Dataframe we are finding the Datatype of the particular column using dtypes() function by writing dict(df.dtypes)[‘Rating’], here we are using dict because as we see in the above example df.dtypes return the list of tuples that contains the name and datatype of the column. So using dict we are typecasting tuple into the dictionary." }, { "code": null, "e": 3050, "s": 2715, "text": "As we know in the dictionary the data is stored in key and value pair, while writing dict(df.dtypes)[‘Rating’] we are giving the key i.e, ‘Rating’ and extracting its value of that is double, which is the datatype of the column. So in this way, we can find out the datatype of column type while passing the specific name of the column." }, { "code": null, "e": 3057, "s": 3050, "text": "Python" }, { "code": "# finding data type of the Rating # column using dtype functiondata_type = dict(df.dtypes)['Rating'] # printingprint(f'Data type of Rating is : {data_type}') # visualizing the dataframedf.show()", "e": 3254, "s": 3057, "text": null }, { "code": null, "e": 3262, "s": 3254, "text": "Output:" }, { "code": null, "e": 3328, "s": 3262, "text": "Example 3: Verify the column type of the Dataframe using for loop" }, { "code": null, "e": 3474, "s": 3328, "text": "After creating the Dataframe, for finding the datatypes of the column with column name we are using df.dtypes which gives us the list of tuples. " }, { "code": null, "e": 3715, "s": 3474, "text": "While iterating we are getting the column name and column type as a tuple then printing the name of the column and column type using print(col[0],”,”,col[1]). In this way, we are getting every column name and column type using by iterating." }, { "code": null, "e": 3722, "s": 3715, "text": "Python" }, { "code": "print(\"Datatype of the columns with column names are:\") # finding datatype of all column with# column name using for loopfor col in df.dtypes: # printing the column and datatype # of that column print(col[0],\",\",col[1]) # visualizing the dataframedf.show()", "e": 3989, "s": 3722, "text": null }, { "code": null, "e": 3997, "s": 3989, "text": "Output:" }, { "code": null, "e": 4061, "s": 3997, "text": "Example 4: Verify the column type of the Dataframe using schema" }, { "code": null, "e": 4418, "s": 4061, "text": "After creating the Dataframe for verifying the column type we are using printSchema() function by writing df.printSchema() through this function schema of the Dataframe is printed which contains the datatype of each and every column present in Dataframe. So, using printSchema() function also we can easily verify the column type of the PySpark Dataframe. " }, { "code": null, "e": 4425, "s": 4418, "text": "Python" }, { "code": "# printing the schema of the Dataframe# using printscheam functiondf.printSchema() # visualizing the dataframedf.show()", "e": 4546, "s": 4425, "text": null }, { "code": null, "e": 4554, "s": 4546, "text": "Output:" }, { "code": null, "e": 4561, "s": 4554, "text": "Picked" }, { "code": null, "e": 4576, "s": 4561, "text": "Python-Pyspark" }, { "code": null, "e": 4583, "s": 4576, "text": "Python" } ]
Storage Classes in C++
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C++ Program. These specifiers precede the type that they modify. There are following storage classes, which can be used in a C++ Program auto register static extern mutable The auto storage class is the default storage class for all local variables. { int mount; auto int month; } The example above defines two variables with the same storage class, auto can only be used within functions, i.e., local variables. The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location). { register int miles; } The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions. The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared. In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class. #include <iostream> // Function declaration void func(void); static int count = 10; /* Global variable */ main() { while(count--) { func(); } return 0; } // Function definition void func( void ) { static int i = 5; // local static variable i++; std::cout << "i is " << i ; std::cout << " and count is " << count << std::endl; } When the above code is compiled and executed, it produces the following result − i is 6 and count is 9 i is 7 and count is 8 i is 8 and count is 7 i is 9 and count is 6 i is 10 and count is 5 i is 11 and count is 4 i is 12 and count is 3 i is 13 and count is 2 i is 14 and count is 1 i is 15 and count is 0 The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined. When you have multiple files and you define a global variable or function, which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to declare a global variable or function in another file. The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below. #include <iostream> int count ; extern void write_extern(); main() { count = 5; write_extern(); } #include <iostream> extern int count; void write_extern(void) { std::cout << "Count is " << count << std::endl; } Here, extern keyword is being used to declare count in another file. Now compile these two files as follows − $g++ main.cpp support.cpp -o write This will produce write executable program, try to execute write and check the result as follows − $./write 5 The mutable specifier applies only to class objects, which are discussed later in this tutorial. It allows a member of an object to override const member function. That is, a mutable member can be modified by a const member function.
[ { "code": null, "e": 2689, "s": 2452, "text": "A storage class defines the scope (visibility) and life-time of variables and/or functions within a C++ Program. These specifiers precede the type that they modify. There are following storage classes, which can be used in a C++ Program" }, { "code": null, "e": 2694, "s": 2689, "text": "auto" }, { "code": null, "e": 2703, "s": 2694, "text": "register" }, { "code": null, "e": 2710, "s": 2703, "text": "static" }, { "code": null, "e": 2717, "s": 2710, "text": "extern" }, { "code": null, "e": 2725, "s": 2717, "text": "mutable" }, { "code": null, "e": 2802, "s": 2725, "text": "The auto storage class is the default storage class for all local variables." }, { "code": null, "e": 2840, "s": 2802, "text": "{\n int mount;\n auto int month;\n}\n" }, { "code": null, "e": 2972, "s": 2840, "text": "The example above defines two variables with the same storage class, auto can only be used within functions, i.e., local variables." }, { "code": null, "e": 3272, "s": 2972, "text": "The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location)." }, { "code": null, "e": 3301, "s": 3272, "text": "{\n register int miles;\n}\n" }, { "code": null, "e": 3605, "s": 3301, "text": "The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions." }, { "code": null, "e": 3915, "s": 3605, "text": "The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls." }, { "code": null, "e": 4081, "s": 3915, "text": "The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared." }, { "code": null, "e": 4214, "s": 4081, "text": "In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class." }, { "code": null, "e": 4580, "s": 4214, "text": "#include <iostream>\n \n// Function declaration\nvoid func(void);\n \nstatic int count = 10; /* Global variable */\n \nmain() {\n while(count--) {\n func();\n }\n \n return 0;\n}\n\n// Function definition\nvoid func( void ) {\n static int i = 5; // local static variable\n i++;\n std::cout << \"i is \" << i ;\n std::cout << \" and count is \" << count << std::endl;\n}" }, { "code": null, "e": 4661, "s": 4580, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4888, "s": 4661, "text": "i is 6 and count is 9\ni is 7 and count is 8\ni is 8 and count is 7\ni is 9 and count is 6\ni is 10 and count is 5\ni is 11 and count is 4\ni is 12 and count is 3\ni is 13 and count is 2\ni is 14 and count is 1\ni is 15 and count is 0\n" }, { "code": null, "e": 5161, "s": 4888, "text": "The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined." }, { "code": null, "e": 5466, "s": 5161, "text": "When you have multiple files and you define a global variable or function, which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to declare a global variable or function in another file." }, { "code": null, "e": 5608, "s": 5466, "text": "The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below." }, { "code": null, "e": 5714, "s": 5608, "text": "#include <iostream>\nint count ;\nextern void write_extern();\n \nmain() {\n count = 5;\n write_extern();\n}" }, { "code": null, "e": 5834, "s": 5714, "text": "#include <iostream>\n\nextern int count;\n\nvoid write_extern(void) {\n std::cout << \"Count is \" << count << std::endl;\n}\n" }, { "code": null, "e": 5944, "s": 5834, "text": "Here, extern keyword is being used to declare count in another file. Now compile these two files as follows −" }, { "code": null, "e": 5980, "s": 5944, "text": "$g++ main.cpp support.cpp -o write\n" }, { "code": null, "e": 6079, "s": 5980, "text": "This will produce write executable program, try to execute write and check the result as follows −" }, { "code": null, "e": 6091, "s": 6079, "text": "$./write\n5\n" } ]
Matrix Multiplication in NumPy
02 Sep, 2020 Let us see how to compute matrix multiplication with NumPy. We will be using the numpy.dot() method to find the product of 2 matrices. For example, for two matrices A and B. A = [[1, 2], [2, 3]] B = [[4, 5], [6, 7]] So, A.B = [[1*4 + 2*6, 2*4 + 3*6], [1*5 + 2*7, 2*5 + 3*7] So the computed answer will be: [[16, 26], [19, 31]] In Python numpy.dot() method is used to calculate the dot product between two arrays. Example 1 : Matrix multiplication of 2 square matrices. # importing the moduleimport numpy as np # creating two matricesp = [[1, 2], [2, 3]]q = [[4, 5], [6, 7]]print("Matrix p :")print(p)print("Matrix q :")print(q) # computing productresult = np.dot(p, q) # printing the resultprint("The matrix multiplication is :")print(result) Output : Matrix p : [[1, 2], [2, 3]] Matrix q : [[4, 5], [6, 7]] The matrix multiplication is : [[16 19] [26 31]] Example 2 : Matrix multiplication of 2 rectangular matrices. # importing the moduleimport numpy as np # creating two matricesp = [[1, 2], [2, 3], [4, 5]]q = [[4, 5, 1], [6, 7, 2]]print("Matrix p :")print(p)print("Matrix q :")print(q) # computing productresult = np.dot(p, q) # printing the resultprint("The matrix multiplication is :")print(result) Output : Matrix p : [[1, 2], [2, 3], [4, 5]] Matrix q : [[4, 5, 1], [6, 7, 2]] The matrix multiplication is : [[16 19 5] [26 31 8] [46 55 14]] Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2020" }, { "code": null, "e": 163, "s": 28, "text": "Let us see how to compute matrix multiplication with NumPy. We will be using the numpy.dot() method to find the product of 2 matrices." }, { "code": null, "e": 357, "s": 163, "text": "For example, for two matrices A and B.\nA = [[1, 2], [2, 3]]\nB = [[4, 5], [6, 7]]\n\nSo, A.B = [[1*4 + 2*6, 2*4 + 3*6], [1*5 + 2*7, 2*5 + 3*7]\nSo the computed answer will be: [[16, 26], [19, 31]]\n" }, { "code": null, "e": 443, "s": 357, "text": "In Python numpy.dot() method is used to calculate the dot product between two arrays." }, { "code": null, "e": 499, "s": 443, "text": "Example 1 : Matrix multiplication of 2 square matrices." }, { "code": "# importing the moduleimport numpy as np # creating two matricesp = [[1, 2], [2, 3]]q = [[4, 5], [6, 7]]print(\"Matrix p :\")print(p)print(\"Matrix q :\")print(q) # computing productresult = np.dot(p, q) # printing the resultprint(\"The matrix multiplication is :\")print(result)", "e": 776, "s": 499, "text": null }, { "code": null, "e": 785, "s": 776, "text": "Output :" }, { "code": null, "e": 892, "s": 785, "text": "Matrix p :\n[[1, 2], [2, 3]]\nMatrix q :\n[[4, 5], [6, 7]]\nThe matrix multiplication is :\n[[16 19]\n [26 31]]\n" }, { "code": null, "e": 953, "s": 892, "text": "Example 2 : Matrix multiplication of 2 rectangular matrices." }, { "code": "# importing the moduleimport numpy as np # creating two matricesp = [[1, 2], [2, 3], [4, 5]]q = [[4, 5, 1], [6, 7, 2]]print(\"Matrix p :\")print(p)print(\"Matrix q :\")print(q) # computing productresult = np.dot(p, q) # printing the resultprint(\"The matrix multiplication is :\")print(result)", "e": 1244, "s": 953, "text": null }, { "code": null, "e": 1253, "s": 1244, "text": "Output :" }, { "code": null, "e": 1392, "s": 1253, "text": "Matrix p :\n[[1, 2], [2, 3], [4, 5]]\nMatrix q :\n[[4, 5, 1], [6, 7, 2]]\nThe matrix multiplication is :\n[[16 19 5]\n [26 31 8]\n [46 55 14]]\n" }, { "code": null, "e": 1427, "s": 1392, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 1440, "s": 1427, "text": "Python-numpy" }, { "code": null, "e": 1447, "s": 1440, "text": "Python" }, { "code": null, "e": 1545, "s": 1447, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1577, "s": 1545, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1604, "s": 1577, "text": "Python Classes and Objects" }, { "code": null, "e": 1635, "s": 1604, "text": "Python | os.path.join() method" }, { "code": null, "e": 1658, "s": 1635, "text": "Introduction To PYTHON" }, { "code": null, "e": 1679, "s": 1658, "text": "Python OOPs Concepts" }, { "code": null, "e": 1735, "s": 1679, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1777, "s": 1735, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1819, "s": 1777, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1858, "s": 1819, "text": "Python | Get unique values from a list" } ]
Groovy - replaceAll()
Replaces all occurrences of a captured group by the result of a closure on that text. void replaceAll(String regex, String replacement) regex − the regular expression to which this string is to be matched. regex − the regular expression to which this string is to be matched. replacement − the string which would replace found expression. replacement − the string which would replace found expression. This method returns the resulting String. Following is an example of the usage of this method − class Example { static void main(String[] args) { String a = "Hello World Hello"; println(a.replaceAll("Hello","Bye")); println(a.replaceAll("World","Hello")); } } When we run the above program, we will get the following result − Bye World Bye Hello Hello Hello 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2324, "s": 2238, "text": "Replaces all occurrences of a captured group by the result of a closure on that text." }, { "code": null, "e": 2375, "s": 2324, "text": "void replaceAll(String regex, String replacement)\n" }, { "code": null, "e": 2445, "s": 2375, "text": "regex − the regular expression to which this string is to be matched." }, { "code": null, "e": 2515, "s": 2445, "text": "regex − the regular expression to which this string is to be matched." }, { "code": null, "e": 2578, "s": 2515, "text": "replacement − the string which would replace found expression." }, { "code": null, "e": 2641, "s": 2578, "text": "replacement − the string which would replace found expression." }, { "code": null, "e": 2683, "s": 2641, "text": "This method returns the resulting String." }, { "code": null, "e": 2737, "s": 2683, "text": "Following is an example of the usage of this method −" }, { "code": null, "e": 2935, "s": 2737, "text": "class Example { \n static void main(String[] args) { \n String a = \"Hello World Hello\"; \n println(a.replaceAll(\"Hello\",\"Bye\")); \n println(a.replaceAll(\"World\",\"Hello\")); \n } \n}" }, { "code": null, "e": 3001, "s": 2935, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 3035, "s": 3001, "text": "Bye World Bye \nHello Hello Hello\n" }, { "code": null, "e": 3068, "s": 3035, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 3086, "s": 3068, "text": " Krishna Sakinala" }, { "code": null, "e": 3121, "s": 3086, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3139, "s": 3121, "text": " Packt Publishing" }, { "code": null, "e": 3146, "s": 3139, "text": " Print" }, { "code": null, "e": 3157, "s": 3146, "text": " Add Notes" } ]
Check if values of two arrays are the same/equal in JavaScript
We have two arrays of numbers, let’s say − [2, 4, 6, 7, 1] [4, 1, 7, 6, 2] Assume, we have to write a function that returns a boolean based on the fact whether or not they contain the same elements irrespective of their order. For example − [2, 4, 6, 7, 1] and [4, 1, 7, 6, 2] should yield true because they have the same elements but ordered differently. Now, let’s write the code for this function − const first = [2, 4, 6, 7, 1]; const second = [4, 1, 7, 6, 2]; const areEqual = (first, second) => { if(first.length !== second.length){ return false; }; for(let i = 0; i < first.length; i++){ if(!second.includes(first[i])){ return false; }; }; return true; }; console.log(areEqual(first, second)); The output in the console will be − true
[ { "code": null, "e": 1105, "s": 1062, "text": "We have two arrays of numbers, let’s say −" }, { "code": null, "e": 1137, "s": 1105, "text": "[2, 4, 6, 7, 1]\n[4, 1, 7, 6, 2]" }, { "code": null, "e": 1289, "s": 1137, "text": "Assume, we have to write a function that returns a boolean based on the fact whether or not\nthey contain the same elements irrespective of their order." }, { "code": null, "e": 1303, "s": 1289, "text": "For example −" }, { "code": null, "e": 1418, "s": 1303, "text": "[2, 4, 6, 7, 1] and [4, 1, 7, 6, 2] should yield true because they have the same elements but\nordered differently." }, { "code": null, "e": 1464, "s": 1418, "text": "Now, let’s write the code for this function −" }, { "code": null, "e": 1805, "s": 1464, "text": "const first = [2, 4, 6, 7, 1];\nconst second = [4, 1, 7, 6, 2];\nconst areEqual = (first, second) => {\n if(first.length !== second.length){\n return false;\n };\n for(let i = 0; i < first.length; i++){\n if(!second.includes(first[i])){\n return false;\n };\n };\n return true;\n};\nconsole.log(areEqual(first, second));" }, { "code": null, "e": 1841, "s": 1805, "text": "The output in the console will be −" }, { "code": null, "e": 1846, "s": 1841, "text": "true" } ]
How to use Predicate<T> and BiPredicate<T, U> in lambda expression in Java?
A Predicate<T> interface defined in java.util.function package. It represents a boolean-valued function with one argument. It is kind of a functional interface whose functional method is the test(). BiPredicate<T, U> interface is similar to the Predicate<T> interface with two arguments. It can be used as an assignment target for a lambda expression. @FunctionalInterface public interface Predicate<T> import java.util.*; import java.util.function.*; import java.util.stream.*; public class EmployeePredicateTest { public static void main(String[] args) { Employee e1 = new Employee(1, 23, "M", "Raja"); Employee e2 = new Employee(2, 13, "M", "Jai"); Employee e3 = new Employee(3, 36, "F", "Yamini"); Employee e4 = new Employee(4, 26, "F", "Geetha"); Employee e5 = new Employee(5, 19, "M", "Adithya"); List<Employee> employees = new ArrayList<Employee>(); employees.addAll(Arrays.asList(new Employee[]{e1, e2, e3, e4, e5})); System.out.println(EmployeePredicate.filterEmployees(employees, EmployeePredicate.isAdultMale())); System.out.println(EmployeePredicate.filterEmployees(employees, EmployeePredicate.isAdultFemale())); System.out.println(EmployeePredicate.filterEmployees(employees, EmployeePredicate.isAgeMoreThan(35))); System.out.println(EmployeePredicate.filterEmployees(employees, EmployeePredicate.isAgeMoreThan(35).negate())); } } // Employee class class Employee { private Integer id; private Integer age; private String gender; private String name; public Employee(Integer id, Integer age, String gender, String name) { this.id = id; this.age = age; this.gender = gender; this.name = name; } public Integer getAge() { return age; } public String getGender() { return gender; } public String getName() { return name; } @Override public String toString() { return this.name.toString()+" - "+ this.age.toString(); } } // EmployeePredicate class class EmployeePredicate { public static Predicate isAdultMale() { return p -> p.getAge() > 21 && p.getGender().equalsIgnoreCase("M"); } public static Predicate isAdultFemale() { return p -> p.getAge() > 18 && p.getGender().equalsIgnoreCase("F"); } public static Predicate isAgeMoreThan(Integer age) { return p -> p.getAge() > age; } public static List filterEmployees(List<Employee> employees, Predicate<Employee> predicate) { return employees.stream().filter(predicate).collect(Collectors.<Employee>toList()); } } [Raja - 23] [Yamini - 36, Geetha - 26] [Yamini - 36] [Raja - 23, Jai - 13, Geetha - 26, Adithya - 19] @FunctionalInterface public interface BiPredicate<T, U> import java.util.*; import java.util.function.*; public class BiPredicateTest { public static void main(String[] args) { BiPredicate<Integer, Integer> bi = (x, y) -> x > y; BiPredicate<Integer, Integer> eq = (x, y) -> x -2 > y; System.out.println(bi.test(2, 3)); System.out.println(bi.or(eq).test(2, 3)); System.out.println(bi.or(eq).test(8, 3)); } } false false true
[ { "code": null, "e": 1414, "s": 1062, "text": "A Predicate<T> interface defined in java.util.function package. It represents a boolean-valued function with one argument. It is kind of a functional interface whose functional method is the test(). BiPredicate<T, U> interface is similar to the Predicate<T> interface with two arguments. It can be used as an assignment target for a lambda expression." }, { "code": null, "e": 1465, "s": 1414, "text": "@FunctionalInterface\npublic interface Predicate<T>" }, { "code": null, "e": 3659, "s": 1465, "text": "import java.util.*;\nimport java.util.function.*;\nimport java.util.stream.*;\n\npublic class EmployeePredicateTest {\n public static void main(String[] args) {\n Employee e1 = new Employee(1, 23, \"M\", \"Raja\");\n Employee e2 = new Employee(2, 13, \"M\", \"Jai\");\n Employee e3 = new Employee(3, 36, \"F\", \"Yamini\");\n Employee e4 = new Employee(4, 26, \"F\", \"Geetha\");\n Employee e5 = new Employee(5, 19, \"M\", \"Adithya\");\n\n List<Employee> employees = new ArrayList<Employee>();\n employees.addAll(Arrays.asList(new Employee[]{e1, e2, e3, e4, e5}));\n\n System.out.println(EmployeePredicate.filterEmployees(employees, EmployeePredicate.isAdultMale()));\n System.out.println(EmployeePredicate.filterEmployees(employees, EmployeePredicate.isAdultFemale()));\n System.out.println(EmployeePredicate.filterEmployees(employees, EmployeePredicate.isAgeMoreThan(35)));\n System.out.println(EmployeePredicate.filterEmployees(employees, EmployeePredicate.isAgeMoreThan(35).negate()));\n }\n}\n\n// Employee class\nclass Employee {\n private Integer id;\n private Integer age;\n private String gender;\n private String name;\n public Employee(Integer id, Integer age, String gender, String name) {\n this.id = id;\n this.age = age;\n this.gender = gender;\n this.name = name;\n }\n public Integer getAge() {\n return age;\n }\n public String getGender() {\n return gender;\n }\n public String getName() {\n return name;\n }\n @Override\n public String toString() {\n return this.name.toString()+\" - \"+ this.age.toString();\n }\n}\n\n// EmployeePredicate class\nclass EmployeePredicate {\n public static Predicate isAdultMale() {\n return p -> p.getAge() > 21 && p.getGender().equalsIgnoreCase(\"M\");\n }\n public static Predicate isAdultFemale() {\n return p -> p.getAge() > 18 && p.getGender().equalsIgnoreCase(\"F\");\n }\n public static Predicate isAgeMoreThan(Integer age) {\n return p -> p.getAge() > age;\n }\n public static List filterEmployees(List<Employee> employees, Predicate<Employee> predicate) {\n return employees.stream().filter(predicate).collect(Collectors.<Employee>toList());\n }\n}" }, { "code": null, "e": 3761, "s": 3659, "text": "[Raja - 23]\n[Yamini - 36, Geetha - 26]\n[Yamini - 36]\n[Raja - 23, Jai - 13, Geetha - 26, Adithya - 19]" }, { "code": null, "e": 3817, "s": 3761, "text": "@FunctionalInterface\npublic interface BiPredicate<T, U>" }, { "code": null, "e": 4206, "s": 3817, "text": "import java.util.*;\nimport java.util.function.*;\n\npublic class BiPredicateTest {\n public static void main(String[] args) {\n BiPredicate<Integer, Integer> bi = (x, y) -> x > y;\n BiPredicate<Integer, Integer> eq = (x, y) -> x -2 > y;\n\n System.out.println(bi.test(2, 3));\n System.out.println(bi.or(eq).test(2, 3));\n System.out.println(bi.or(eq).test(8, 3));\n }\n}" }, { "code": null, "e": 4223, "s": 4206, "text": "false\nfalse\ntrue" } ]
Print all Subsequences of String which Start with Vowel and End with Consonant in C++
In this problem, we are given a string and we have to find the substring from the given string. The substring to be found should start with a vowel and end with constant character. A string is an array of characters. The substring that is to be generated in this problem can be generated by deleting some characters of the string. And without changing the order of the string. Input: ‘abc’ Output: ab, ac, abc To solve this problem, we will iterate the string and fix vowels and check for the next sequence. Let’s see an algorithm to find a solution − Step 1: Iterate of each character of the string, with variable i. Step 2: If the ith character is a vowel. Step 3: If the jth character is a consonant. Step 4: Add to the HashSet, substring from 1st character to jth character. Step 5: Repeat the following steps and find substrings from the string. Live Demo #include <bits/stdc++.h> using namespace std; set<string> st; bool isaVowel(char c); bool isaConsonant(char c); void findSubSequence(string str); int main(){ string s = "abekns"; findSubSequence(s); cout<<"The substring generated are :\n"; for (auto i : st) cout<<i<<" "; cout << endl; return 0; } bool isaVowel(char c) { return (c=='a'||c=='e'||c=='i'||c=='o'||c=='u'); } bool isaConsonant(char c) { return !isaVowel(c); } void findSubSequence(string str) { for (int i = 0; i < str.length(); i++) { if (isaVowel(str[i])) { for (int j = str.length() - 1; j >= i; j--) { if (isaConsonant(str[j])) { string str_sub = str.substr(i, j + 1); st.insert(str_sub); for (int k = 1; k < str_sub.length() - 1; k++){ string sb = str_sub; sb.erase(sb.begin() + k); findSubSequence(sb); } } } } } } The substring generated are − ab abek abekn abekns abeks aben abens abes abk abkn abkns abks abn abns abs aek aekn aekns aeks aen aens aes ak akn akns aks an ans as ek ekn ekns eks en ens es
[ { "code": null, "e": 1243, "s": 1062, "text": "In this problem, we are given a string and we have to find the substring from the given string. The substring to be found should start with a vowel and end with constant character." }, { "code": null, "e": 1279, "s": 1243, "text": "A string is an array of characters." }, { "code": null, "e": 1439, "s": 1279, "text": "The substring that is to be generated in this problem can be generated by deleting some characters of the string. And without changing the order of the string." }, { "code": null, "e": 1472, "s": 1439, "text": "Input: ‘abc’\nOutput: ab, ac, abc" }, { "code": null, "e": 1614, "s": 1472, "text": "To solve this problem, we will iterate the string and fix vowels and check for the next sequence. Let’s see an algorithm to find a solution −" }, { "code": null, "e": 1913, "s": 1614, "text": "Step 1: Iterate of each character of the string, with variable i.\nStep 2: If the ith character is a vowel.\nStep 3: If the jth character is a consonant.\nStep 4: Add to the HashSet, substring from 1st character to jth character.\nStep 5: Repeat the following steps and find substrings from the string." }, { "code": null, "e": 1924, "s": 1913, "text": " Live Demo" }, { "code": null, "e": 2913, "s": 1924, "text": "#include <bits/stdc++.h>\nusing namespace std;\nset<string> st;\nbool isaVowel(char c);\nbool isaConsonant(char c);\nvoid findSubSequence(string str);\nint main(){\n string s = \"abekns\";\n findSubSequence(s);\n cout<<\"The substring generated are :\\n\";\n for (auto i : st)\n cout<<i<<\" \";\n cout << endl;\n return 0;\n}\nbool isaVowel(char c) {\n return (c=='a'||c=='e'||c=='i'||c=='o'||c=='u');\n}\nbool isaConsonant(char c) {\n return !isaVowel(c);\n}\nvoid findSubSequence(string str) {\n for (int i = 0; i < str.length(); i++) {\n if (isaVowel(str[i])) {\n for (int j = str.length() - 1; j >= i; j--) {\n if (isaConsonant(str[j])) {\n string str_sub = str.substr(i, j + 1);\n st.insert(str_sub);\n for (int k = 1; k < str_sub.length() - 1; k++){\n string sb = str_sub;\n sb.erase(sb.begin() + k);\n findSubSequence(sb);\n }\n }\n }\n }\n }\n}" }, { "code": null, "e": 2943, "s": 2913, "text": "The substring generated are −" }, { "code": null, "e": 3104, "s": 2943, "text": "ab abek abekn abekns abeks aben abens abes abk abkn abkns abks abn abns abs aek aekn aekns aeks aen aens aes ak akn akns aks an ans as ek ekn ekns eks en ens es" } ]
How to plot two histograms together in R?
Consider the below data frames − > glucose <- data.frame(length = rnorm(100, 2.5)) > fructose <- data.frame(length = rnorm(500, 2.5)) We need to combine these two data frames but before that we have to make a new column in each of these data frames to create their identification > glucose$sweetener <- 'glucose' > fructose$sweetener <- 'fructose' > sweeteners <- rbind(glucose, fructose) Now let’s create the histograms > library(ggplot2) > ggplot(sweeteners, aes(length, fill = sweetener)) + geom_density(alpha = 0.2)
[ { "code": null, "e": 1095, "s": 1062, "text": "Consider the below data frames −" }, { "code": null, "e": 1197, "s": 1095, "text": "> glucose <- data.frame(length = rnorm(100, 2.5))\n> fructose <- data.frame(length = rnorm(500, 2.5))" }, { "code": null, "e": 1343, "s": 1197, "text": "We need to combine these two data frames but before that we have to make a new\ncolumn in each of these data frames to create their identification" }, { "code": null, "e": 1453, "s": 1343, "text": "> glucose$sweetener <- 'glucose'\n> fructose$sweetener <- 'fructose'\n> sweeteners <- rbind(glucose, fructose)" }, { "code": null, "e": 1485, "s": 1453, "text": "Now let’s create the histograms" }, { "code": null, "e": 1584, "s": 1485, "text": "> library(ggplot2)\n> ggplot(sweeteners, aes(length, fill = sweetener)) + geom_density(alpha = 0.2)" } ]
Collections.singleton() method in Java with example - GeeksforGeeks
02 Jul, 2021 java.util.Collections.singleton() method is a java.util.Collections class method. It creates a immutable set over a single specified element. An application of this method is to remove an element from Collections like List and Set. Syntax: public static Set singleton(T obj) and public static List singletonList(T obj) Parameters: obj : the sole object to be stored in the returned list or set. Return: an immutable list/set containing only the specified object. Example: myList : {"Geeks", "code", "Practice", " Error", "Java", "Class", "Error", "Practice", "Java" } To remove all "Error" elements from our list at once, we use singleton() method myList.removeAll(Collections.singleton("Error")); After using singleton() and removeAll, we get following. {"Geeks", "code", "Practice", "Java", "Class", "Practice", "Java" } Java // Java program to demonstrate// working of singleton()import java.util.*; class GFG { public static void main(String args[]) { String[] geekslist = { "1", "2", "4", "2", "1", "2", "3", "1", "3", "4", "3", "3" }; // Creating a list and removing // elements without use of singleton() List geekslist1 = new ArrayList(Arrays.asList(geekslist)); System.out.println("Original geeklist1: " + geekslist1); geekslist1.remove("1"); System.out.println("geekslist1 after removal of 1 without" + " singleton " + geekslist1); geekslist1.remove("1"); System.out.println("geekslist1 after removal of 1 without" + " singleton " + geekslist1); geekslist1.remove("2"); System.out.println("geekslist1 after removal of 2 without" + " singleton " + geekslist1); /* Creating another list and removing its elements using singleton() method */ List geekslist2 = new ArrayList(Arrays.asList(geekslist)); System.out.println("\nOriginal geeklist2: " + geekslist2); // Selectively delete "1" from // all it's occurrences geekslist2.removeAll(Collections.singleton("1")); System.out.println("geekslist2 after removal of 1 with " + "singleton:" + geekslist2); // Selectively delete "4" from // all it's occurrences geekslist2.removeAll(Collections.singleton("4")); System.out.println("geekslist2 after removal of 4 with " + "singleton:" + geekslist2); // Selectively delete "3" from // all it's occurrences geekslist2.removeAll(Collections.singleton("3")); System.out.println("geekslist2 after removal of 3 with" + " singleton: " + geekslist2); }} Output: Original geeklist1 [1, 2, 4, 2, 1, 2, 3, 1, 3, 4, 3, 3] geekslist1 after removal of 1 without singleton [2, 4, 2, 1, 2, 3, 1, 3, 4, 3, 3] geekslist1 after removal of 1 without singleton [2, 4, 2, 2, 3, 1, 3, 4, 3, 3] geekslist1 after removal of 2 without singleton [4, 2, 2, 3, 1, 3, 4, 3, 3] Original geeklist2 [1, 2, 4, 2, 1, 2, 3, 1, 3, 4, 3, 3] geekslist2 after removal of 1 with singleton [2, 4, 2, 2, 3, 3, 4, 3, 3] geekslist2 after removal of 4 with singleton [2, 2, 2, 3, 3, 3, 3] geekslist2 after removal of 3 with singleton [2, 2, 2] This article is contributed by Mohit Gupta. 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 nishantsaini ShahTanay akshaysingh98088 Java - util package Java-Collections Java-Collections-Class Java-Functions Java-Library Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java HashMap in Java with Examples Interfaces in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Stack Class in Java Stream In Java Singleton Class in Java Set in Java
[ { "code": null, "e": 24318, "s": 24290, "text": "\n02 Jul, 2021" }, { "code": null, "e": 24550, "s": 24318, "text": "java.util.Collections.singleton() method is a java.util.Collections class method. It creates a immutable set over a single specified element. An application of this method is to remove an element from Collections like List and Set." }, { "code": null, "e": 24559, "s": 24550, "text": "Syntax: " }, { "code": null, "e": 24810, "s": 24559, "text": "public static Set singleton(T obj)\nand\npublic static List singletonList(T obj)\nParameters: obj : the sole object to be stored in\n the returned list or set.\nReturn: an immutable list/set containing only the \n specified object." }, { "code": null, "e": 25186, "s": 24810, "text": "Example:\nmyList : {\"Geeks\", \"code\", \"Practice\", \" Error\", \"Java\", \n \"Class\", \"Error\", \"Practice\", \"Java\" }\n\nTo remove all \"Error\" elements from our list at once, we use \nsingleton() method \nmyList.removeAll(Collections.singleton(\"Error\"));\n\nAfter using singleton() and removeAll, we get following.\n{\"Geeks\", \"code\", \"Practice\", \"Java\", \"Class\", \"Practice\", \"Java\" }" }, { "code": null, "e": 25191, "s": 25186, "text": "Java" }, { "code": "// Java program to demonstrate// working of singleton()import java.util.*; class GFG { public static void main(String args[]) { String[] geekslist = { \"1\", \"2\", \"4\", \"2\", \"1\", \"2\", \"3\", \"1\", \"3\", \"4\", \"3\", \"3\" }; // Creating a list and removing // elements without use of singleton() List geekslist1 = new ArrayList(Arrays.asList(geekslist)); System.out.println(\"Original geeklist1: \" + geekslist1); geekslist1.remove(\"1\"); System.out.println(\"geekslist1 after removal of 1 without\" + \" singleton \" + geekslist1); geekslist1.remove(\"1\"); System.out.println(\"geekslist1 after removal of 1 without\" + \" singleton \" + geekslist1); geekslist1.remove(\"2\"); System.out.println(\"geekslist1 after removal of 2 without\" + \" singleton \" + geekslist1); /* Creating another list and removing its elements using singleton() method */ List geekslist2 = new ArrayList(Arrays.asList(geekslist)); System.out.println(\"\\nOriginal geeklist2: \" + geekslist2); // Selectively delete \"1\" from // all it's occurrences geekslist2.removeAll(Collections.singleton(\"1\")); System.out.println(\"geekslist2 after removal of 1 with \" + \"singleton:\" + geekslist2); // Selectively delete \"4\" from // all it's occurrences geekslist2.removeAll(Collections.singleton(\"4\")); System.out.println(\"geekslist2 after removal of 4 with \" + \"singleton:\" + geekslist2); // Selectively delete \"3\" from // all it's occurrences geekslist2.removeAll(Collections.singleton(\"3\")); System.out.println(\"geekslist2 after removal of 3 with\" + \" singleton: \" + geekslist2); }}", "e": 27096, "s": 25191, "text": null }, { "code": null, "e": 27105, "s": 27096, "text": "Output: " }, { "code": null, "e": 27694, "s": 27105, "text": "Original geeklist1 [1, 2, 4, 2, 1, 2, 3, 1, 3, 4, 3, 3]\ngeekslist1 after removal of 1 without singleton [2, 4, 2, 1, 2, 3, 1, 3, 4, 3, 3]\ngeekslist1 after removal of 1 without singleton [2, 4, 2, 2, 3, 1, 3, 4, 3, 3]\ngeekslist1 after removal of 2 without singleton [4, 2, 2, 3, 1, 3, 4, 3, 3]\n\nOriginal geeklist2 [1, 2, 4, 2, 1, 2, 3, 1, 3, 4, 3, 3]\ngeekslist2 after removal of 1 with singleton [2, 4, 2, 2, 3, 3, 4, 3, 3]\ngeekslist2 after removal of 4 with singleton [2, 2, 2, 3, 3, 3, 3]\ngeekslist2 after removal of 3 with singleton [2, 2, 2]" }, { "code": null, "e": 28113, "s": 27694, "text": "This article is contributed by Mohit Gupta. 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": 28126, "s": 28113, "text": "nishantsaini" }, { "code": null, "e": 28136, "s": 28126, "text": "ShahTanay" }, { "code": null, "e": 28153, "s": 28136, "text": "akshaysingh98088" }, { "code": null, "e": 28173, "s": 28153, "text": "Java - util package" }, { "code": null, "e": 28190, "s": 28173, "text": "Java-Collections" }, { "code": null, "e": 28213, "s": 28190, "text": "Java-Collections-Class" }, { "code": null, "e": 28228, "s": 28213, "text": "Java-Functions" }, { "code": null, "e": 28241, "s": 28228, "text": "Java-Library" }, { "code": null, "e": 28246, "s": 28241, "text": "Java" }, { "code": null, "e": 28251, "s": 28246, "text": "Java" }, { "code": null, "e": 28268, "s": 28251, "text": "Java-Collections" }, { "code": null, "e": 28366, "s": 28268, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28398, "s": 28366, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28428, "s": 28398, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28447, "s": 28428, "text": "Interfaces in Java" }, { "code": null, "e": 28465, "s": 28447, "text": "ArrayList in Java" }, { "code": null, "e": 28496, "s": 28465, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28528, "s": 28496, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28548, "s": 28528, "text": "Stack Class in Java" }, { "code": null, "e": 28563, "s": 28548, "text": "Stream In Java" }, { "code": null, "e": 28587, "s": 28563, "text": "Singleton Class in Java" } ]
bar() function in C graphics
bar() function is a C graphics function that is used to draw graphics in the C programming language. The graphics.h header contains functions that work for drawing graphics. The bar() function is also defined in the header file. void bar(int left, int top, int right, int bottom ); The bar() function is used to draw a bar ( of bar graph) which is a 2-dimensional figure. It is filled rectangular figure. The function takes four arguments that are the coordinates of (X, Y) coordinates of the top-left corner of the bar {left and top } and (X, Y) coordinates of the bottom-right corner of the bar {right and bottom}. #include <graphics.h> #include <conio.h> int main() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\TC\\BGI"); bar(120, 120, 250, 250); getch(); closegraph(); return 0; }
[ { "code": null, "e": 1291, "s": 1062, "text": "bar() function is a C graphics function that is used to draw graphics in the C programming language. The graphics.h header contains functions that work for drawing graphics. The bar() function is also defined in the header file." }, { "code": null, "e": 1344, "s": 1291, "text": "void bar(int left, int top, int right, int bottom );" }, { "code": null, "e": 1679, "s": 1344, "text": "The bar() function is used to draw a bar ( of bar graph) which is a 2-dimensional figure. It is filled rectangular figure. The function takes four arguments that are the coordinates of (X, Y) coordinates of the top-left corner of the bar {left and top } and (X, Y) coordinates of the bottom-right corner of the bar {right and bottom}." }, { "code": null, "e": 1869, "s": 1679, "text": "#include <graphics.h>\n#include <conio.h>\n\nint main() {\n int gd = DETECT, gm;\n initgraph(&gd, &gm, \"C:\\\\TC\\\\BGI\");\n bar(120, 120, 250, 250);\n getch();\n closegraph();\n return 0;\n}" } ]
C program to implement DFS traversal using Adjacency Matrix in a given Graph - GeeksforGeeks
13 Jan, 2022 Given a undirected graph with V vertices and E edges. The task is to perform DFS traversal of the graph. Examples: Input: V = 7, E = 7Connections: 0-1, 0-2, 1-3, 1-4, 1-5, 1-6, 6-2See the diagram for connections: Output : 0 1 3 4 5 6 2Explanation: The traversal starts from 0 and follows the following path 0-1, 1-3, 1-4, 1-5, 1-6, 6-2. Input: V = 1, E = 0Output: 0Explanation: There is no other vertex than 0 itself. Approach: Follow the approach mentioned below. Initially all vertices are marked unvisited (false). The DFS algorithm starts at a vertex u in the graph. By starting at vertex u it considers the edges from u to other vertices.If the edge leads to an already visited vertex, then backtrack to current vertex u.If an edge leads to an unvisited vertex, then go to that vertex and start processing from that vertex. That means the new vertex becomes the current root for traversal. If the edge leads to an already visited vertex, then backtrack to current vertex u. If an edge leads to an unvisited vertex, then go to that vertex and start processing from that vertex. That means the new vertex becomes the current root for traversal. Follow this process until a vertices are marked visited. Here adjacency matrix is used to store the connection between the vertices. Take the following graph: The adjacency matrix for this graph is: Below is implementations of simple Depth First Traversal. C // C code to implement above approach#include <stdio.h>#include <stdlib.h> // Globally declared visited arrayint vis[100]; // Graph structure to store number// of vertices and edges and// Adjacency matrixstruct Graph { int V; int E; int** Adj;}; // Function to input data of graphstruct Graph* adjMatrix(){ struct Graph* G = (struct Graph*) malloc(sizeof(struct Graph)); if (!G) { printf("Memory Error\n"); return NULL; } G->V = 7; G->E = 7; G->Adj = (int**)malloc((G->V) * sizeof(int*)); for (int k = 0; k < G->V; k++) { G->Adj[k] = (int*)malloc((G->V) * sizeof(int)); } for (int u = 0; u < G->V; u++) { for (int v = 0; v < G->V; v++) { G->Adj[u][v] = 0; } } G->Adj[0][1] = G->Adj[1][0] = 1; G->Adj[0][2] = G->Adj[2][0] = 1; G->Adj[1][3] = G->Adj[3][1] = 1; G->Adj[1][4] = G->Adj[4][1] = 1; G->Adj[1][5] = G->Adj[5][1] = 1; G->Adj[1][6] = G->Adj[6][1] = 1; G->Adj[6][2] = G->Adj[2][6] = 1; return G;} // DFS function to print DFS traversal of graphvoid DFS(struct Graph* G, int u){ vis[u] = 1; printf("%d ", u); for (int v = 0; v < G->V; v++) { if (!vis[v] && G->Adj[u][v]) { DFS(G, v); } }} // Function for DFS traversalvoid DFStraversal(struct Graph* G){ for (int i = 0; i < 100; i++) { vis[i] = 0; } for (int i = 0; i < G->V; i++) { if (!vis[i]) { DFS(G, i); } }} // Driver codevoid main(){ struct Graph* G; G = adjMatrix(); DFStraversal(G);} 0 1 3 4 5 6 2 Time Complexity: O(V + E)Auxiliary Space: O(V) sagartomar9927 Algo-Geek 2021 DFS Algo Geek C Programs Graph DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Minimize cost to sort given array by sorting unsorted subarrays Divide given number into two even parts Program to find simple moving average | Set-2 Check if the given string is valid English word or not Find Permutation of N numbers in range [1, N] such that K numbers have value same as their index Strings in C C Program to read contents of Whole File Generating random number in a range in C Regular expressions in C Header files in C/C++ and its uses
[ { "code": null, "e": 25807, "s": 25779, "text": "\n13 Jan, 2022" }, { "code": null, "e": 25912, "s": 25807, "text": "Given a undirected graph with V vertices and E edges. The task is to perform DFS traversal of the graph." }, { "code": null, "e": 25922, "s": 25912, "text": "Examples:" }, { "code": null, "e": 26021, "s": 25922, "text": "Input: V = 7, E = 7Connections: 0-1, 0-2, 1-3, 1-4, 1-5, 1-6, 6-2See the diagram for connections: " }, { "code": null, "e": 26145, "s": 26021, "text": "Output : 0 1 3 4 5 6 2Explanation: The traversal starts from 0 and follows the following path 0-1, 1-3, 1-4, 1-5, 1-6, 6-2." }, { "code": null, "e": 26226, "s": 26145, "text": "Input: V = 1, E = 0Output: 0Explanation: There is no other vertex than 0 itself." }, { "code": null, "e": 26273, "s": 26226, "text": "Approach: Follow the approach mentioned below." }, { "code": null, "e": 26326, "s": 26273, "text": "Initially all vertices are marked unvisited (false)." }, { "code": null, "e": 26703, "s": 26326, "text": "The DFS algorithm starts at a vertex u in the graph. By starting at vertex u it considers the edges from u to other vertices.If the edge leads to an already visited vertex, then backtrack to current vertex u.If an edge leads to an unvisited vertex, then go to that vertex and start processing from that vertex. That means the new vertex becomes the current root for traversal." }, { "code": null, "e": 26787, "s": 26703, "text": "If the edge leads to an already visited vertex, then backtrack to current vertex u." }, { "code": null, "e": 26956, "s": 26787, "text": "If an edge leads to an unvisited vertex, then go to that vertex and start processing from that vertex. That means the new vertex becomes the current root for traversal." }, { "code": null, "e": 27013, "s": 26956, "text": "Follow this process until a vertices are marked visited." }, { "code": null, "e": 27090, "s": 27013, "text": "Here adjacency matrix is used to store the connection between the vertices. " }, { "code": null, "e": 27117, "s": 27090, "text": "Take the following graph: " }, { "code": null, "e": 27157, "s": 27117, "text": "The adjacency matrix for this graph is:" }, { "code": null, "e": 27215, "s": 27157, "text": "Below is implementations of simple Depth First Traversal." }, { "code": null, "e": 27217, "s": 27215, "text": "C" }, { "code": "// C code to implement above approach#include <stdio.h>#include <stdlib.h> // Globally declared visited arrayint vis[100]; // Graph structure to store number// of vertices and edges and// Adjacency matrixstruct Graph { int V; int E; int** Adj;}; // Function to input data of graphstruct Graph* adjMatrix(){ struct Graph* G = (struct Graph*) malloc(sizeof(struct Graph)); if (!G) { printf(\"Memory Error\\n\"); return NULL; } G->V = 7; G->E = 7; G->Adj = (int**)malloc((G->V) * sizeof(int*)); for (int k = 0; k < G->V; k++) { G->Adj[k] = (int*)malloc((G->V) * sizeof(int)); } for (int u = 0; u < G->V; u++) { for (int v = 0; v < G->V; v++) { G->Adj[u][v] = 0; } } G->Adj[0][1] = G->Adj[1][0] = 1; G->Adj[0][2] = G->Adj[2][0] = 1; G->Adj[1][3] = G->Adj[3][1] = 1; G->Adj[1][4] = G->Adj[4][1] = 1; G->Adj[1][5] = G->Adj[5][1] = 1; G->Adj[1][6] = G->Adj[6][1] = 1; G->Adj[6][2] = G->Adj[2][6] = 1; return G;} // DFS function to print DFS traversal of graphvoid DFS(struct Graph* G, int u){ vis[u] = 1; printf(\"%d \", u); for (int v = 0; v < G->V; v++) { if (!vis[v] && G->Adj[u][v]) { DFS(G, v); } }} // Function for DFS traversalvoid DFStraversal(struct Graph* G){ for (int i = 0; i < 100; i++) { vis[i] = 0; } for (int i = 0; i < G->V; i++) { if (!vis[i]) { DFS(G, i); } }} // Driver codevoid main(){ struct Graph* G; G = adjMatrix(); DFStraversal(G);}", "e": 28773, "s": 27217, "text": null }, { "code": null, "e": 28791, "s": 28776, "text": "0 1 3 4 5 6 2 " }, { "code": null, "e": 28840, "s": 28793, "text": "Time Complexity: O(V + E)Auxiliary Space: O(V)" }, { "code": null, "e": 28857, "s": 28842, "text": "sagartomar9927" }, { "code": null, "e": 28872, "s": 28857, "text": "Algo-Geek 2021" }, { "code": null, "e": 28876, "s": 28872, "text": "DFS" }, { "code": null, "e": 28886, "s": 28876, "text": "Algo Geek" }, { "code": null, "e": 28897, "s": 28886, "text": "C Programs" }, { "code": null, "e": 28903, "s": 28897, "text": "Graph" }, { "code": null, "e": 28907, "s": 28903, "text": "DFS" }, { "code": null, "e": 28913, "s": 28907, "text": "Graph" }, { "code": null, "e": 29011, "s": 28913, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29020, "s": 29011, "text": "Comments" }, { "code": null, "e": 29033, "s": 29020, "text": "Old Comments" }, { "code": null, "e": 29097, "s": 29033, "text": "Minimize cost to sort given array by sorting unsorted subarrays" }, { "code": null, "e": 29137, "s": 29097, "text": "Divide given number into two even parts" }, { "code": null, "e": 29183, "s": 29137, "text": "Program to find simple moving average | Set-2" }, { "code": null, "e": 29238, "s": 29183, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 29335, "s": 29238, "text": "Find Permutation of N numbers in range [1, N] such that K numbers have value same as their index" }, { "code": null, "e": 29348, "s": 29335, "text": "Strings in C" }, { "code": null, "e": 29389, "s": 29348, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 29430, "s": 29389, "text": "Generating random number in a range in C" }, { "code": null, "e": 29455, "s": 29430, "text": "Regular expressions in C" } ]
How can one modify the outline color of a node in networkx using Matplotlib?
To modify the outline color of a node in networkx, we can use set_edgecolor() method. Create a Pandas dataframe with from and to keys. Return a graph from Pandas DataFrame containing an edge list. Get the position of the nodes. Draw the nodes of the graph using draw_networkx_nodes(). Set the outline color of the nodes using set_edgecolor(). To display the figure, use show() method. from networkx import * import matplotlib.pyplot as plt import pandas as pd plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame({'from': ['A', 'B', 'C', 'A'], 'to': ['D', 'A', 'E', 'C']}) G = nx.from_pandas_edgelist(df, 'from', 'to') pos = spring_layout(G) nodes = draw_networkx_nodes(G, pos) nodes.set_edgecolor('red') plt.show()
[ { "code": null, "e": 1148, "s": 1062, "text": "To modify the outline color of a node in networkx, we can use set_edgecolor() method." }, { "code": null, "e": 1197, "s": 1148, "text": "Create a Pandas dataframe with from and to keys." }, { "code": null, "e": 1259, "s": 1197, "text": "Return a graph from Pandas DataFrame containing an edge list." }, { "code": null, "e": 1290, "s": 1259, "text": "Get the position of the nodes." }, { "code": null, "e": 1347, "s": 1290, "text": "Draw the nodes of the graph using draw_networkx_nodes()." }, { "code": null, "e": 1405, "s": 1347, "text": "Set the outline color of the nodes using set_edgecolor()." }, { "code": null, "e": 1447, "s": 1405, "text": "To display the figure, use show() method." }, { "code": null, "e": 1830, "s": 1447, "text": "from networkx import *\nimport matplotlib.pyplot as plt\nimport pandas as pd\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndf = pd.DataFrame({'from': ['A', 'B', 'C', 'A'], 'to': ['D', 'A', 'E', 'C']})\nG = nx.from_pandas_edgelist(df, 'from', 'to')\npos = spring_layout(G)\nnodes = draw_networkx_nodes(G, pos)\nnodes.set_edgecolor('red')\nplt.show()" } ]
How to add shadow to text using CSS ? - GeeksforGeeks
15 Sep, 2020 The approach of this article is to add a shadow using text-shadow property in CSS. This property accepts a list of a comma-separated list of shadows to be applied to the text. The default value of the text-shadow property is “none”. Syntax: text-shadow: h-shadow v-shadow blur-radius color|none|initial| Example: HTML <!DOCTYPE html><html> <head> <style> h1 { text-shadow: 4px 4px green; } h2 { text-shadow: 2px 3px blue; } </style></head> <body style="text-align:center;"> <h1> GeeksForGeeks </h1> <h2> How to apply shadow effects to text using CSS? </h2></body> </html> Output: Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Primer CSS Flexbox Flex Direction HTML Course | First Web Page | Printing Hello World Design a web page using HTML and CSS Search Bar using HTML, CSS and JavaScript How to wrap the text around an image using HTML and CSS ? How to set input type date in dd-mm-yyyy format using HTML ? Form validation using HTML and JavaScript HTML | <img> align Attribute How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 24985, "s": 24957, "text": "\n15 Sep, 2020" }, { "code": null, "e": 25218, "s": 24985, "text": "The approach of this article is to add a shadow using text-shadow property in CSS. This property accepts a list of a comma-separated list of shadows to be applied to the text. The default value of the text-shadow property is “none”." }, { "code": null, "e": 25226, "s": 25218, "text": "Syntax:" }, { "code": null, "e": 25289, "s": 25226, "text": "text-shadow: h-shadow v-shadow blur-radius color|none|initial|" }, { "code": null, "e": 25298, "s": 25289, "text": "Example:" }, { "code": null, "e": 25303, "s": 25298, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> h1 { text-shadow: 4px 4px green; } h2 { text-shadow: 2px 3px blue; } </style></head> <body style=\"text-align:center;\"> <h1> GeeksForGeeks </h1> <h2> How to apply shadow effects to text using CSS? </h2></body> </html>", "e": 25651, "s": 25303, "text": null }, { "code": null, "e": 25659, "s": 25651, "text": "Output:" }, { "code": null, "e": 25679, "s": 25659, "text": "Supported Browsers:" }, { "code": null, "e": 25693, "s": 25679, "text": "Google Chrome" }, { "code": null, "e": 25711, "s": 25693, "text": "Internet Explorer" }, { "code": null, "e": 25719, "s": 25711, "text": "Firefox" }, { "code": null, "e": 25725, "s": 25719, "text": "Opera" }, { "code": null, "e": 25732, "s": 25725, "text": "Safari" }, { "code": null, "e": 25869, "s": 25732, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 25878, "s": 25869, "text": "CSS-Misc" }, { "code": null, "e": 25888, "s": 25878, "text": "HTML-Misc" }, { "code": null, "e": 25892, "s": 25888, "text": "CSS" }, { "code": null, "e": 25897, "s": 25892, "text": "HTML" }, { "code": null, "e": 25914, "s": 25897, "text": "Web Technologies" }, { "code": null, "e": 25919, "s": 25914, "text": "HTML" }, { "code": null, "e": 26017, "s": 25919, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26026, "s": 26017, "text": "Comments" }, { "code": null, "e": 26039, "s": 26026, "text": "Old Comments" }, { "code": null, "e": 26073, "s": 26039, "text": "Primer CSS Flexbox Flex Direction" }, { "code": null, "e": 26125, "s": 26073, "text": "HTML Course | First Web Page | Printing Hello World" }, { "code": null, "e": 26162, "s": 26125, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26204, "s": 26162, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 26262, "s": 26204, "text": "How to wrap the text around an image using HTML and CSS ?" }, { "code": null, "e": 26323, "s": 26262, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 26365, "s": 26323, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 26394, "s": 26365, "text": "HTML | <img> align Attribute" } ]
Find sub-matrix with the given sum - GeeksforGeeks
18 Aug, 2021 Given an N x N matrix and two integers S and K, the task is to find whether there exists a K x K sub-matrix with sum equal to S. Examples: Input: K = 2, S = 14, mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }} Output: Yes 1 2 5 6 is the required 2 x 2 sub-matrix with element sum = 14 Input: K = 1, S = 5, mat[][] = {{1, 2}, {7, 8}} Output: No Approach: Dynamic programming can be used to solve this problem, Create an array dp[N + 1][N + 1] where dp[i][j] stores the sum of all the elements with row between 1 to i and column between 1 to j. Once the 2-D matrix is generated, now suppose we wish to find sum of square starting with (i, j) to (i + x, j + x). The required sum will be dp[i + x][j + x] – dp[i][j + x] – dp[i + x][j] + dp[i][j] where, First term denotes the sum of all the elements present in rows between 1 to i + x and columns between 1 to j + x. This area has our required square.Second two terms is to remove the area which is outside our required region but inside the region calculated in the first step.Sum of elements of rows between 1 to i and columns between 1 to j is subtracted twice in the second step, so it is added once. First term denotes the sum of all the elements present in rows between 1 to i + x and columns between 1 to j + x. This area has our required square.Second two terms is to remove the area which is outside our required region but inside the region calculated in the first step.Sum of elements of rows between 1 to i and columns between 1 to j is subtracted twice in the second step, so it is added once. First term denotes the sum of all the elements present in rows between 1 to i + x and columns between 1 to j + x. This area has our required square. Second two terms is to remove the area which is outside our required region but inside the region calculated in the first step. Sum of elements of rows between 1 to i and columns between 1 to j is subtracted twice in the second step, so it is added once. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int#define N 4 // Function to return the sum of the sub-matrixint getSum(int r1, int r2, int c1, int c2, int dp[N + 1][N + 1]){ return dp[r2][c2] - dp[r2][c1] - dp[r1][c2] + dp[r1][c1];} // Function that returns true if it is possible// to find the sub-matrix with required sumbool sumFound(int K, int S, int grid[N][N]){ // 2-D array to store the sum of // all the sub-matrices int dp[N + 1][N + 1]; // Filling of dp[][] array for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) dp[i + 1][j + 1] = dp[i + 1][j] + dp[i][j + 1] - dp[i][j] + grid[i][j]; // Checking for each possible sub-matrix of size k X k for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) { int sum = getSum(i, i + K, j, j + K, dp); if (sum == S) return true; } // Sub-matrix with the given sum not found return false;} // Driver codeint main(){ int grid[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; int K = 2; int S = 14; // Function call if (sumFound(K, S, grid)) cout << "Yes" << endl; else cout << "No" << endl;}// Modified by Kartik Verma // Java implementation of the approachclass GfG { static int N = 4; // Function to return the sum of the sub-matrix static int getSum(int r1, int r2, int c1, int c2, int dp[][]) { return dp[r2][c2] - dp[r2][c1] - dp[r1][c2] + dp[r1][c1]; } // Function that returns true if it is possible // to find the sub-matrix with required sum static boolean sumFound(int K, int S, int grid[][]) { // 2-D array to store the sum of // all the sub-matrices int dp[][] = new int[N + 1][N + 1]; // Filling of dp[][] array for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { dp[i + 1][j + 1] = dp[i + 1][j] + dp[i][j + 1] - dp[i][j] + grid[i][j]; } } // Checking for each possible sub-matrix of size k X // k for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { int sum = getSum(i, i + K, j, j + K, dp); if (sum == S) { return true; } } } // Sub-matrix with the given sum not found return false; } // Driver code public static void main(String[] args) { int grid[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; int K = 2; int S = 14; // Function call if (sumFound(K, S, grid)) { System.out.println("Yes"); } else { System.out.println("No"); } }} // This code contributed by Rajput-Ji// Modified by Kartik Verma # Python implementation of the approachN = 4 # Function to return the sum of the sub-matrix def getSum(r1, r2, c1, c2, dp): return dp[r2][c2] - dp[r2][c1] - dp[r1][c2] + dp[r1][c1] # Function that returns true if it is possible# to find the sub-matrix with required sumdef sumFound(K, S, grid): # 2-D array to store the sum of # all the sub-matrices dp = [[0 for i in range(N+1)] for j in range(N+1)] # Filling of dp[][] array for i in range(N): for j in range(N): dp[i + 1][j + 1] = dp[i + 1][j] + \ dp[i][j + 1] - dp[i][j] + grid[i][j] # Checking for each possible sub-matrix of size k X k for i in range(0, N): for j in range(0, N): sum = getSum(i, i + K, j, j + K, dp) if (sum == S): return True # Sub-matrix with the given sum not found return False # Driver codegrid = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]K = 2S = 14 # Function callif (sumFound(K, S, grid)): print("Yes")else: print("No") # This code is contributed by ankush_953# Modified by Kartik Verma // C# implementation of the approachusing System; class GfG { static int N = 4; // Function to return the sum of the sub-matrix static int getSum(int r1, int r2, int c1, int c2, int[, ] dp) { return dp[r2, c2] - dp[r2, c1] - dp[r1, c2] + dp[r1, c1]; } // Function that returns true if it is possible // to find the sub-matrix with required sum static bool sumFound(int K, int S, int[, ] grid) { // 2-D array to store the sum of // all the sub-matrices int[, ] dp = new int[N + 1, N + 1]; // Filling of dp[,] array for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { dp[i + 1, j + 1] = dp[i + 1, j] + dp[i, j + 1] - dp[i, j] + grid[i, j]; } } // Checking for each possible sub-matrix of size k X // k for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { int sum = getSum(i, i + K, j, j + K, dp); if (sum == S) { return true; } } } // Sub-matrix with the given sum not found return false; } // Driver code public static void Main(String[] args) { int[, ] grid = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; int K = 2; int S = 14; // Function call if (sumFound(K, S, grid)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } }} // This code has been contributed by 29AjayKumar// Modified by Kartik Verma <?php// PHP implementation of the approach $GLOBALS['N'] = 4; // Function to return the sum of// the sub-matrixfunction getSum($r1, $r2, $c1, $c2, $dp){ return $dp[$r2][$c2] - $dp[$r2][$c1] - $dp[$r1][$c2] + $dp[$r1][$c1];} // Function that returns true if it is// possible to find the sub-matrix with// required sumfunction sumFound($K, $S, $grid){ // 2-D array to store the sum of // all the sub-matrices $dp = array(array()); for ($i = 0; $i < $GLOBALS['N']; $i++) for ($j = 0; $j < $GLOBALS['N']; $j++) $dp[$i][$j] = 0 ; // Filling of dp[][] array for ($i = 0; $i < $GLOBALS['N']; $i++) for ($j = 0; $j < $GLOBALS['N']; $j++) $dp[$i + 1][$j + 1] = $dp[$i + 1][$j] + $dp[$i][$j + 1] - $dp[$i][$j] + $grid[$i][$j]; // Checking for each possible sub-matrix // of size k X k for ($i = 0; $i < $GLOBALS['N']; $i++) for ($j = 0; $j < $GLOBALS['N']; $j++) { $sum = getSum($i, $i + $K, $j, $j + $K, $dp); if ($sum == $S) return true; } // Sub-matrix with the given // sum not found return false;} // Driver code$grid = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16));$K = 2;$S = 14; // Function callif (sumFound($K, $S, $grid)) echo "Yes";else echo "No"; // This code is contributed by Ryuga//Modified by Kartik Verma?> <script> // Javascript implementation of the approach var N = 4 // Function to return the sum of the sub-matrixfunction getSum(r1, r2, c1, c2, dp){ return dp[r2][c2] - dp[r2][c1] - dp[r1][c2] + dp[r1][c1];} // Function that returns true if it is possible// to find the sub-matrix with required sumfunction sumFound(K, S, grid){ // 2-D array to store the sum of // all the sub-matrices var dp = Array.from(Array(N+1), ()=> Array(N+1).fill(0)); // Filling of dp[][] array for (var i = 0; i < N; i++) for (var j = 0; j < N; j++) dp[i + 1][j + 1] = dp[i + 1][j] + dp[i][j + 1] - dp[i][j] + grid[i][j]; // Checking for each possible sub-matrix of size k X k for (var i = 0; i < N; i++) for (var j = 0; j < N; j++) { var sum = getSum(i, i + K, j, j + K, dp); if (sum == S) return true; } // Sub-matrix with the given sum not found return false;} // Driver codevar grid = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ];var K = 2;var S = 14;// Function callif (sumFound(K, S, grid)) document.write( "Yes");else document.write( "No" ); </script> Yes ankthon Rajput-Ji 29AjayKumar ankush_953 kartik17158 itsok saurabh1990aror Dynamic Programming Matrix Dynamic Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimal Substructure Property in Dynamic Programming | DP-2 Count All Palindrome Sub-Strings in a String | Set 1 Min Cost Path | DP-6 Maximum sum such that no two elements are adjacent Optimal Strategy for a Game | DP-31 Program to find largest element in an array Print a given matrix in spiral form Rat in a Maze | Backtracking-2 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Sudoku | Backtracking-7
[ { "code": null, "e": 24696, "s": 24668, "text": "\n18 Aug, 2021" }, { "code": null, "e": 24825, "s": 24696, "text": "Given an N x N matrix and two integers S and K, the task is to find whether there exists a K x K sub-matrix with sum equal to S." }, { "code": null, "e": 24836, "s": 24825, "text": "Examples: " }, { "code": null, "e": 25016, "s": 24836, "text": "Input: K = 2, S = 14, mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }} Output: Yes 1 2 5 6 is the required 2 x 2 sub-matrix with element sum = 14" }, { "code": null, "e": 25076, "s": 25016, "text": "Input: K = 1, S = 5, mat[][] = {{1, 2}, {7, 8}} Output: No " }, { "code": null, "e": 25142, "s": 25076, "text": "Approach: Dynamic programming can be used to solve this problem, " }, { "code": null, "e": 25276, "s": 25142, "text": "Create an array dp[N + 1][N + 1] where dp[i][j] stores the sum of all the elements with row between 1 to i and column between 1 to j." }, { "code": null, "e": 25884, "s": 25276, "text": "Once the 2-D matrix is generated, now suppose we wish to find sum of square starting with (i, j) to (i + x, j + x). The required sum will be dp[i + x][j + x] – dp[i][j + x] – dp[i + x][j] + dp[i][j] where, First term denotes the sum of all the elements present in rows between 1 to i + x and columns between 1 to j + x. This area has our required square.Second two terms is to remove the area which is outside our required region but inside the region calculated in the first step.Sum of elements of rows between 1 to i and columns between 1 to j is subtracted twice in the second step, so it is added once." }, { "code": null, "e": 26286, "s": 25884, "text": "First term denotes the sum of all the elements present in rows between 1 to i + x and columns between 1 to j + x. This area has our required square.Second two terms is to remove the area which is outside our required region but inside the region calculated in the first step.Sum of elements of rows between 1 to i and columns between 1 to j is subtracted twice in the second step, so it is added once." }, { "code": null, "e": 26435, "s": 26286, "text": "First term denotes the sum of all the elements present in rows between 1 to i + x and columns between 1 to j + x. This area has our required square." }, { "code": null, "e": 26563, "s": 26435, "text": "Second two terms is to remove the area which is outside our required region but inside the region calculated in the first step." }, { "code": null, "e": 26690, "s": 26563, "text": "Sum of elements of rows between 1 to i and columns between 1 to j is subtracted twice in the second step, so it is added once." }, { "code": null, "e": 26742, "s": 26690, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26746, "s": 26742, "text": "C++" }, { "code": null, "e": 26751, "s": 26746, "text": "Java" }, { "code": null, "e": 26759, "s": 26751, "text": "Python3" }, { "code": null, "e": 26762, "s": 26759, "text": "C#" }, { "code": null, "e": 26766, "s": 26762, "text": "PHP" }, { "code": null, "e": 26777, "s": 26766, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int#define N 4 // Function to return the sum of the sub-matrixint getSum(int r1, int r2, int c1, int c2, int dp[N + 1][N + 1]){ return dp[r2][c2] - dp[r2][c1] - dp[r1][c2] + dp[r1][c1];} // Function that returns true if it is possible// to find the sub-matrix with required sumbool sumFound(int K, int S, int grid[N][N]){ // 2-D array to store the sum of // all the sub-matrices int dp[N + 1][N + 1]; // Filling of dp[][] array for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) dp[i + 1][j + 1] = dp[i + 1][j] + dp[i][j + 1] - dp[i][j] + grid[i][j]; // Checking for each possible sub-matrix of size k X k for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) { int sum = getSum(i, i + K, j, j + K, dp); if (sum == S) return true; } // Sub-matrix with the given sum not found return false;} // Driver codeint main(){ int grid[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; int K = 2; int S = 14; // Function call if (sumFound(K, S, grid)) cout << \"Yes\" << endl; else cout << \"No\" << endl;}// Modified by Kartik Verma", "e": 28192, "s": 26777, "text": null }, { "code": "// Java implementation of the approachclass GfG { static int N = 4; // Function to return the sum of the sub-matrix static int getSum(int r1, int r2, int c1, int c2, int dp[][]) { return dp[r2][c2] - dp[r2][c1] - dp[r1][c2] + dp[r1][c1]; } // Function that returns true if it is possible // to find the sub-matrix with required sum static boolean sumFound(int K, int S, int grid[][]) { // 2-D array to store the sum of // all the sub-matrices int dp[][] = new int[N + 1][N + 1]; // Filling of dp[][] array for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { dp[i + 1][j + 1] = dp[i + 1][j] + dp[i][j + 1] - dp[i][j] + grid[i][j]; } } // Checking for each possible sub-matrix of size k X // k for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { int sum = getSum(i, i + K, j, j + K, dp); if (sum == S) { return true; } } } // Sub-matrix with the given sum not found return false; } // Driver code public static void main(String[] args) { int grid[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; int K = 2; int S = 14; // Function call if (sumFound(K, S, grid)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } }} // This code contributed by Rajput-Ji// Modified by Kartik Verma", "e": 29949, "s": 28192, "text": null }, { "code": "# Python implementation of the approachN = 4 # Function to return the sum of the sub-matrix def getSum(r1, r2, c1, c2, dp): return dp[r2][c2] - dp[r2][c1] - dp[r1][c2] + dp[r1][c1] # Function that returns true if it is possible# to find the sub-matrix with required sumdef sumFound(K, S, grid): # 2-D array to store the sum of # all the sub-matrices dp = [[0 for i in range(N+1)] for j in range(N+1)] # Filling of dp[][] array for i in range(N): for j in range(N): dp[i + 1][j + 1] = dp[i + 1][j] + \\ dp[i][j + 1] - dp[i][j] + grid[i][j] # Checking for each possible sub-matrix of size k X k for i in range(0, N): for j in range(0, N): sum = getSum(i, i + K, j, j + K, dp) if (sum == S): return True # Sub-matrix with the given sum not found return False # Driver codegrid = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]K = 2S = 14 # Function callif (sumFound(K, S, grid)): print(\"Yes\")else: print(\"No\") # This code is contributed by ankush_953# Modified by Kartik Verma", "e": 31079, "s": 29949, "text": null }, { "code": "// C# implementation of the approachusing System; class GfG { static int N = 4; // Function to return the sum of the sub-matrix static int getSum(int r1, int r2, int c1, int c2, int[, ] dp) { return dp[r2, c2] - dp[r2, c1] - dp[r1, c2] + dp[r1, c1]; } // Function that returns true if it is possible // to find the sub-matrix with required sum static bool sumFound(int K, int S, int[, ] grid) { // 2-D array to store the sum of // all the sub-matrices int[, ] dp = new int[N + 1, N + 1]; // Filling of dp[,] array for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { dp[i + 1, j + 1] = dp[i + 1, j] + dp[i, j + 1] - dp[i, j] + grid[i, j]; } } // Checking for each possible sub-matrix of size k X // k for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { int sum = getSum(i, i + K, j, j + K, dp); if (sum == S) { return true; } } } // Sub-matrix with the given sum not found return false; } // Driver code public static void Main(String[] args) { int[, ] grid = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; int K = 2; int S = 14; // Function call if (sumFound(K, S, grid)) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } }} // This code has been contributed by 29AjayKumar// Modified by Kartik Verma", "e": 32853, "s": 31079, "text": null }, { "code": "<?php// PHP implementation of the approach $GLOBALS['N'] = 4; // Function to return the sum of// the sub-matrixfunction getSum($r1, $r2, $c1, $c2, $dp){ return $dp[$r2][$c2] - $dp[$r2][$c1] - $dp[$r1][$c2] + $dp[$r1][$c1];} // Function that returns true if it is// possible to find the sub-matrix with// required sumfunction sumFound($K, $S, $grid){ // 2-D array to store the sum of // all the sub-matrices $dp = array(array()); for ($i = 0; $i < $GLOBALS['N']; $i++) for ($j = 0; $j < $GLOBALS['N']; $j++) $dp[$i][$j] = 0 ; // Filling of dp[][] array for ($i = 0; $i < $GLOBALS['N']; $i++) for ($j = 0; $j < $GLOBALS['N']; $j++) $dp[$i + 1][$j + 1] = $dp[$i + 1][$j] + $dp[$i][$j + 1] - $dp[$i][$j] + $grid[$i][$j]; // Checking for each possible sub-matrix // of size k X k for ($i = 0; $i < $GLOBALS['N']; $i++) for ($j = 0; $j < $GLOBALS['N']; $j++) { $sum = getSum($i, $i + $K, $j, $j + $K, $dp); if ($sum == $S) return true; } // Sub-matrix with the given // sum not found return false;} // Driver code$grid = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16));$K = 2;$S = 14; // Function callif (sumFound($K, $S, $grid)) echo \"Yes\";else echo \"No\"; // This code is contributed by Ryuga//Modified by Kartik Verma?>", "e": 34452, "s": 32853, "text": null }, { "code": "<script> // Javascript implementation of the approach var N = 4 // Function to return the sum of the sub-matrixfunction getSum(r1, r2, c1, c2, dp){ return dp[r2][c2] - dp[r2][c1] - dp[r1][c2] + dp[r1][c1];} // Function that returns true if it is possible// to find the sub-matrix with required sumfunction sumFound(K, S, grid){ // 2-D array to store the sum of // all the sub-matrices var dp = Array.from(Array(N+1), ()=> Array(N+1).fill(0)); // Filling of dp[][] array for (var i = 0; i < N; i++) for (var j = 0; j < N; j++) dp[i + 1][j + 1] = dp[i + 1][j] + dp[i][j + 1] - dp[i][j] + grid[i][j]; // Checking for each possible sub-matrix of size k X k for (var i = 0; i < N; i++) for (var j = 0; j < N; j++) { var sum = getSum(i, i + K, j, j + K, dp); if (sum == S) return true; } // Sub-matrix with the given sum not found return false;} // Driver codevar grid = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ];var K = 2;var S = 14;// Function callif (sumFound(K, S, grid)) document.write( \"Yes\");else document.write( \"No\" ); </script>", "e": 35720, "s": 34452, "text": null }, { "code": null, "e": 35724, "s": 35720, "text": "Yes" }, { "code": null, "e": 35734, "s": 35726, "text": "ankthon" }, { "code": null, "e": 35744, "s": 35734, "text": "Rajput-Ji" }, { "code": null, "e": 35756, "s": 35744, "text": "29AjayKumar" }, { "code": null, "e": 35767, "s": 35756, "text": "ankush_953" }, { "code": null, "e": 35779, "s": 35767, "text": "kartik17158" }, { "code": null, "e": 35785, "s": 35779, "text": "itsok" }, { "code": null, "e": 35801, "s": 35785, "text": "saurabh1990aror" }, { "code": null, "e": 35821, "s": 35801, "text": "Dynamic Programming" }, { "code": null, "e": 35828, "s": 35821, "text": "Matrix" }, { "code": null, "e": 35848, "s": 35828, "text": "Dynamic Programming" }, { "code": null, "e": 35855, "s": 35848, "text": "Matrix" }, { "code": null, "e": 35953, "s": 35855, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36013, "s": 35953, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 36066, "s": 36013, "text": "Count All Palindrome Sub-Strings in a String | Set 1" }, { "code": null, "e": 36087, "s": 36066, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 36138, "s": 36087, "text": "Maximum sum such that no two elements are adjacent" }, { "code": null, "e": 36174, "s": 36138, "text": "Optimal Strategy for a Game | DP-31" }, { "code": null, "e": 36218, "s": 36174, "text": "Program to find largest element in an array" }, { "code": null, "e": 36254, "s": 36218, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 36285, "s": 36254, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 36347, "s": 36285, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" } ]
C Program to Store Information of Students Using Structure - GeeksforGeeks
18 Oct, 2019 Write a C program to store the information of Students using Structure. The information of each student to be stored is: Each Student Record should have: Name Roll Number Age Total Marks A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. ‘struct’ keyword is used to create the student structure as:struct Student { char* name; int roll_number; int age; double total_marks; }; struct Student { char* name; int roll_number; int age; double total_marks; }; Get the number of Students whose details are to be stored. Here we are taking 5 students for simplicity. Create a variable of Student structure to access the records. Here it is taken as ‘student’ Get the data of n students and store it in student’s fields with the help of dot (.) operatorSyntax:student[i].member = value; student[i].member = value; After all the data is stored, print the records of each students using the dot (.) operator and loop.Syntax:student[i].member; Syntax: student[i].member; Below is the implementation of the above approach: // C Program to Store Information// of Students Using Structure #include <stdio.h>#include <stdlib.h>#include <string.h> // Create the student structurestruct Student { char* name; int roll_number; int age; double total_marks;}; // Driver codeint main(){ int i = 0, n = 5; // Create the student's structure variable // with n Student's records struct Student student[n]; // Get the students data student[0].roll_number = 1; student[0].name = "Geeks1"; student[0].age = 12; student[0].total_marks = 78.50; student[1].roll_number = 5; student[1].name = "Geeks5"; student[1].age = 10; student[1].total_marks = 56.84; student[2].roll_number = 2; student[2].name = "Geeks2"; student[2].age = 11; student[2].total_marks = 87.94; student[3].roll_number = 4; student[3].name = "Geeks4"; student[3].age = 12; student[3].total_marks = 89.78; student[4].roll_number = 3; student[4].name = "Geeks3"; student[4].age = 13; student[4].total_marks = 78.55; // Print the Students information printf("Student Records:\n\n"); for (i = 0; i < n; i++) { printf("\tName = %s\n", student[i].name); printf("\tRoll Number = %d\n", student[i].roll_number); printf("\tAge = %d\n", student[i].age); printf("\tTotal Marks = %0.2f\n\n", student[i].total_marks); } return 0;} Student Records: Name = Geeks1 Roll Number = 1 Age = 12 Total Marks = 78.50 Name = Geeks5 Roll Number = 5 Age = 10 Total Marks = 56.84 Name = Geeks2 Roll Number = 2 Age = 11 Total Marks = 87.94 Name = Geeks4 Roll Number = 4 Age = 12 Total Marks = 89.78 Name = Geeks3 Roll Number = 3 Age = 13 Total Marks = 78.55 C-Structure & Union C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Regular expressions in C Conditional wait and signal in multi-threading Handling multiple clients on server with multithreading using Socket Programming in C/C++ C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7 C Hello World Program Difference between break and continue statement in C
[ { "code": null, "e": 24954, "s": 24926, "text": "\n18 Oct, 2019" }, { "code": null, "e": 25075, "s": 24954, "text": "Write a C program to store the information of Students using Structure. The information of each student to be stored is:" }, { "code": null, "e": 25150, "s": 25075, "text": "Each Student Record should have:\n Name\n Roll Number\n Age\n Total Marks\n" }, { "code": null, "e": 25312, "s": 25150, "text": "A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type." }, { "code": null, "e": 25465, "s": 25312, "text": "‘struct’ keyword is used to create the student structure as:struct Student\n{ \n char* name; \n int roll_number;\n int age;\n double total_marks;\n};\n" }, { "code": null, "e": 25558, "s": 25465, "text": "struct Student\n{ \n char* name; \n int roll_number;\n int age;\n double total_marks;\n};\n" }, { "code": null, "e": 25663, "s": 25558, "text": "Get the number of Students whose details are to be stored. Here we are taking 5 students for simplicity." }, { "code": null, "e": 25755, "s": 25663, "text": "Create a variable of Student structure to access the records. Here it is taken as ‘student’" }, { "code": null, "e": 25882, "s": 25755, "text": "Get the data of n students and store it in student’s fields with the help of dot (.) operatorSyntax:student[i].member = value;" }, { "code": null, "e": 25909, "s": 25882, "text": "student[i].member = value;" }, { "code": null, "e": 26036, "s": 25909, "text": "After all the data is stored, print the records of each students using the dot (.) operator and loop.Syntax:student[i].member;" }, { "code": null, "e": 26044, "s": 26036, "text": "Syntax:" }, { "code": null, "e": 26063, "s": 26044, "text": "student[i].member;" }, { "code": null, "e": 26114, "s": 26063, "text": "Below is the implementation of the above approach:" }, { "code": "// C Program to Store Information// of Students Using Structure #include <stdio.h>#include <stdlib.h>#include <string.h> // Create the student structurestruct Student { char* name; int roll_number; int age; double total_marks;}; // Driver codeint main(){ int i = 0, n = 5; // Create the student's structure variable // with n Student's records struct Student student[n]; // Get the students data student[0].roll_number = 1; student[0].name = \"Geeks1\"; student[0].age = 12; student[0].total_marks = 78.50; student[1].roll_number = 5; student[1].name = \"Geeks5\"; student[1].age = 10; student[1].total_marks = 56.84; student[2].roll_number = 2; student[2].name = \"Geeks2\"; student[2].age = 11; student[2].total_marks = 87.94; student[3].roll_number = 4; student[3].name = \"Geeks4\"; student[3].age = 12; student[3].total_marks = 89.78; student[4].roll_number = 3; student[4].name = \"Geeks3\"; student[4].age = 13; student[4].total_marks = 78.55; // Print the Students information printf(\"Student Records:\\n\\n\"); for (i = 0; i < n; i++) { printf(\"\\tName = %s\\n\", student[i].name); printf(\"\\tRoll Number = %d\\n\", student[i].roll_number); printf(\"\\tAge = %d\\n\", student[i].age); printf(\"\\tTotal Marks = %0.2f\\n\\n\", student[i].total_marks); } return 0;}", "e": 27508, "s": 26114, "text": null }, { "code": null, "e": 27906, "s": 27508, "text": "Student Records:\n\n Name = Geeks1\n Roll Number = 1\n Age = 12\n Total Marks = 78.50\n\n Name = Geeks5\n Roll Number = 5\n Age = 10\n Total Marks = 56.84\n\n Name = Geeks2\n Roll Number = 2\n Age = 11\n Total Marks = 87.94\n\n Name = Geeks4\n Roll Number = 4\n Age = 12\n Total Marks = 89.78\n\n Name = Geeks3\n Roll Number = 3\n Age = 13\n Total Marks = 78.55\n" }, { "code": null, "e": 27926, "s": 27906, "text": "C-Structure & Union" }, { "code": null, "e": 27937, "s": 27926, "text": "C Programs" }, { "code": null, "e": 28035, "s": 27937, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28076, "s": 28035, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 28107, "s": 28076, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 28148, "s": 28107, "text": "C program to find the length of a string" }, { "code": null, "e": 28182, "s": 28148, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 28207, "s": 28182, "text": "Regular expressions in C" }, { "code": null, "e": 28254, "s": 28207, "text": "Conditional wait and signal in multi-threading" }, { "code": null, "e": 28344, "s": 28254, "text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++" }, { "code": null, "e": 28415, "s": 28344, "text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 28437, "s": 28415, "text": "C Hello World Program" } ]
Optimization of a weekly production plan with Python and Gurobi — Part 3 | by Soulard Baptiste | Towards Data Science
We studied in the previous articles how to spread the workload between several production lines to meet the demand while reducing labour, inventory, and shortage costs. This model had some limitations and might not be used in a natural environment. Indeed, most of the time, the demand is a quantity to ship according to a list of customer orders. Also, the cycle time of each material is different. We will see here how to optimize the production schedule in this case. The idea of final assembly scheduling is to refine the daily demand by scheduling the production orders at a daily level. Our objective is to reduce the costs by smoothing the production load to reduce labour costs while producing just in time to reduce inventory and shortage costs. We are in a make-to-order scheme with three production lines in parallel. The factory is organised so that one-piece flow is always respected and all the tasks to produce a material are realised on the same line. Between 7 and 12 hours per day, each production line can be initiated at an extra cost charged as overtime work. We need to schedule the production orders to meet the requirement expressed by our list of customer orders. In addition to what we did in the previous articles, we will add the concept of cycle time for each product family that our factory is producing. This cycle time is used as an input through a matrix that shows the demonstrated capacity for an 8 hour shift. As the equipment varies from a line to another, the capability depends not only on the product family but also on the assembly line, as you can see below. How to propose a final assembly schedule that minimizes the cost based on these inputs? The algorithm presented in this article is based on the one presented in parts 1 and 2. In this article, we will only insist on the concepts newly introduced. Below is a summary of our problem that will be solved using Python and Gurobi solver. Inputs- Customer requirements- Capacity matrix- Labor cost per hour- Inventory cost per material per day- Shortage cost per material per dayVariables- x_qty[date, order, assembly line]: quantity of materials produced per day for each order on a given assembly line- x_time[date, order, assembly line]: working time per day for each order on a given assembly line. Defined according to the cycle time for each model.Constraints- Produce the quantity required by our customers- From 7 to 8 standard working hours per day- From 0 to 4 overtime working hours per dayObjective function to minimizeSum of all costs considered- Labor cost- Inventory cost- Shortage cost ‣ Extracting the data This time, to propose a model that better fits the need in a professional environment, the inputs are coming from an Excel file that could be extracted from our ERP. Our algorithm will read the customer’s requirement and generate the optimized production schedule in another Excel file using the same template. We will use the pandas’ library to fit this information and transform the data to use it in our optimization algorithm. The second Excel file used as an input is the demonstrated capacity of each line for each product. Ideally, all the assembly lines should have the same process and, thus, the same ability. However, it is not the case in our small assembly factory. The demonstrated capacity is not based on the theoretical routing times, and the losses due to a lack of efficiency are already considered. Here is the 8 hours capacity per line: Let’s now get the data from Excel and load it into a pandas data frame: The data presented previously and stored in two Excel files are not stored into the variable’s customer_orders and capacity. Moreover, to create our algorithm, we need to convert the capacity into the cycle time, i.e., the time required to produce one item. This information is stored in the variable cycle_time. After extracting these data from the local file, we need to set the labour, inventory, and shortage costs. This is done in the same way as for the previous articles and will not be shown here. Contrary to the previous articles, the calendar on which we operate is built based on the customer orders file. If you need it, you can find the code on my Git Hub. Now that we have access to all the information to treat, we will create the dictionaries to solve our model with the solver Gurobi. ‣ Creating the dictionaries First, we need to create a dictionary containing information related to cycle times. We want to know the time required to produce one unit of each order on each assembly line. As we do not know the cycle time for each order yet, we need to link the two data frames created in the first part of this article, i.e. customer orders and capacity data frames. We will also take this opportunity to format the date. We now have all the information necessary to build our dictionaries in one data frame. For the record, dictionaries are used to store data indexed by keys. As we need to know the time required to produce one unit of each order on each assembly line, the key used to index cycle times dictionary is the tuple (order, assembly line). To create the dictionary, we will look for the cycle time information into the customer_orders data frame and iterate each order and each assembly line. The output will be: cycle_times = {('A','Line_1'): 0.025, ('A','Line_2'): 0.0228, ... ,('L','Line_2'): 0.0228,('L','Line_3'): 0.025} Similarly, we create, the dictionary containing the daily requirements i.e. the customer’s need. daily_requirements = {('2020/07/13','A'): 600, ('2020/07/13','B'): 0, ... ,('2020/07/19','K'): 0, ('2020/07/19','L'): 200} At this point, we have managed to extract and refined the data we will use for our optimization problem. Let us now initiate to define our variables. Here is the main innovation compared to what we have done so far in the first two articles. In the previous articles, we were working in two dimensions, and our variable was the time spent working on each assembly line each day. This time we add one dimension, the order concerned by this variable. We have one main optimization variable x_qty and one slave variable x_time defined using the cycle_times dictionary. A tuple in three dimensions represents them. x_qty[date, order, assembly line]: quantity of items produced per day for each order on a given assembly line x_time[date, order, assembly line]: working time per day for each order on a given assembly line Apart from these new variables, we will use the variables defined in the previous articles. Here is a reminder of these variables: ‣ Time variables These variables are used to set the constraints on the working hours depending on the regulations in place in our factory. • reg_hours[date, assembly line]: regular working time on each assembly line • OT_hours[date, assembly line]: overtime working hours on each assembly line • line_opening[date, assembly line]: binary variable telling if an assembly line is opened each day • total_hours[date, assembly line]: total working hours on each assembly line. It is the sum of regular and overtime working hours on the days the line is opened. ‣ Quantity variables These variables are used to calculate inventory and shortage costs. • early_prod[date, order]: quantity of items produced early for each order • late_prod[date, order]: quantity of items produced late for each order As seen in the introduction, we have some constraints on the daily working time which is a hindrance to meet our customer’s requirement. The constraints on the limitation of working hours have been set in the definition of each variable by setting the lower and upper boundaries to match with the regulation. To meet our customer’s demand, we want to produce the exact quantity ordered. To do so, we will set the following constraint: Our objective is to propose a cost-efficient schedule considering the labour cost, inventory cost, and shortage cost. We will add all these variables into our objective function and then minimize this function. After minimising the objective function, our optimisation algorithm returns the following production schedule: You can see in the graph below how the customer’s requirements have been spread between our production lines. We can notice that the production of each order is realised on the day it is required to minimise our inventory. This is not the case for order L as it represents only a few hours of production, and it is forbidden to open a line for less than 7 hours. The order L is produced on July 18th, and it will build an inventory of 200 pieces that will be shipped on July 19th. We can check that the limitations on the daily working time are respected. These limitations are defined accordingly to the local regulations. In our case, the regulations in place define a minimum working time of 7 hours and a maximum of 12 hours per day, 8 hours being the ideal working time for a load of 100%. These extremums are represented by the grey lines on the graph below. The daily working time on each line always falls between 7 and 12 hours, and the regulations are respected. Let us now display the inventory and shortages to expect with this schedule proposal. As seen in the production schedule, order L impacts our inventory level by adding 200 pieces of model 7 to store for one day. There is no late production, the customer’s requirements are met without any shortage. What if the customer’s requirement is too high to be handled on the first day? Let us discover how our scheduling optimization algorithm handles a significant customer order at the beginning of the timeframe. The planning below shows the production schedule proposed by our model if the volume of the first customer order is higher. In this example, the quantity of order A is 2000 while it was 600 pieces in our first test. This quantity can not be handled one day, even if our three lines are running fully. We can see that our model manages this type of request by proposing to produce these materials on the next day. It is more visible in the shortage report below, where we can see that we could not make 515 pieces. They will be produced on the 13th of July. Of course, this should not happen as it will negatively impact customer satisfaction. Through these three articles, we learned step by step how to formalize an optimization problem and how to solve it using Python and Gurobi solver. This methodology has been applied to a Make To Order factory that needs to schedule its production to reduce the costs, including labour, inventory, and shortages. All the constraints and all the costs have not been considered; some areas of improvement could be: Considering changeover time between the different model Modelling a more complex factory with various tasks to be performed on separate lines in a specific order towardsdatascience.com towardsdatascience.com The repository of this project on my GitHub : https://github.com/soulabat/Production-plan-optimization/tree/master/Planning_optimization_part1 Explanation of how SAP is using linear optimization in its modules for planning optimization: http://www.gurobi.com/pdfs/user-events/2017-frankfurt/SAP.pdf Gurobi documentation: https://www.gurobi.com/documentation/8.0/examples/workforce5_py.html Feel free to contact me if you need further information or if you want to exchange views on this subject. You can reach me on LinkedIn.
[ { "code": null, "e": 341, "s": 172, "text": "We studied in the previous articles how to spread the workload between several production lines to meet the demand while reducing labour, inventory, and shortage costs." }, { "code": null, "e": 572, "s": 341, "text": "This model had some limitations and might not be used in a natural environment. Indeed, most of the time, the demand is a quantity to ship according to a list of customer orders. Also, the cycle time of each material is different." }, { "code": null, "e": 643, "s": 572, "text": "We will see here how to optimize the production schedule in this case." }, { "code": null, "e": 927, "s": 643, "text": "The idea of final assembly scheduling is to refine the daily demand by scheduling the production orders at a daily level. Our objective is to reduce the costs by smoothing the production load to reduce labour costs while producing just in time to reduce inventory and shortage costs." }, { "code": null, "e": 1253, "s": 927, "text": "We are in a make-to-order scheme with three production lines in parallel. The factory is organised so that one-piece flow is always respected and all the tasks to produce a material are realised on the same line. Between 7 and 12 hours per day, each production line can be initiated at an extra cost charged as overtime work." }, { "code": null, "e": 1361, "s": 1253, "text": "We need to schedule the production orders to meet the requirement expressed by our list of customer orders." }, { "code": null, "e": 1773, "s": 1361, "text": "In addition to what we did in the previous articles, we will add the concept of cycle time for each product family that our factory is producing. This cycle time is used as an input through a matrix that shows the demonstrated capacity for an 8 hour shift. As the equipment varies from a line to another, the capability depends not only on the product family but also on the assembly line, as you can see below." }, { "code": null, "e": 1861, "s": 1773, "text": "How to propose a final assembly schedule that minimizes the cost based on these inputs?" }, { "code": null, "e": 2020, "s": 1861, "text": "The algorithm presented in this article is based on the one presented in parts 1 and 2. In this article, we will only insist on the concepts newly introduced." }, { "code": null, "e": 2106, "s": 2020, "text": "Below is a summary of our problem that will be solved using Python and Gurobi solver." }, { "code": null, "e": 2769, "s": 2106, "text": "Inputs- Customer requirements- Capacity matrix- Labor cost per hour- Inventory cost per material per day- Shortage cost per material per dayVariables- x_qty[date, order, assembly line]: quantity of materials produced per day for each order on a given assembly line- x_time[date, order, assembly line]: working time per day for each order on a given assembly line. Defined according to the cycle time for each model.Constraints- Produce the quantity required by our customers- From 7 to 8 standard working hours per day- From 0 to 4 overtime working hours per dayObjective function to minimizeSum of all costs considered- Labor cost- Inventory cost- Shortage cost" }, { "code": null, "e": 2791, "s": 2769, "text": "‣ Extracting the data" }, { "code": null, "e": 3102, "s": 2791, "text": "This time, to propose a model that better fits the need in a professional environment, the inputs are coming from an Excel file that could be extracted from our ERP. Our algorithm will read the customer’s requirement and generate the optimized production schedule in another Excel file using the same template." }, { "code": null, "e": 3222, "s": 3102, "text": "We will use the pandas’ library to fit this information and transform the data to use it in our optimization algorithm." }, { "code": null, "e": 3470, "s": 3222, "text": "The second Excel file used as an input is the demonstrated capacity of each line for each product. Ideally, all the assembly lines should have the same process and, thus, the same ability. However, it is not the case in our small assembly factory." }, { "code": null, "e": 3649, "s": 3470, "text": "The demonstrated capacity is not based on the theoretical routing times, and the losses due to a lack of efficiency are already considered. Here is the 8 hours capacity per line:" }, { "code": null, "e": 3721, "s": 3649, "text": "Let’s now get the data from Excel and load it into a pandas data frame:" }, { "code": null, "e": 4034, "s": 3721, "text": "The data presented previously and stored in two Excel files are not stored into the variable’s customer_orders and capacity. Moreover, to create our algorithm, we need to convert the capacity into the cycle time, i.e., the time required to produce one item. This information is stored in the variable cycle_time." }, { "code": null, "e": 4227, "s": 4034, "text": "After extracting these data from the local file, we need to set the labour, inventory, and shortage costs. This is done in the same way as for the previous articles and will not be shown here." }, { "code": null, "e": 4392, "s": 4227, "text": "Contrary to the previous articles, the calendar on which we operate is built based on the customer orders file. If you need it, you can find the code on my Git Hub." }, { "code": null, "e": 4524, "s": 4392, "text": "Now that we have access to all the information to treat, we will create the dictionaries to solve our model with the solver Gurobi." }, { "code": null, "e": 4552, "s": 4524, "text": "‣ Creating the dictionaries" }, { "code": null, "e": 4728, "s": 4552, "text": "First, we need to create a dictionary containing information related to cycle times. We want to know the time required to produce one unit of each order on each assembly line." }, { "code": null, "e": 4962, "s": 4728, "text": "As we do not know the cycle time for each order yet, we need to link the two data frames created in the first part of this article, i.e. customer orders and capacity data frames. We will also take this opportunity to format the date." }, { "code": null, "e": 5049, "s": 4962, "text": "We now have all the information necessary to build our dictionaries in one data frame." }, { "code": null, "e": 5294, "s": 5049, "text": "For the record, dictionaries are used to store data indexed by keys. As we need to know the time required to produce one unit of each order on each assembly line, the key used to index cycle times dictionary is the tuple (order, assembly line)." }, { "code": null, "e": 5447, "s": 5294, "text": "To create the dictionary, we will look for the cycle time information into the customer_orders data frame and iterate each order and each assembly line." }, { "code": null, "e": 5467, "s": 5447, "text": "The output will be:" }, { "code": null, "e": 5580, "s": 5467, "text": "cycle_times = {('A','Line_1'): 0.025, ('A','Line_2'): 0.0228, ... ,('L','Line_2'): 0.0228,('L','Line_3'): 0.025}" }, { "code": null, "e": 5677, "s": 5580, "text": "Similarly, we create, the dictionary containing the daily requirements i.e. the customer’s need." }, { "code": null, "e": 5800, "s": 5677, "text": "daily_requirements = {('2020/07/13','A'): 600, ('2020/07/13','B'): 0, ... ,('2020/07/19','K'): 0, ('2020/07/19','L'): 200}" }, { "code": null, "e": 5950, "s": 5800, "text": "At this point, we have managed to extract and refined the data we will use for our optimization problem. Let us now initiate to define our variables." }, { "code": null, "e": 6042, "s": 5950, "text": "Here is the main innovation compared to what we have done so far in the first two articles." }, { "code": null, "e": 6249, "s": 6042, "text": "In the previous articles, we were working in two dimensions, and our variable was the time spent working on each assembly line each day. This time we add one dimension, the order concerned by this variable." }, { "code": null, "e": 6411, "s": 6249, "text": "We have one main optimization variable x_qty and one slave variable x_time defined using the cycle_times dictionary. A tuple in three dimensions represents them." }, { "code": null, "e": 6521, "s": 6411, "text": "x_qty[date, order, assembly line]: quantity of items produced per day for each order on a given assembly line" }, { "code": null, "e": 6618, "s": 6521, "text": "x_time[date, order, assembly line]: working time per day for each order on a given assembly line" }, { "code": null, "e": 6749, "s": 6618, "text": "Apart from these new variables, we will use the variables defined in the previous articles. Here is a reminder of these variables:" }, { "code": null, "e": 6766, "s": 6749, "text": "‣ Time variables" }, { "code": null, "e": 6889, "s": 6766, "text": "These variables are used to set the constraints on the working hours depending on the regulations in place in our factory." }, { "code": null, "e": 7308, "s": 6889, "text": " • reg_hours[date, assembly line]: regular working time on each assembly line • OT_hours[date, assembly line]: overtime working hours on each assembly line • line_opening[date, assembly line]: binary variable telling if an assembly line is opened each day • total_hours[date, assembly line]: total working hours on each assembly line. It is the sum of regular and overtime working hours on the days the line is opened." }, { "code": null, "e": 7329, "s": 7308, "text": "‣ Quantity variables" }, { "code": null, "e": 7397, "s": 7329, "text": "These variables are used to calculate inventory and shortage costs." }, { "code": null, "e": 7546, "s": 7397, "text": " • early_prod[date, order]: quantity of items produced early for each order • late_prod[date, order]: quantity of items produced late for each order" }, { "code": null, "e": 7683, "s": 7546, "text": "As seen in the introduction, we have some constraints on the daily working time which is a hindrance to meet our customer’s requirement." }, { "code": null, "e": 7855, "s": 7683, "text": "The constraints on the limitation of working hours have been set in the definition of each variable by setting the lower and upper boundaries to match with the regulation." }, { "code": null, "e": 7981, "s": 7855, "text": "To meet our customer’s demand, we want to produce the exact quantity ordered. To do so, we will set the following constraint:" }, { "code": null, "e": 8192, "s": 7981, "text": "Our objective is to propose a cost-efficient schedule considering the labour cost, inventory cost, and shortage cost. We will add all these variables into our objective function and then minimize this function." }, { "code": null, "e": 8303, "s": 8192, "text": "After minimising the objective function, our optimisation algorithm returns the following production schedule:" }, { "code": null, "e": 8526, "s": 8303, "text": "You can see in the graph below how the customer’s requirements have been spread between our production lines. We can notice that the production of each order is realised on the day it is required to minimise our inventory." }, { "code": null, "e": 8784, "s": 8526, "text": "This is not the case for order L as it represents only a few hours of production, and it is forbidden to open a line for less than 7 hours. The order L is produced on July 18th, and it will build an inventory of 200 pieces that will be shipped on July 19th." }, { "code": null, "e": 8927, "s": 8784, "text": "We can check that the limitations on the daily working time are respected. These limitations are defined accordingly to the local regulations." }, { "code": null, "e": 9168, "s": 8927, "text": "In our case, the regulations in place define a minimum working time of 7 hours and a maximum of 12 hours per day, 8 hours being the ideal working time for a load of 100%. These extremums are represented by the grey lines on the graph below." }, { "code": null, "e": 9276, "s": 9168, "text": "The daily working time on each line always falls between 7 and 12 hours, and the regulations are respected." }, { "code": null, "e": 9362, "s": 9276, "text": "Let us now display the inventory and shortages to expect with this schedule proposal." }, { "code": null, "e": 9575, "s": 9362, "text": "As seen in the production schedule, order L impacts our inventory level by adding 200 pieces of model 7 to store for one day. There is no late production, the customer’s requirements are met without any shortage." }, { "code": null, "e": 9654, "s": 9575, "text": "What if the customer’s requirement is too high to be handled on the first day?" }, { "code": null, "e": 9784, "s": 9654, "text": "Let us discover how our scheduling optimization algorithm handles a significant customer order at the beginning of the timeframe." }, { "code": null, "e": 10085, "s": 9784, "text": "The planning below shows the production schedule proposed by our model if the volume of the first customer order is higher. In this example, the quantity of order A is 2000 while it was 600 pieces in our first test. This quantity can not be handled one day, even if our three lines are running fully." }, { "code": null, "e": 10341, "s": 10085, "text": "We can see that our model manages this type of request by proposing to produce these materials on the next day. It is more visible in the shortage report below, where we can see that we could not make 515 pieces. They will be produced on the 13th of July." }, { "code": null, "e": 10427, "s": 10341, "text": "Of course, this should not happen as it will negatively impact customer satisfaction." }, { "code": null, "e": 10574, "s": 10427, "text": "Through these three articles, we learned step by step how to formalize an optimization problem and how to solve it using Python and Gurobi solver." }, { "code": null, "e": 10738, "s": 10574, "text": "This methodology has been applied to a Make To Order factory that needs to schedule its production to reduce the costs, including labour, inventory, and shortages." }, { "code": null, "e": 10838, "s": 10738, "text": "All the constraints and all the costs have not been considered; some areas of improvement could be:" }, { "code": null, "e": 10894, "s": 10838, "text": "Considering changeover time between the different model" }, { "code": null, "e": 11000, "s": 10894, "text": "Modelling a more complex factory with various tasks to be performed on separate lines in a specific order" }, { "code": null, "e": 11023, "s": 11000, "text": "towardsdatascience.com" }, { "code": null, "e": 11046, "s": 11023, "text": "towardsdatascience.com" }, { "code": null, "e": 11189, "s": 11046, "text": "The repository of this project on my GitHub : https://github.com/soulabat/Production-plan-optimization/tree/master/Planning_optimization_part1" }, { "code": null, "e": 11345, "s": 11189, "text": "Explanation of how SAP is using linear optimization in its modules for planning optimization: http://www.gurobi.com/pdfs/user-events/2017-frankfurt/SAP.pdf" }, { "code": null, "e": 11436, "s": 11345, "text": "Gurobi documentation: https://www.gurobi.com/documentation/8.0/examples/workforce5_py.html" } ]
Multi-Class Image Classification With Transfer Learning In PySpark | by Mohammed Innat | Towards Data Science
In this article, We’ll be using Keras (TensorFlow backend), PySpark, and Deep Learning Pipelines libraries to build an end-to-end deep learning computer vision solution for a multi-class image classification problem that runs on a Spark cluster. Spark is a robust open-source distributed analytics engine that can process large amounts of data with great speed. PySpark is the Python API for Spark that allows us to use Python programming language and leverage the power of Apache Spark. In this article, we’ll be using majorly Deep Learning Pipelines(DLP) which is a high-level Deep Learning framework that facilitates common Deep Learning workflows via the Spark MLlib Pipelines API. It currently supports TensorFlow and Keras with the TensorFlow-backend. In this article, We’ll be using this DLP to build a multi-class image classifier that will run on the Spark cluster. To get everything set up, please follow this installation instruction. docs.databricks.com The library comes from Databricks and leverages Spark for its two strongest facets: In the spirit of Spark and Spark MLlib, It provides easy-to-use APIs that enable deep learning in very few lines of code.It uses Spark’s powerful distributed engine to scale out deep learning on massive datasets. In the spirit of Spark and Spark MLlib, It provides easy-to-use APIs that enable deep learning in very few lines of code. It uses Spark’s powerful distributed engine to scale out deep learning on massive datasets. My goal is to integrate Deep Learning into the PySpark pipeline with the DLP. I’m running the entire project using Jupyter Notebook on my local machine to build the prototype. However, I found it a bit difficult to put together this prototype so I hope others will find this article useful. I’ll break down this project into a few steps. Some of the steps will be self-explanatory, but for others, I’ll try to explain as possible to make it painless. If you want to see just the notebook with explanations and code you can go directly to GitHub. Transfer Learning: A short intuition of Deep Learning Pipelines ( from Databricks ) Data Set: Introducing the multiclass image data. Modeling: Build a model and training. Evaluate: Evaluating the model performance using various evaluation metrics. Transfer learning is a technique in machine learning in general that focuses on saving knowledge (weights and biases) gained while solving one problem and further applying it to a different but related problem. Deep Learning Pipelines provide utilities to perform transfer learning on the images, which is one of the fastest ways to start using deep learning. With the concept of a Featurizer, Deep Learning Pipelines enables fast transfer learning on Spark-Cluster. Right now it provides the following neural nets for Transfer Learning: InceptionV3 Xception ResNet50 VGG16 VGG19 For demonstration purposes, we’ll work only on the InceptionV3 model. You can read the technical details of this model from here. The following example combines the InceptionV3 model and multinomial logistic regression in Spark. A utility function from Deep Learning Pipelines called DeepImageFeaturizer automatically peels off the last layer of a pre-trained neural network and uses the output from all the previous layers as features for the logistic regression algorithm. The Bengali script has ten numerical digits (graphemes or symbols indicating the numbers from 0 to 9). Numbers larger than 9 are written in Bengali using a positional base 10 numeral system. We choose NumtaDB as a source of our dataset. It’s a collection of Bengali Handwritten Digit data. The dataset contains more than 85,000 digits from over 2,700 contributors. But here we’re not planning to work on the whole data set rather than choose randomly 50 images of each class. Let’s look below what we’ve inside each above ten folders. I rename each image shown below of its corresponding class label for demonstration purposes. At first, we load all the images to SparkData Frame. Then we build the model and train it. After that, we’ll evaluate the performance of our trained model. The data sets (from 0 to 9) contain almost 500 handwritten Bangla digits (50 images each class). Here we manually load each image into a spark data frame with a target column. After loading the whole dataset we split into an 8:2 ratio randomly for the training set and final test set. Our goal is to train the model with the training data set and finally evaluate the model’s performance with the test dataset. # necessary import from pyspark.sql import SparkSessionfrom pyspark.ml.image import ImageSchemafrom pyspark.sql.functions import litfrom functools import reduce# create a spark sessionspark = SparkSession.builder.appName(‘DigitRecog’).getOrCreate()# loaded imagezero = ImageSchema.readImages("0").withColumn("label", lit(0))one = ImageSchema.readImages("1").withColumn("label", lit(1))two = ImageSchema.readImages("2").withColumn("label", lit(2))three = ImageSchema.readImages("3").withColumn("label", lit(3))four = ImageSchema.readImages("4").withColumn("label", lit(4))five = ImageSchema.readImages("5").withColumn("label", lit(5))six = ImageSchema.readImages("6").withColumn("label", lit(6))seven = ImageSchema.readImages("7").withColumn("label", lit(7))eight = ImageSchema.readImages("8").withColumn("label", lit(8))nine = ImageSchema.readImages("9").withColumn("label", lit(9))dataframes = [zero, one, two, three,four, five, six, seven, eight, nine]# merge data framedf = reduce(lambda first, second: first.union(second), dataframes)# repartition dataframe df = df.repartition(200)# split the data-frametrain, test = df.randomSplit([0.8, 0.2], 42) Here we can perform various Exploratory Data Analysis on Spark DataFrame. We can also view the schema of the data frame too. df.printSchema()root |-- image: struct (nullable = true) | |-- origin: string (nullable = true) | |-- height: integer (nullable = false) | |-- width: integer (nullable = false) | |-- nChannels: integer (nullable = false) | |-- mode: integer (nullable = false) | |-- data: binary (nullable = false) |-- label: integer (nullable = false) We can also convert Spark-DataFrame to Pandas-DataFrame using .toPandas(). Here we combine the InceptionV3 model and logistic regression in Spark. The DeepImageFeaturizer automatically peels off the last layer of a pre-trained neural network and uses the output from all the previous layers as features for the logistic regression algorithm. Since logistic regression is a simple and fast algorithm, this transfer learning training can converge quickly. from pyspark.ml.evaluation import MulticlassClassificationEvaluatorfrom pyspark.ml.classification import LogisticRegressionfrom pyspark.ml import Pipelinefrom sparkdl import DeepImageFeaturizer# model: InceptionV3# extracting feature from imagesfeaturizer = DeepImageFeaturizer(inputCol="image", outputCol="features", modelName="InceptionV3")# used as a multi class classifierlr = LogisticRegression(maxIter=5, regParam=0.03, elasticNetParam=0.5, labelCol="label")# define a pipeline modelsparkdn = Pipeline(stages=[featurizer, lr])spark_model = sparkdn.fit(train) # start fitting or training Now, It’s time to evaluate model performance. We now like to evaluate four evaluation metrics such as F1-score, Precision, Recall, Accuracy on the test data set. from pyspark.ml.evaluation import MulticlassClassificationEvaluator# evaluate the model with test setevaluator = MulticlassClassificationEvaluator() tx_test = spark_model.transform(test)print('F1-Score ', evaluator.evaluate(tx_test, {evaluator.metricName: 'f1'}))print('Precision ', evaluator.evaluate(tx_test, {evaluator.metricName: 'weightedPrecision'}))print('Recall ', evaluator.evaluate(tx_test, {evaluator.metricName: 'weightedRecall'}))print('Accuracy ', evaluator.evaluate(tx_test, {evaluator.metricName: 'accuracy'})) Here we get the result. It’s promising until now. F1-Score 0.8111782234361806Precision 0.8422058244785519Recall 0.8090909090909091Accuracy 0.8090909090909091 Here, we’ll summarize the performance of a classification model using the confusion matrix. import matplotlib.pyplot as pltimport numpy as npimport itertoolsdef plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.GnBu):plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes)fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black")plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') For this, we need to convert Spark-DataFrame to Pandas-DataFrame first and then call Confusion Matrix with true and predicted labels. from sklearn.metrics import confusion_matrixy_true = tx_test.select("label")y_true = y_true.toPandas()y_pred = tx_test.select("prediction")y_pred = y_pred.toPandas()cnf_matrix = confusion_matrix(y_true, y_pred,labels=range(10)) Let’s visualize the Confusion Matrix import seaborn as sns%matplotlib inlinesns.set_style("darkgrid")plt.figure(figsize=(7,7))plt.grid(False)# call pre defined functionplot_confusion_matrix(cnf_matrix, classes=range(10)) Here we can also get a report on the classification of each class by the evaluation matrix. from sklearn.metrics import classification_reporttarget_names = ["Class {}".format(i) for i in range(10)]print(classification_report(y_true, y_pred, target_names = target_names)) It’ll demonstrate much better the model performance for each class label prediction. precision recall f1-score support Class 0 1.00 0.92 0.96 13 Class 1 0.57 1.00 0.73 8 Class 2 0.64 1.00 0.78 7 Class 3 0.88 0.70 0.78 10 Class 4 0.90 1.00 0.95 9 Class 5 0.67 0.83 0.74 12 Class 6 0.83 0.62 0.71 8 Class 7 1.00 0.80 0.89 10 Class 8 1.00 0.80 0.89 20 Class 9 0.70 0.54 0.61 13 micro avg 0.81 0.81 0.81 110 macro avg 0.82 0.82 0.80 110weighted avg 0.84 0.81 0.81 110 Let’s also find the ROC AUC score point of this model. I’ve found the following piece of code from here. from sklearn.metrics import roc_curve, auc, roc_auc_scorefrom sklearn.preprocessing import LabelBinarizerdef multiclass_roc_auc_score(y_test, y_pred, average="macro"): lb = LabelBinarizer() lb.fit(y_test) y_test = lb.transform(y_test) y_pred = lb.transform(y_pred) return roc_auc_score(y_test, y_pred, average=average)print('ROC AUC score:', multiclass_roc_auc_score(y_true,y_pred)) It scores 0.901. Let’s see some of its predictions, comparison with the real label. # all columns after transformationsprint(tx_test.columns)# see some predicted outputtx_test.select('image', "prediction", "label").show() And, the result would be as follows ['image', 'label', 'features', 'rawPrediction', 'probability', 'prediction']+------------------+----------+--------+| image |prediction| label |+------------------+----------+--------+|[file:/home/i...| 1.0| 1||[file:/home/i...| 8.0| 8||[file:/home/i...| 9.0| 9||[file:/home/i...| 1.0| 8||[file:/home/i...| 1.0| 1||[file:/home/i...| 1.0| 9||[file:/home/i...| 0.0| 0||[file:/home/i...| 2.0| 9||[file:/home/i...| 8.0| 8||[file:/home/i...| 9.0| 9||[file:/home/i...| 0.0| 0||[file:/home/i...| 4.0| 0||[file:/home/i...| 5.0| 9||[file:/home/i...| 1.0| 1||[file:/home/i...| 9.0| 9||[file:/home/i...| 9.0| 9||[file:/home/i...| 1.0| 1||[file:/home/i...| 1.0| 1||[file:/home/i...| 9.0| 9||[file:/home/i...| 3.0| 6|+--------------------+----------+-----+only showing top 20 rows Though we’ve used an ImageNet weight our model performs pretty much promising to recognize handwritten digits. Moreover, we didn’t also perform any image processing tasks for better generalization. Also, the model is trained on very few amounts of data compared to the ImageNet dataset. At a very high level, each Spark apps consists of a driver program that launches various parallel operations on a cluster. The driver program contains our apps’ main function and defines distributed datasets on the cluster, then applies operations to them. This is a standalone application where we’ve linked the application to Spark first and then we imported the Spark packages in our program and create a SparkContext using SparkSession. Though we’ve worked on a single machine, we can connect the same shell to a cluster to train data in parallel. However, you can get the source code of today’s demonstration from the link below and can also follow me on GitHub for future code updates. :) github.com Next, We’ll do Distributed Hyperparameter Tuning with Spark, and will try the custom Keras model and some new challenging examples. Get in touch :) Say Hi On: Email | LinkedIn | Quora | GitHub | Twitter | Instagram Distributed DL with Keras & PySpark — Elephas Distributed Deep Learning Library for Apache Spark — BigDL TensorFlow to Apache Spark clusters — TensorFlowOnSpark Databricks: Deep Learning Guide Apache Spark: PySpark Machine Learning
[ { "code": null, "e": 660, "s": 172, "text": "In this article, We’ll be using Keras (TensorFlow backend), PySpark, and Deep Learning Pipelines libraries to build an end-to-end deep learning computer vision solution for a multi-class image classification problem that runs on a Spark cluster. Spark is a robust open-source distributed analytics engine that can process large amounts of data with great speed. PySpark is the Python API for Spark that allows us to use Python programming language and leverage the power of Apache Spark." }, { "code": null, "e": 1118, "s": 660, "text": "In this article, we’ll be using majorly Deep Learning Pipelines(DLP) which is a high-level Deep Learning framework that facilitates common Deep Learning workflows via the Spark MLlib Pipelines API. It currently supports TensorFlow and Keras with the TensorFlow-backend. In this article, We’ll be using this DLP to build a multi-class image classifier that will run on the Spark cluster. To get everything set up, please follow this installation instruction." }, { "code": null, "e": 1138, "s": 1118, "text": "docs.databricks.com" }, { "code": null, "e": 1222, "s": 1138, "text": "The library comes from Databricks and leverages Spark for its two strongest facets:" }, { "code": null, "e": 1435, "s": 1222, "text": "In the spirit of Spark and Spark MLlib, It provides easy-to-use APIs that enable deep learning in very few lines of code.It uses Spark’s powerful distributed engine to scale out deep learning on massive datasets." }, { "code": null, "e": 1557, "s": 1435, "text": "In the spirit of Spark and Spark MLlib, It provides easy-to-use APIs that enable deep learning in very few lines of code." }, { "code": null, "e": 1649, "s": 1557, "text": "It uses Spark’s powerful distributed engine to scale out deep learning on massive datasets." }, { "code": null, "e": 2195, "s": 1649, "text": "My goal is to integrate Deep Learning into the PySpark pipeline with the DLP. I’m running the entire project using Jupyter Notebook on my local machine to build the prototype. However, I found it a bit difficult to put together this prototype so I hope others will find this article useful. I’ll break down this project into a few steps. Some of the steps will be self-explanatory, but for others, I’ll try to explain as possible to make it painless. If you want to see just the notebook with explanations and code you can go directly to GitHub." }, { "code": null, "e": 2279, "s": 2195, "text": "Transfer Learning: A short intuition of Deep Learning Pipelines ( from Databricks )" }, { "code": null, "e": 2328, "s": 2279, "text": "Data Set: Introducing the multiclass image data." }, { "code": null, "e": 2366, "s": 2328, "text": "Modeling: Build a model and training." }, { "code": null, "e": 2443, "s": 2366, "text": "Evaluate: Evaluating the model performance using various evaluation metrics." }, { "code": null, "e": 2654, "s": 2443, "text": "Transfer learning is a technique in machine learning in general that focuses on saving knowledge (weights and biases) gained while solving one problem and further applying it to a different but related problem." }, { "code": null, "e": 2981, "s": 2654, "text": "Deep Learning Pipelines provide utilities to perform transfer learning on the images, which is one of the fastest ways to start using deep learning. With the concept of a Featurizer, Deep Learning Pipelines enables fast transfer learning on Spark-Cluster. Right now it provides the following neural nets for Transfer Learning:" }, { "code": null, "e": 2993, "s": 2981, "text": "InceptionV3" }, { "code": null, "e": 3002, "s": 2993, "text": "Xception" }, { "code": null, "e": 3011, "s": 3002, "text": "ResNet50" }, { "code": null, "e": 3017, "s": 3011, "text": "VGG16" }, { "code": null, "e": 3023, "s": 3017, "text": "VGG19" }, { "code": null, "e": 3153, "s": 3023, "text": "For demonstration purposes, we’ll work only on the InceptionV3 model. You can read the technical details of this model from here." }, { "code": null, "e": 3498, "s": 3153, "text": "The following example combines the InceptionV3 model and multinomial logistic regression in Spark. A utility function from Deep Learning Pipelines called DeepImageFeaturizer automatically peels off the last layer of a pre-trained neural network and uses the output from all the previous layers as features for the logistic regression algorithm." }, { "code": null, "e": 3689, "s": 3498, "text": "The Bengali script has ten numerical digits (graphemes or symbols indicating the numbers from 0 to 9). Numbers larger than 9 are written in Bengali using a positional base 10 numeral system." }, { "code": null, "e": 3974, "s": 3689, "text": "We choose NumtaDB as a source of our dataset. It’s a collection of Bengali Handwritten Digit data. The dataset contains more than 85,000 digits from over 2,700 contributors. But here we’re not planning to work on the whole data set rather than choose randomly 50 images of each class." }, { "code": null, "e": 4126, "s": 3974, "text": "Let’s look below what we’ve inside each above ten folders. I rename each image shown below of its corresponding class label for demonstration purposes." }, { "code": null, "e": 4282, "s": 4126, "text": "At first, we load all the images to SparkData Frame. Then we build the model and train it. After that, we’ll evaluate the performance of our trained model." }, { "code": null, "e": 4567, "s": 4282, "text": "The data sets (from 0 to 9) contain almost 500 handwritten Bangla digits (50 images each class). Here we manually load each image into a spark data frame with a target column. After loading the whole dataset we split into an 8:2 ratio randomly for the training set and final test set." }, { "code": null, "e": 4693, "s": 4567, "text": "Our goal is to train the model with the training data set and finally evaluate the model’s performance with the test dataset." }, { "code": null, "e": 5858, "s": 4693, "text": "# necessary import from pyspark.sql import SparkSessionfrom pyspark.ml.image import ImageSchemafrom pyspark.sql.functions import litfrom functools import reduce# create a spark sessionspark = SparkSession.builder.appName(‘DigitRecog’).getOrCreate()# loaded imagezero = ImageSchema.readImages(\"0\").withColumn(\"label\", lit(0))one = ImageSchema.readImages(\"1\").withColumn(\"label\", lit(1))two = ImageSchema.readImages(\"2\").withColumn(\"label\", lit(2))three = ImageSchema.readImages(\"3\").withColumn(\"label\", lit(3))four = ImageSchema.readImages(\"4\").withColumn(\"label\", lit(4))five = ImageSchema.readImages(\"5\").withColumn(\"label\", lit(5))six = ImageSchema.readImages(\"6\").withColumn(\"label\", lit(6))seven = ImageSchema.readImages(\"7\").withColumn(\"label\", lit(7))eight = ImageSchema.readImages(\"8\").withColumn(\"label\", lit(8))nine = ImageSchema.readImages(\"9\").withColumn(\"label\", lit(9))dataframes = [zero, one, two, three,four, five, six, seven, eight, nine]# merge data framedf = reduce(lambda first, second: first.union(second), dataframes)# repartition dataframe df = df.repartition(200)# split the data-frametrain, test = df.randomSplit([0.8, 0.2], 42)" }, { "code": null, "e": 5983, "s": 5858, "text": "Here we can perform various Exploratory Data Analysis on Spark DataFrame. We can also view the schema of the data frame too." }, { "code": null, "e": 6337, "s": 5983, "text": "df.printSchema()root |-- image: struct (nullable = true) | |-- origin: string (nullable = true) | |-- height: integer (nullable = false) | |-- width: integer (nullable = false) | |-- nChannels: integer (nullable = false) | |-- mode: integer (nullable = false) | |-- data: binary (nullable = false) |-- label: integer (nullable = false)" }, { "code": null, "e": 6412, "s": 6337, "text": "We can also convert Spark-DataFrame to Pandas-DataFrame using .toPandas()." }, { "code": null, "e": 6679, "s": 6412, "text": "Here we combine the InceptionV3 model and logistic regression in Spark. The DeepImageFeaturizer automatically peels off the last layer of a pre-trained neural network and uses the output from all the previous layers as features for the logistic regression algorithm." }, { "code": null, "e": 6791, "s": 6679, "text": "Since logistic regression is a simple and fast algorithm, this transfer learning training can converge quickly." }, { "code": null, "e": 7472, "s": 6791, "text": "from pyspark.ml.evaluation import MulticlassClassificationEvaluatorfrom pyspark.ml.classification import LogisticRegressionfrom pyspark.ml import Pipelinefrom sparkdl import DeepImageFeaturizer# model: InceptionV3# extracting feature from imagesfeaturizer = DeepImageFeaturizer(inputCol=\"image\", outputCol=\"features\", modelName=\"InceptionV3\")# used as a multi class classifierlr = LogisticRegression(maxIter=5, regParam=0.03, elasticNetParam=0.5, labelCol=\"label\")# define a pipeline modelsparkdn = Pipeline(stages=[featurizer, lr])spark_model = sparkdn.fit(train) # start fitting or training" }, { "code": null, "e": 7634, "s": 7472, "text": "Now, It’s time to evaluate model performance. We now like to evaluate four evaluation metrics such as F1-score, Precision, Recall, Accuracy on the test data set." }, { "code": null, "e": 8330, "s": 7634, "text": "from pyspark.ml.evaluation import MulticlassClassificationEvaluator# evaluate the model with test setevaluator = MulticlassClassificationEvaluator() tx_test = spark_model.transform(test)print('F1-Score ', evaluator.evaluate(tx_test, {evaluator.metricName: 'f1'}))print('Precision ', evaluator.evaluate(tx_test, {evaluator.metricName: 'weightedPrecision'}))print('Recall ', evaluator.evaluate(tx_test, {evaluator.metricName: 'weightedRecall'}))print('Accuracy ', evaluator.evaluate(tx_test, {evaluator.metricName: 'accuracy'}))" }, { "code": null, "e": 8380, "s": 8330, "text": "Here we get the result. It’s promising until now." }, { "code": null, "e": 8492, "s": 8380, "text": "F1-Score 0.8111782234361806Precision 0.8422058244785519Recall 0.8090909090909091Accuracy 0.8090909090909091" }, { "code": null, "e": 8584, "s": 8492, "text": "Here, we’ll summarize the performance of a classification model using the confusion matrix." }, { "code": null, "e": 9386, "s": 8584, "text": "import matplotlib.pyplot as pltimport numpy as npimport itertoolsdef plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.GnBu):plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes)fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment=\"center\", color=\"white\" if cm[i, j] > thresh else \"black\")plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label')" }, { "code": null, "e": 9520, "s": 9386, "text": "For this, we need to convert Spark-DataFrame to Pandas-DataFrame first and then call Confusion Matrix with true and predicted labels." }, { "code": null, "e": 9748, "s": 9520, "text": "from sklearn.metrics import confusion_matrixy_true = tx_test.select(\"label\")y_true = y_true.toPandas()y_pred = tx_test.select(\"prediction\")y_pred = y_pred.toPandas()cnf_matrix = confusion_matrix(y_true, y_pred,labels=range(10))" }, { "code": null, "e": 9785, "s": 9748, "text": "Let’s visualize the Confusion Matrix" }, { "code": null, "e": 9969, "s": 9785, "text": "import seaborn as sns%matplotlib inlinesns.set_style(\"darkgrid\")plt.figure(figsize=(7,7))plt.grid(False)# call pre defined functionplot_confusion_matrix(cnf_matrix, classes=range(10))" }, { "code": null, "e": 10061, "s": 9969, "text": "Here we can also get a report on the classification of each class by the evaluation matrix." }, { "code": null, "e": 10240, "s": 10061, "text": "from sklearn.metrics import classification_reporttarget_names = [\"Class {}\".format(i) for i in range(10)]print(classification_report(y_true, y_pred, target_names = target_names))" }, { "code": null, "e": 10325, "s": 10240, "text": "It’ll demonstrate much better the model performance for each class label prediction." }, { "code": null, "e": 11053, "s": 10325, "text": "precision recall f1-score support Class 0 1.00 0.92 0.96 13 Class 1 0.57 1.00 0.73 8 Class 2 0.64 1.00 0.78 7 Class 3 0.88 0.70 0.78 10 Class 4 0.90 1.00 0.95 9 Class 5 0.67 0.83 0.74 12 Class 6 0.83 0.62 0.71 8 Class 7 1.00 0.80 0.89 10 Class 8 1.00 0.80 0.89 20 Class 9 0.70 0.54 0.61 13 micro avg 0.81 0.81 0.81 110 macro avg 0.82 0.82 0.80 110weighted avg 0.84 0.81 0.81 110" }, { "code": null, "e": 11158, "s": 11053, "text": "Let’s also find the ROC AUC score point of this model. I’ve found the following piece of code from here." }, { "code": null, "e": 11556, "s": 11158, "text": "from sklearn.metrics import roc_curve, auc, roc_auc_scorefrom sklearn.preprocessing import LabelBinarizerdef multiclass_roc_auc_score(y_test, y_pred, average=\"macro\"): lb = LabelBinarizer() lb.fit(y_test) y_test = lb.transform(y_test) y_pred = lb.transform(y_pred) return roc_auc_score(y_test, y_pred, average=average)print('ROC AUC score:', multiclass_roc_auc_score(y_true,y_pred))" }, { "code": null, "e": 11573, "s": 11556, "text": "It scores 0.901." }, { "code": null, "e": 11640, "s": 11573, "text": "Let’s see some of its predictions, comparison with the real label." }, { "code": null, "e": 11778, "s": 11640, "text": "# all columns after transformationsprint(tx_test.columns)# see some predicted outputtx_test.select('image', \"prediction\", \"label\").show()" }, { "code": null, "e": 11814, "s": 11778, "text": "And, the result would be as follows" }, { "code": null, "e": 12774, "s": 11814, "text": "['image', 'label', 'features', 'rawPrediction', 'probability', 'prediction']+------------------+----------+--------+| image |prediction| label |+------------------+----------+--------+|[file:/home/i...| 1.0| 1||[file:/home/i...| 8.0| 8||[file:/home/i...| 9.0| 9||[file:/home/i...| 1.0| 8||[file:/home/i...| 1.0| 1||[file:/home/i...| 1.0| 9||[file:/home/i...| 0.0| 0||[file:/home/i...| 2.0| 9||[file:/home/i...| 8.0| 8||[file:/home/i...| 9.0| 9||[file:/home/i...| 0.0| 0||[file:/home/i...| 4.0| 0||[file:/home/i...| 5.0| 9||[file:/home/i...| 1.0| 1||[file:/home/i...| 9.0| 9||[file:/home/i...| 9.0| 9||[file:/home/i...| 1.0| 1||[file:/home/i...| 1.0| 1||[file:/home/i...| 9.0| 9||[file:/home/i...| 3.0| 6|+--------------------+----------+-----+only showing top 20 rows" }, { "code": null, "e": 13061, "s": 12774, "text": "Though we’ve used an ImageNet weight our model performs pretty much promising to recognize handwritten digits. Moreover, we didn’t also perform any image processing tasks for better generalization. Also, the model is trained on very few amounts of data compared to the ImageNet dataset." }, { "code": null, "e": 13318, "s": 13061, "text": "At a very high level, each Spark apps consists of a driver program that launches various parallel operations on a cluster. The driver program contains our apps’ main function and defines distributed datasets on the cluster, then applies operations to them." }, { "code": null, "e": 13613, "s": 13318, "text": "This is a standalone application where we’ve linked the application to Spark first and then we imported the Spark packages in our program and create a SparkContext using SparkSession. Though we’ve worked on a single machine, we can connect the same shell to a cluster to train data in parallel." }, { "code": null, "e": 13756, "s": 13613, "text": "However, you can get the source code of today’s demonstration from the link below and can also follow me on GitHub for future code updates. :)" }, { "code": null, "e": 13767, "s": 13756, "text": "github.com" }, { "code": null, "e": 13915, "s": 13767, "text": "Next, We’ll do Distributed Hyperparameter Tuning with Spark, and will try the custom Keras model and some new challenging examples. Get in touch :)" }, { "code": null, "e": 13982, "s": 13915, "text": "Say Hi On: Email | LinkedIn | Quora | GitHub | Twitter | Instagram" }, { "code": null, "e": 14028, "s": 13982, "text": "Distributed DL with Keras & PySpark — Elephas" }, { "code": null, "e": 14087, "s": 14028, "text": "Distributed Deep Learning Library for Apache Spark — BigDL" }, { "code": null, "e": 14143, "s": 14087, "text": "TensorFlow to Apache Spark clusters — TensorFlowOnSpark" }, { "code": null, "e": 14175, "s": 14143, "text": "Databricks: Deep Learning Guide" } ]
Python Program for Identity Matrix - GeeksforGeeks
13 Jan, 2022 Introduction to Identity Matrix : The dictionary definition of an Identity Matrix is a square matrix in which all the elements of the principal or main diagonal are 1’s and all other elements are zeros. In the below image, every matrix is an Identity Matrix. In linear algebra, this is sometimes called as a Unit Matrix, of a square matrix (size = n x n) with ones on the main diagonal and zeros elsewhere. The identity matrix is denoted by “ I “. Sometimes U or E is also used to denote an Identity Matrix. A property of the identity matrix is that it leaves a matrix unchanged if it is multiplied by an Identity Matrix. Examples: Input : 2 Output : 1 0 0 1 Input : 4 Output : 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 The explanation is simple. We need to make all the elements of principal or main diagonal as 1 and everything else as 0. Program to print Identity Matrix : The logic is simple. You need to the print 1 in those positions where row is equal to column of a matrix and make all other positions as 0. Python3 # Python code to print identity matrix # Function to print identity matrixdef Identity(size): for row in range(0, size): for col in range(0, size): # Here end is used to stay in same line if (row == col): print("1 ", end=" ") else: print("0 ", end=" ") print() # Driver Code size = 5Identity(size) Output: 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 Program to check if a given square matrix is Identity Matrix : Python3 # Python3 program to check # if a given matrix is identityMAX = 100;def isIdentity(mat, N): for row in range(N): for col in range(N): if (row == col and mat[row][col] != 1): return False; elif (row != col and mat[row][col] != 0): return False; return True; # Driver CodeN = 4;mat = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]; if (isIdentity(mat, N)): print("Yes ");else: print("No "); # This code is contributed# by mits Output: Yes Mathematical Matrix Python Python Programs School Programming Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 Check if a number is Palindrome Program to print prime numbers from 1 to N. Program to add two binary strings Program to multiply two matrices Matrix Chain Multiplication | DP-8 Program to find largest element in an array Print a given matrix in spiral form Sudoku | Backtracking-7 Rat in a Maze | Backtracking-2
[ { "code": null, "e": 24301, "s": 24273, "text": "\n13 Jan, 2022" }, { "code": null, "e": 24335, "s": 24301, "text": "Introduction to Identity Matrix :" }, { "code": null, "e": 24563, "s": 24335, "text": " The dictionary definition of an Identity Matrix is a square matrix in which all the elements of the principal or main diagonal are 1’s and all other elements are zeros. In the below image, every matrix is an Identity Matrix. " }, { "code": null, "e": 24926, "s": 24563, "text": "In linear algebra, this is sometimes called as a Unit Matrix, of a square matrix (size = n x n) with ones on the main diagonal and zeros elsewhere. The identity matrix is denoted by “ I “. Sometimes U or E is also used to denote an Identity Matrix. A property of the identity matrix is that it leaves a matrix unchanged if it is multiplied by an Identity Matrix." }, { "code": null, "e": 24938, "s": 24926, "text": "Examples: " }, { "code": null, "e": 25177, "s": 24938, "text": "Input : 2\nOutput : 1 0\n 0 1\n\nInput : 4\nOutput : 1 0 0 0\n 0 1 0 0\n 0 0 1 0\n 0 0 0 1\nThe explanation is simple. We need to make all\nthe elements of principal or main diagonal as \n1 and everything else as 0." }, { "code": null, "e": 25353, "s": 25177, "text": "Program to print Identity Matrix : The logic is simple. You need to the print 1 in those positions where row is equal to column of a matrix and make all other positions as 0. " }, { "code": null, "e": 25361, "s": 25353, "text": "Python3" }, { "code": "# Python code to print identity matrix # Function to print identity matrixdef Identity(size): for row in range(0, size): for col in range(0, size): # Here end is used to stay in same line if (row == col): print(\"1 \", end=\" \") else: print(\"0 \", end=\" \") print() # Driver Code size = 5Identity(size)", "e": 25750, "s": 25361, "text": null }, { "code": null, "e": 25759, "s": 25750, "text": "Output: " }, { "code": null, "e": 25839, "s": 25759, "text": "1 0 0 0 0 \n0 1 0 0 0 \n0 0 1 0 0 \n0 0 0 1 0 \n0 0 0 0 1 " }, { "code": null, "e": 25904, "s": 25839, "text": " Program to check if a given square matrix is Identity Matrix : " }, { "code": null, "e": 25912, "s": 25904, "text": "Python3" }, { "code": "# Python3 program to check # if a given matrix is identityMAX = 100;def isIdentity(mat, N): for row in range(N): for col in range(N): if (row == col and mat[row][col] != 1): return False; elif (row != col and mat[row][col] != 0): return False; return True; # Driver CodeN = 4;mat = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]; if (isIdentity(mat, N)): print(\"Yes \");else: print(\"No \"); # This code is contributed# by mits", "e": 26472, "s": 25912, "text": null }, { "code": null, "e": 26480, "s": 26472, "text": "Output:" }, { "code": null, "e": 26484, "s": 26480, "text": "Yes" }, { "code": null, "e": 26499, "s": 26486, "text": "Mathematical" }, { "code": null, "e": 26506, "s": 26499, "text": "Matrix" }, { "code": null, "e": 26513, "s": 26506, "text": "Python" }, { "code": null, "e": 26529, "s": 26513, "text": "Python Programs" }, { "code": null, "e": 26548, "s": 26529, "text": "School Programming" }, { "code": null, "e": 26561, "s": 26548, "text": "Mathematical" }, { "code": null, "e": 26568, "s": 26561, "text": "Matrix" }, { "code": null, "e": 26666, "s": 26568, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26675, "s": 26666, "text": "Comments" }, { "code": null, "e": 26688, "s": 26675, "text": "Old Comments" }, { "code": null, "e": 26733, "s": 26688, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 26765, "s": 26733, "text": "Check if a number is Palindrome" }, { "code": null, "e": 26809, "s": 26765, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 26843, "s": 26809, "text": "Program to add two binary strings" }, { "code": null, "e": 26876, "s": 26843, "text": "Program to multiply two matrices" }, { "code": null, "e": 26911, "s": 26876, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 26955, "s": 26911, "text": "Program to find largest element in an array" }, { "code": null, "e": 26991, "s": 26955, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 27015, "s": 26991, "text": "Sudoku | Backtracking-7" } ]
Dart Programming - Variables
A variable is “a named space in the memory” that stores values. In other words, it acts a container for values in a program. Variable names are called identifiers. Following are the naming rules for an identifier − Identifiers cannot be keywords. Identifiers cannot be keywords. Identifiers can contain alphabets and numbers. Identifiers can contain alphabets and numbers. Identifiers cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign. Identifiers cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign. Variable names cannot begin with a number. Variable names cannot begin with a number. A variable must be declared before it is used. Dart uses the var keyword to achieve the same. The syntax for declaring a variable is as given below − var name = 'Smith'; All variables in dart store a reference to the value rather than containing the value. The variable called name contains a reference to a String object with a value of “Smith”. Dart supports type-checking by prefixing the variable name with the data type. Type-checking ensures that a variable holds only data specific to a data type. The syntax for the same is given below − String name = 'Smith'; int num = 10; Consider the following example − void main() { String name = 1; } The above snippet will result in a warning since the value assigned to the variable doesn’t match the variable’s data type. Warning: A value of type 'String' cannot be assigned to a variable of type 'int' All uninitialized variables have an initial value of null. This is because Dart considers all values as objects. The following example illustrates the same − void main() { int num; print(num); } Null Variables declared without a static type are implicitly declared as dynamic. Variables can be also declared using the dynamic keyword in place of the var keyword. The following example illustrates the same. void main() { dynamic x = "tom"; print(x); } tom The final and const keyword are used to declare constants. Dart prevents modifying the values of a variable declared using the final or const keyword. These keywords can be used in conjunction with the variable’s data type or instead of the var keyword. The const keyword is used to represent a compile-time constant. Variables declared using the const keyword are implicitly final. final variable_name OR final data_type variable_name const variable_name OR const data_type variable_name void main() { final val1 = 12; print(val1); } 12 void main() { const pi = 3.14; const area = pi*12*12; print("The output is ${area}"); } The above example declares two constants, pi and area, using the const keyword. The area variable’s value is a compile-time constant. The output is 452.15999999999997 Note − Only const variables can be used to compute a compile time constant. Compile-time constants are constants whose values will be determined at compile time Dart throws an exception if an attempt is made to modify variables declared with the final or const keyword. The example given below illustrates the same − void main() { final v1 = 12; const v2 = 13; v2 = 12; } The code given above will throw the following error as output − Unhandled exception: cannot assign to final variable 'v2='. NoSuchMethodError: cannot assign to final variable 'v2=' #0 NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:178) #1 main (file: Test.dart:5:3) #2 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261) #3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148) 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2740, "s": 2525, "text": "A variable is “a named space in the memory” that stores values. In other words, it acts a container for values in a program. Variable names are called identifiers. Following are the naming rules for an identifier −" }, { "code": null, "e": 2772, "s": 2740, "text": "Identifiers cannot be keywords." }, { "code": null, "e": 2804, "s": 2772, "text": "Identifiers cannot be keywords." }, { "code": null, "e": 2851, "s": 2804, "text": "Identifiers can contain alphabets and numbers." }, { "code": null, "e": 2898, "s": 2851, "text": "Identifiers can contain alphabets and numbers." }, { "code": null, "e": 3007, "s": 2898, "text": "Identifiers cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign." }, { "code": null, "e": 3116, "s": 3007, "text": "Identifiers cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign." }, { "code": null, "e": 3159, "s": 3116, "text": "Variable names cannot begin with a number." }, { "code": null, "e": 3202, "s": 3159, "text": "Variable names cannot begin with a number." }, { "code": null, "e": 3352, "s": 3202, "text": "A variable must be declared before it is used. Dart uses the var keyword to achieve the same. The syntax for declaring a variable is as given below −" }, { "code": null, "e": 3373, "s": 3352, "text": "var name = 'Smith';\n" }, { "code": null, "e": 3550, "s": 3373, "text": "All variables in dart store a reference to the value rather than containing the value. The variable called name contains a reference to a String object with a value of “Smith”." }, { "code": null, "e": 3749, "s": 3550, "text": "Dart supports type-checking by prefixing the variable name with the data type. Type-checking ensures that a variable holds only data specific to a data type. The syntax for the same is given below −" }, { "code": null, "e": 3788, "s": 3749, "text": "String name = 'Smith'; \nint num = 10;\n" }, { "code": null, "e": 3821, "s": 3788, "text": "Consider the following example −" }, { "code": null, "e": 3859, "s": 3821, "text": "void main() { \n String name = 1; \n}" }, { "code": null, "e": 3983, "s": 3859, "text": "The above snippet will result in a warning since the value assigned to the variable doesn’t match the variable’s data type." }, { "code": null, "e": 4066, "s": 3983, "text": "Warning: A value of type 'String' cannot be assigned to a variable of type 'int' \n" }, { "code": null, "e": 4225, "s": 4066, "text": "All uninitialized variables have an initial value of null. This is because Dart considers all values as objects. The following example illustrates the same −" }, { "code": null, "e": 4271, "s": 4225, "text": "void main() { \n int num; \n print(num); \n}" }, { "code": null, "e": 4278, "s": 4271, "text": "Null \n" }, { "code": null, "e": 4441, "s": 4278, "text": "Variables declared without a static type are implicitly declared as dynamic. Variables can be also declared using the dynamic keyword in place of the var keyword." }, { "code": null, "e": 4485, "s": 4441, "text": "The following example illustrates the same." }, { "code": null, "e": 4540, "s": 4485, "text": "void main() { \n dynamic x = \"tom\"; \n print(x); \n}" }, { "code": null, "e": 4545, "s": 4540, "text": "tom\n" }, { "code": null, "e": 4799, "s": 4545, "text": "The final and const keyword are used to declare constants. Dart prevents modifying the values of a variable declared using the final or const keyword. These keywords can be used in conjunction with the variable’s data type or instead of the var keyword." }, { "code": null, "e": 4929, "s": 4799, "text": "The const keyword is used to represent a compile-time constant. Variables declared using the const keyword are implicitly final." }, { "code": null, "e": 4950, "s": 4929, "text": "final variable_name\n" }, { "code": null, "e": 4953, "s": 4950, "text": "OR" }, { "code": null, "e": 4985, "s": 4953, "text": "final data_type variable_name\n" }, { "code": null, "e": 5006, "s": 4985, "text": "const variable_name\n" }, { "code": null, "e": 5009, "s": 5006, "text": "OR" }, { "code": null, "e": 5040, "s": 5009, "text": "const data_type variable_name\n" }, { "code": null, "e": 5095, "s": 5040, "text": "void main() { \n final val1 = 12; \n print(val1); \n}" }, { "code": null, "e": 5099, "s": 5095, "text": "12\n" }, { "code": null, "e": 5200, "s": 5099, "text": "void main() { \n const pi = 3.14; \n const area = pi*12*12; \n print(\"The output is ${area}\"); \n}" }, { "code": null, "e": 5334, "s": 5200, "text": "The above example declares two constants, pi and area, using the const keyword. The area variable’s value is a compile-time constant." }, { "code": null, "e": 5368, "s": 5334, "text": "The output is 452.15999999999997\n" }, { "code": null, "e": 5529, "s": 5368, "text": "Note − Only const variables can be used to compute a compile time constant. Compile-time constants are constants whose values will be determined at compile time" }, { "code": null, "e": 5685, "s": 5529, "text": "Dart throws an exception if an attempt is made to modify variables declared with the final or const keyword. The example given below illustrates the same −" }, { "code": null, "e": 5753, "s": 5685, "text": "void main() { \n final v1 = 12; \n const v2 = 13; \n v2 = 12; \n}" }, { "code": null, "e": 5817, "s": 5753, "text": "The code given above will throw the following error as output −" }, { "code": null, "e": 6218, "s": 5817, "text": "Unhandled exception: \ncannot assign to final variable 'v2='. \nNoSuchMethodError: cannot assign to final variable 'v2=' \n#0 NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:178) \n#1 main (file: Test.dart:5:3) \n#2 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261) \n#3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)\n" }, { "code": null, "e": 6253, "s": 6218, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6273, "s": 6253, "text": " Sriyank Siddhartha" }, { "code": null, "e": 6306, "s": 6273, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 6326, "s": 6306, "text": " Sriyank Siddhartha" }, { "code": null, "e": 6359, "s": 6326, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 6376, "s": 6359, "text": " Frahaan Hussain" }, { "code": null, "e": 6411, "s": 6376, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 6428, "s": 6411, "text": " Frahaan Hussain" }, { "code": null, "e": 6463, "s": 6428, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6483, "s": 6463, "text": " Pranjal Srivastava" }, { "code": null, "e": 6516, "s": 6483, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 6536, "s": 6516, "text": " Pranjal Srivastava" }, { "code": null, "e": 6543, "s": 6536, "text": " Print" }, { "code": null, "e": 6554, "s": 6543, "text": " Add Notes" } ]
What is different between constant and variable in C++?
Variable and constant are two commonly used mathematical concepts. Simply put, a variable is a value that is changing or that have the ability to change. A constant is a value which remains unchanged. For example, if you have a program that has a list of 10 radii and you want to calculate the area for all of these circles. To find the area of these circles, you'll write a program that will have a variable that will store the value of PI and this value will not change throughout the program. Such values can be declared as a constant. In the same example, if you're calculating the area in a loop, you can use the same variable to temporarily store the value of the area and print it and then reuse it for some other calculation. The code for the above will look something like − float area; const float PI = 3.141; for(int i = 0; i < 10; i++) { area = PI * radii[i] * radii[i]; // Calculate area cout << area; // Print area } The value of PI remains same throughout the life of this program.
[ { "code": null, "e": 1263, "s": 1062, "text": "Variable and constant are two commonly used mathematical concepts. Simply put, a variable is a value that is changing or that have the ability to change. A constant is a value which remains unchanged." }, { "code": null, "e": 1601, "s": 1263, "text": "For example, if you have a program that has a list of 10 radii and you want to calculate the area for all of these circles. To find the area of these circles, you'll write a program that will have a variable that will store the value of PI and this value will not change throughout the program. Such values can be declared as a constant." }, { "code": null, "e": 1846, "s": 1601, "text": "In the same example, if you're calculating the area in a loop, you can use the same variable to temporarily store the value of the area and print it and then reuse it for some other calculation. The code for the above will look something like −" }, { "code": null, "e": 2000, "s": 1846, "text": "float area;\nconst float PI = 3.141;\nfor(int i = 0; i < 10; i++) {\n area = PI * radii[i] * radii[i]; // Calculate area\n cout << area; // Print area\n}" }, { "code": null, "e": 2066, "s": 2000, "text": "The value of PI remains same throughout the life of this program." } ]
How to copy Docker images from one host to another without using a repository?
If you have a Docker image in your own local machine and you want that image to be copied into another machine, there are two ways to do that. The first is by pushing that image to a repository such as the ones in Dockerhub registry. You need to have an account in Dockerhub and then you can use the Docker push command to push the images on it. However, if you don’t want to go through all the hassles of creating an account, tagging the images, etc., there are other simple methods that you can use. Let’s check out all such methods in this article. Docker allows you to save images into tar files using the Docker save command. This will also compress the entire image and will allow you to share them easily and quickly. You can then use the Docker load command in another machine to load the Docker image back from the tar file. The commands to do so are - $ docker save -o <tar file path in source host machine> <image name> You can then copy this tar file using simple tools such as cp, rsync, scp, etc. or any other method that you prefer. Next, you can use the Docker load command to restore the image from this tar file. $ docker load -i <path to image tar file> You can also transfer your Docker images through SSH and bzip the content to compress it on the fly. The command to do so is - $ docker save <image> | bzip2 | \ ssh user@host 'bunzip2 | docker load' If you want to check how the transfer is taking place, you can use the pv through the pipe. $ docker save <image> | bzip2 | pv | \ ssh user@host 'bunzip2 | docker load' If you have two Docker machines - machine1 and machine2, you can copy the images using the following command. $ docker $(docker-machine config machine1) save <image> | docker $(docker-machine config machine2) load You can also use the DOCKER_HOST variable to copy images from one host to another. You will need the SSH credentials and both the users on the local and remote machines should be in the Docker group. $ docker save <image name>:<tag-name> | gzip | DOCKER_HOST=ssh://user@remotehost docker load You have another command-line utility called docker-push-ssh. It will help you to set up a private Docker registry which is temporary on the host server. It will then create an SSH tunnel from the localhost. Next, it will push the Docker image and automatically clean up. The advantage of using this method instead of the docker save command is that in this case only the new layers are always pushed to the server. This results in a faster upload. To do so, you will have to first install docker-push-ssh using the following pip command. $ pip install docker-push-ssh You can then use the one-line to push the image. $ docker-push-ssh -i ~/your-ssh-key [email protected] <docker-image> The Docker Machine scp was created to copy or transfer files from a particular Docker machine to another. It becomes extremely convenient in case you want to copy images from the local machine to a remote Docker machine on cloud such as AWS or Digital Ocean. This is so because the Docker Machine will automatically take care of the SSH credentials. To do so, you can follow these steps - Use Docker save command. $ docker save -o <tar-file-location> <image name> Transfer Docker Images using docker machine scp. $ docker-machine scp ./image-tar.tar target-machine:/home/ubuntu Here, target-machine is the name of the remote machine, /home/ubuntu is the target location, and image-tar is the name of the tar file. Load the tar file. $ docker-machine ssh target-machine sudo docker load -i image-tar.tar To sum up, in this article, we discussed 6 different methods using which you can copy or transfer Docker images from one local machine to another remote machine without the use of any Docker registry or repository. As per your convenience and requirements, you can easily use any of the discussed methods.
[ { "code": null, "e": 1408, "s": 1062, "text": "If you have a Docker image in your own local machine and you want that image to be copied into another machine, there are two ways to do that. The first is by pushing that image to a repository such as the ones in Dockerhub registry. You need to have an account in Dockerhub and then you can use the Docker push command to push the images on it." }, { "code": null, "e": 1614, "s": 1408, "text": "However, if you don’t want to go through all the hassles of creating an account, tagging the images, etc., there are other simple methods that you can use. Let’s check out all such methods in this article." }, { "code": null, "e": 1924, "s": 1614, "text": "Docker allows you to save images into tar files using the Docker save command. This will also compress the entire image and will allow you to share them easily and quickly. You can then use the Docker load command in another machine to load the Docker image back from the tar file. The commands to do so are -" }, { "code": null, "e": 1993, "s": 1924, "text": "$ docker save -o <tar file path in source host machine> <image name>" }, { "code": null, "e": 2193, "s": 1993, "text": "You can then copy this tar file using simple tools such as cp, rsync, scp, etc. or any other method that you prefer. Next, you can use the Docker load command to restore the image from this tar file." }, { "code": null, "e": 2235, "s": 2193, "text": "$ docker load -i <path to image tar file>" }, { "code": null, "e": 2362, "s": 2235, "text": "You can also transfer your Docker images through SSH and bzip the content to compress it on the fly. The command to do so is -" }, { "code": null, "e": 2437, "s": 2362, "text": "$ docker save <image> | bzip2 | \\\n ssh user@host 'bunzip2 | docker load'" }, { "code": null, "e": 2529, "s": 2437, "text": "If you want to check how the transfer is taking place, you can use the pv through the pipe." }, { "code": null, "e": 2609, "s": 2529, "text": "$ docker save <image> | bzip2 | pv | \\\n ssh user@host 'bunzip2 | docker load'" }, { "code": null, "e": 2719, "s": 2609, "text": "If you have two Docker machines - machine1 and machine2, you can copy the images using the following command." }, { "code": null, "e": 2823, "s": 2719, "text": "$ docker $(docker-machine config machine1) save <image> | docker $(docker-machine config machine2) load" }, { "code": null, "e": 3023, "s": 2823, "text": "You can also use the DOCKER_HOST variable to copy images from one host to another. You will need the SSH credentials and both the users on the local and remote machines should be in the Docker group." }, { "code": null, "e": 3116, "s": 3023, "text": "$ docker save <image name>:<tag-name> | gzip | DOCKER_HOST=ssh://user@remotehost docker load" }, { "code": null, "e": 3388, "s": 3116, "text": "You have another command-line utility called docker-push-ssh. It will help you to set up a private Docker registry which is temporary on the host server. It will then create an SSH tunnel from the localhost. Next, it will push the Docker image and automatically clean up." }, { "code": null, "e": 3565, "s": 3388, "text": "The advantage of using this method instead of the docker save command is that in this case only the new layers are always pushed to the server. This results in a faster upload." }, { "code": null, "e": 3655, "s": 3565, "text": "To do so, you will have to first install docker-push-ssh using the following pip command." }, { "code": null, "e": 3686, "s": 3655, "text": "$ pip install docker-push-ssh\n" }, { "code": null, "e": 3735, "s": 3686, "text": "You can then use the one-line to push the image." }, { "code": null, "e": 3816, "s": 3735, "text": "$ docker-push-ssh -i ~/your-ssh-key [email protected] <docker-image>" }, { "code": null, "e": 4166, "s": 3816, "text": "The Docker Machine scp was created to copy or transfer files from a particular Docker machine to another. It becomes extremely convenient in case you want to copy images from the local machine to a remote Docker machine on cloud such as AWS or Digital Ocean. This is so because the Docker Machine will automatically take care of the SSH credentials." }, { "code": null, "e": 4205, "s": 4166, "text": "To do so, you can follow these steps -" }, { "code": null, "e": 4230, "s": 4205, "text": "Use Docker save command." }, { "code": null, "e": 4280, "s": 4230, "text": "$ docker save -o <tar-file-location> <image name>" }, { "code": null, "e": 4329, "s": 4280, "text": "Transfer Docker Images using docker machine scp." }, { "code": null, "e": 4394, "s": 4329, "text": "$ docker-machine scp ./image-tar.tar target-machine:/home/ubuntu" }, { "code": null, "e": 4530, "s": 4394, "text": "Here, target-machine is the name of the remote machine, /home/ubuntu is the target location, and image-tar is the name of the tar file." }, { "code": null, "e": 4549, "s": 4530, "text": "Load the tar file." }, { "code": null, "e": 4620, "s": 4549, "text": "$ docker-machine ssh target-machine sudo docker load -i image-tar.tar\n" }, { "code": null, "e": 4926, "s": 4620, "text": "To sum up, in this article, we discussed 6 different methods using which you can copy or transfer Docker images from one local machine to another remote machine without the use of any Docker registry or repository. As per your convenience and requirements, you can easily use any of the discussed methods." } ]
How do I print a Python datetime in the local timezone?
The easiest way in Python date and time to handle timezones is to use the pytz and tzlocal modules. These libraries allows accurate and cross platform timezone calculations. pytz brings the Olson tz database into Python. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference (datetime.tzinfo). Before you use it you'll need to install it using − $ pip install pytz tzlocal You can use the pytz library as follows − from datetime import datetime from pytz import timezone from tzlocal import get_localzone format = "%Y-%m-%d %H:%M:%S %Z%z" # Current time in UTC now_utc = datetime.now(timezone('UTC')) print(now_utc.strftime(format)) # Convert to local time zone now_local = now_utc.astimezone(get_localzone()) print(now_local.strftime(format)) This will give the output − 2018-01-03 07:05:50 UTC+0000 2018-01-03 12:35:50 IST+0530
[ { "code": null, "e": 1444, "s": 1062, "text": "The easiest way in Python date and time to handle timezones is to use the pytz and tzlocal modules. These libraries allows accurate and cross platform timezone calculations. pytz brings the Olson tz database into Python. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference (datetime.tzinfo)." }, { "code": null, "e": 1496, "s": 1444, "text": "Before you use it you'll need to install it using −" }, { "code": null, "e": 1523, "s": 1496, "text": "$ pip install pytz tzlocal" }, { "code": null, "e": 1565, "s": 1523, "text": "You can use the pytz library as follows −" }, { "code": null, "e": 1894, "s": 1565, "text": "from datetime import datetime\nfrom pytz import timezone\nfrom tzlocal import get_localzone\nformat = \"%Y-%m-%d %H:%M:%S %Z%z\"\n# Current time in UTC\nnow_utc = datetime.now(timezone('UTC'))\nprint(now_utc.strftime(format))\n# Convert to local time zone\nnow_local = now_utc.astimezone(get_localzone())\nprint(now_local.strftime(format))" }, { "code": null, "e": 1922, "s": 1894, "text": "This will give the output −" }, { "code": null, "e": 1980, "s": 1922, "text": "2018-01-03 07:05:50 UTC+0000\n2018-01-03 12:35:50 IST+0530" } ]
Reverse mapping an object in JavaScript
Suppose, we have an object like this − const products = { "Pineapple":38, "Apple":110, "Pear":109 }; All the keys are unique in themselves and all the values are unique in themselves. We are required to write a function that accepts a value and returns its key. Let' say we have created a function findKey(). For example, findKey(110) should return "Apple". We will approach this problem by first reverse mapping the values to keys and then simply using object notations to find their values. Therefore, let’s write the code for this function − The code for this will be − const products = { "Pineapple":38, "Apple":110, "Pear":109 }; const findKey = (obj, val) => { const res = {}; Object.keys(obj).map(key => { res[obj[key]] = key; }); // if the value is not present in the object // return false return res[val] || false; }; console.log(findKey(products, 110)); The output in the console will be − Apple
[ { "code": null, "e": 1101, "s": 1062, "text": "Suppose, we have an object like this −" }, { "code": null, "e": 1172, "s": 1101, "text": "const products = {\n \"Pineapple\":38,\n \"Apple\":110,\n \"Pear\":109\n};" }, { "code": null, "e": 1255, "s": 1172, "text": "All the keys are unique in themselves and all the values are unique in themselves." }, { "code": null, "e": 1380, "s": 1255, "text": "We are required to write a function that accepts a value and returns its key. Let' say we have created a function findKey()." }, { "code": null, "e": 1429, "s": 1380, "text": "For example, findKey(110) should return \"Apple\"." }, { "code": null, "e": 1564, "s": 1429, "text": "We will approach this problem by first reverse mapping the values to keys and then simply using object notations to find their values." }, { "code": null, "e": 1616, "s": 1564, "text": "Therefore, let’s write the code for this function −" }, { "code": null, "e": 1644, "s": 1616, "text": "The code for this will be −" }, { "code": null, "e": 1969, "s": 1644, "text": "const products = {\n \"Pineapple\":38,\n \"Apple\":110,\n \"Pear\":109\n};\nconst findKey = (obj, val) => {\n const res = {};\n Object.keys(obj).map(key => {\n res[obj[key]] = key;\n });\n // if the value is not present in the object\n // return false\n return res[val] || false;\n};\nconsole.log(findKey(products, 110));" }, { "code": null, "e": 2005, "s": 1969, "text": "The output in the console will be −" }, { "code": null, "e": 2011, "s": 2005, "text": "Apple" } ]
Overview: State-of-the-Art Machine Learning Algorithms per Discipline & per Task | by Hucker Marius | Towards Data Science
Machine Learning algorithms are on the rise. Every year new techniques are presented that outdate the current leading algorithms. Some of them are only little advances or combinations of existing algorithms and others are newly created and lead to astonishing progress. For most techniques exist already great articles that explain the theory behind it and some of them offer also an implementation with code and tutorial. None did yet offer an overview of the current leading algorithms, so the idea came up to present the best algorithms per task based on the results achieved (performance scores are used). Of course, there are many more tasks and not all tasks can be presented. I tried to select the most popular fields and tasks and hope this might help to get a better understanding. The metiers on which this article will lay a focus are Computer Vision, Natural Language Processing, Speech Recognition. All the fields, tasks and some of the algorithms are presented in the article. If you are interested only in a subpart, skip the to the section you want to dive in. Computer Vision is one of the most researched and most popular fields in machine learning. It is utilized to solve many everyday problems and consecutively involved in multiple applications, from which the most popular is currently the vision of self-driving cars. The tasks on which we’ll take a look are semantic segmentation, image classification and object detection. Semantic Segmentation can be seen as understanding the structures and components of an image on a pixel level. Methods for semantic segmentation try to make predictions about the structures and objects in an image. For a better understanding a semantic segmentation of a street scene can be seen below: The current leading algorithm HRNet-OCR was presented in 2020 by Tao et al. from Nvidia. It achieved a Mean Intersection Over Union (Mean IOU) of 85,1%. HRNet-OCR scales the image and uses a dense mask for each scale. The predictions of all scales are then “combined by performing pixel-wise multiplication between masks with the predictions followed by pixel-wise summation among the different scales to obtain the final results” [1]. Check out the Github to the technique:https://github.com/HRNet/HRNet-Semantic-Segmentation Other top-tier techniques (Method — Dataset): Efficient-Net-L2+NAS-FPN — PASCAL VOC ResNeSt-269 — PASCAL Context VMVF —ScanNet Other than Semantic Segmentation, Image Classification, does not focus on the areas on the image, but on the image as a whole. This discipline tries to classify each image by assigning a label. The FixEfficientNet has been presented first with the corresponding paper on the 20th April 2020 from the Facebook AI Research Team [2][3]. It is currently the state-of-the-art and has the best results on the ImageNet Dataset with 480M params, a top-1 accuracy of 88.5%, and top-5 accuracy of 98,7%. FixRes is the short form for Fix Resolution and tries to keep a fixed size for either the RoC (Region of Classification) used for train time or the crop used for test time. The EfficientNet is a compound scaling of the dimensions of a CNN which improves both accuracy and efficiency. For more information to the FixEfficientNet, read this. Other top-tier techniques (Method — Dataset): BiT-L — CIFAR-10 Wide-ResNet-101 — STL-10 Branching/Merging CNN + Homogeneous Filter Capsules — MNIST Object detection is the task of recognizing instances of objects of a certain class within an image. The current leading Object Detection technique is the Efficient-Det D7x first presented by the Google Brain Team (Tan et al.) in 2020 [4]. It achieved an AP50 (For more on AP50: Average Precision with a fixed IoU threshold at 50) of 74,3 and a box AP of 55,1. The Efficient-Det is a combination of EfficientNets with Bidirectional Feature Pyramid Networks (BiFPNs). As shortly explained above, the EfficientNet is a compound scaling of the dimensions of a CNN which improves both accuracy and efficiency. For more on EfficientNet, you can click here. In Computer Vision a typical approach to increase the accuracy is the creation of multiple copies of the same image with different resolutions. This results in a so-called Pyramid due to the arrangement of the smallest image as the top layer and the biggest image as the bottom layer. The Feature Pyramid Network represents such a pyramid. Bidirectional means that there is not only a top-down approach but simultaneously a bottom-up approach. Every bidirectional path is used as a feature network layer and this leads to the BiFPNs. It helps with increasing accuracy and speed. For more information on BiFPNs, click here. Other top-tier techniques (Method — Dataset): RODEO — PASCAL VOC Patch Refinement — KITTI Cars Easy IterDet — CrowdHuman A common definition for Natural Language Processing is the following: NLP is a subfield of AI that gives the machines the ability to read, understand and derive meaning from human languages. NLP tasks vary in a broad range and as the definition reveals, all of them try to deduct some meaning from our language and perform calculations based on our language and its components. Algorithms based on NLP can be found in various applications and industries. Just to name a few applications which you might encounter every day such as translators, social media monitoring, chatbots, spam filters, grammar check in Microsoft word or messengers and virtual assistants. Sentiment Analysis is a field of Text Mining and is used to interpret and classify emotions in text data. One of the current leading algorithms is BERT which achieved an accuracy of 55.5 on the SST-5 Fine-grained classification dataset in 2019. The original paper was published by the Google AI Team [5]. BERT stands for Bidirectional Encoder Representations from Transformers and applies a bidirectional training of the Transformer technique. Transformer technique is an attention model used for language modeling which was previously only applied in one direction. Either to parse a text from left-to-right or from right-to-left. For more details, read this great article. Other top-tier techniques (Method — Dataset): T5–3B — SST-2 Binary classification NB-weighted-BON + dv-cosine — IMDb Language Modeling is the task of predicting the next words or letters in a text based on the existing text/previous words.The GPT-2 model was given two sentences about a herd of unicorns living in the Andens and it created an astonishing story. You can read it here. In Language Modeling one of the best performing algorithms can be found in Megatron-LM. This model and the paper were first presented in 2019 by the Nvidia team. A model similar to GPT-2 was trained on 8300 billion params. It was able to reduce the current state-of-the-art score of 15.8 to a test perplexity of only 10.8. The dataset used was the WikiText103 [6]. The model makes use of the Transformer Network. In their work, a transformer layer is made up of a self-attention block followed by a two-layer, multi-layer perceptron (MLP). In each of the blocks, model parallelism is used. This helps to reduce communication and keeps the GPUs compute-bound. The computation of the GPUs is duplicated to increase the speed of the model. Other top-tier techniques (Method — Dataset): GPT-3 — Penn Treebank GPT-2 — WikiText2, Text8, enwik8 Machine Translation is used in applications such as Google Translate or www.deepl.com. It is used to translate a text in another language using an algorithm. One of the most promising algorithms in this field is the Transformer Big +BT. It was presented in this paper in 2018 by the Google Brain Team. In general, Transformers are state-of-the-art for dealing sequences and for machine translation. Transformers do not use recurrent connections but parse instead sequences simultaneously [7]. As you can see in the gif above the input and output differ. This is due to the two different languages, the input is for example in English, while the output language is german. For the sake of increasing speed parallelization is a key aspect of the model. This problem is tackled by using CNN together with attention models. The self-attention helps to increase the speed and the focus on certain words, while CNN is used for parallelization [8]. For more on transformers read this great article. The authors applied back-translation (BT) for their training. In this method, the training dataset is translated into the target language and the algorithm translates it back to the original language. The performance can then be observed perfectly [7]. Other top-tier techniques (Method — Dataset): MAT+Knee — IWSLT2014 German-English MADL — WMT2016 English-German Attentional encoder-decoder +BPE — WMT2016 German-English Text Classification is the task of assigning a certain category to a sentence, a text, or a word. The current leading algorithm on three different datasets (DBpedia, AG News and IMDb) is XLNet. The paper and the technique XLNet was first presented in 2019 by the Google AI Team. It improved the leading algorithm BERT in 20 tasks. The method that XLNet pioneered in is called Permutation Language Modeling. It makes use of a permutation of the words. Imagine you got 3 words in the following order [w1,w2,w3]. All permutations are then retrieved, here 3*2*1 = 6 permutations. Obviously, with long sentences, this leads to numerous permutations. All words positioned before the prediction word (e.g. w2) are used for prediction [9]: w3 w1 w2w1 w2 w3w1 w3 w2 ... In row 1, w3 and w1 are used for the prediction of w2. In row 2 only w1 is used for prediction and so on. To get a better understanding of the technique you can read more about it here. Other top-tier techniques (Method — Dataset): USE_T + CNN — TREC-6 SGC — 20News Question Answering is the task of training an algorithm to answer questions (often based on reading comprehension). This task is part of Transfer Learning due to the learning on a given text database and the storing of knowledge to answer the questions to a later point in time. With the T5–11B the Google AI Team achieved state-of-the-art benchmarks on four different datasets: GLUE, SuperGLUE, SQuAD and CNN/Daily Mail. T5 stands for the five T’s in Text-to-Text Transfer Transformer, while 11B stands for the 11 Billion Dataset with which the algorithm was trained. In contrast to BERT and other great algorithms the T5–11B does not output a label to the input sentence. Instead, as the name already shows, the output is a text string as well [10]. The authors of the paper have rigorously evaluated and refined dozens of existing NLP tasks to take the best ideas to their model. These included experiments on model architectures, pre-training objectives, unlabeled datasets, training strategies and scale as the authors describe [10]: model architectures, where we found that encoder-decoder models generally outperformed “decoder-only” language models; pre-training objectives, where we confirmed that fill-in-the-blank-style denoising objectives (where the model is trained to recover missing words in the input) worked best and that the most important factor was the computational cost; unlabeled datasets, where we showed that training on in-domain data can be beneficial but that pre-training on smaller datasets can lead to detrimental overfitting; training strategies, where we found that multitask learning could be close to competitive with a pre-train-then-fine-tune approach but requires carefully choosing how often the model is trained on each task; and scale, where we compare scaling up the model size, the training time, and the number of ensembled models to determine how to make the best use of fixed compute power [11] The full T5–11B model is more than thirty times the size of existing NLP models such as BERT. Other top-tier techniques (Method — Dataset): T5–11B — SQuAD1.1 dev SA-Net on Albert — SQuAD2.0 TANDA-RoBERTa — WikiQA YYou have most probably already seen and used diverse kinds of recommendation systems. Your favorite online shop or platform uses it to suggest similar products in which you might be interested. One of the current leading algorithms in this field is the Bayesian time SVD++. It was presented in 2019 by the Google Team and achieved SOTA benchmarks on the MovieLens100K Dataset. The Google Team tried multiple diverse methods and combinations of methods until they found the leading combination of a Bayesian Matrix Factorization and a timeSVD++. The Bayesian Matrix Factorization model was trained using a Gibbs sampling. More on the model and all methods tried out you can find here [12]. Other top-tier techniques (Method — Dataset): H+Vamp Gated — MovieLens 20M EASE — Million Song Dataset Bayesian timeSVD++ flipped w/ Ordered Probit Regression — MovieLens 1M As well as Recommender Systems Speech Recognition takes part in our everyday life. There are more and more applications utilizing speech recognition in form of virtual assistants such as Siri, Cortana, Bixby, or Alexa. One of the leading algorithms in this field is the ContextNet + SpecAugment-based Noisy Student Training with Libri-Light first introduced 2019 by the Google Team, the paper [13]. As the name reveals this method combines a ContextNet with Noisy Student Training. The ContextNet is a CNN-RNN-Transducer. The model consists of an audio encoder for the input audio, a label encoder for producing the input label, and a joint network of both to decode. For the label encoder, a LSTM is used and the audio encoder is based on a CNN. The Noisy Student Training is a sort of semi-supervised learning that uses unlabeled data to improve accuracy [13]. “In noisy student training, a series of models are trained in succession, such that for each model, the preceding model in the series serves as a teacher model on the unlabeled portion of the dataset. The distinguishing feature of noisy student training is the exploitation of augmentation, where the teacher produces quality labels by reading in clean input, while the student is forced to reproduce those labels with heavily augmented input features.” [13] The Libri Light refers to the unlabeled audio dataset on which the model is trained and which is derived from audio books. Other top-tier techniques (Method — Dataset): ResNet + BiLSTMs acoustic model — Switchboard + Hub500 LiGRU + Dropout + BatchNorm + Monophone Reg — TIMIT Large-10h-LV-60k — Libri-Light test-clean The last decade has brought a breakthrough in multiple disciplines and tasks. New technologies, algorithms, and applications have been discovered and developed and we are still at the beginning. This was made mainly possible through two developments: 1) growing databases that made it possible to feed the algorithm with enough data and 2) the technological development of processors, RAM, and graphic cards made it possible to train more complex algorithms that need more computing power. Furthermore, the half-life period of an algorithm being state-of-the-art shrinks also with increasing investments in Data Science and with more and more people being interested in the field of Data Science and Machine Learning. Consecutively, this article might be already out of date in a year. But for now, these are leading techniques which help in the progress of creating better and better algorithms. For the case you know other methods or disciplines that should be added, you can comment or contact me. I appreciate your feedback and hope you enjoyed reading this article! medium.com References: [1] Tao, A., Sapra, K., & Catanzaro, B. (2020). Hierarchical Multi-Scale Attention for Semantic Segmentation. ArXiv:2005.10821 [Cs]. http://arxiv.org/abs/2005.10821 [2] Touvron, H., Vedaldi, A., Douze, M., & Jégou, H. (2020b). Fixing the train-test resolution discrepancy: FixEfficientNet. ArXiv:2003.08237 [Cs]. http://arxiv.org/abs/2003.08237 [3] Touvron, H., Vedaldi, A., Douze, M., & Jégou, H. (2020a). Fixing the train-test resolution discrepancy. ArXiv:1906.06423 [Cs]. http://arxiv.org/abs/1906.06423 [4] Tan, M., Pang, R., & Le, Q. V. (2020). EfficientDet: Scalable and Efficient Object Detection. ArXiv:1911.09070 [Cs, Eess]. http://arxiv.org/abs/1911.09070 [5] Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. ArXiv:1810.04805 [Cs]. http://arxiv.org/abs/1810.04805 [6] Shoeybi, M., Patwary, M., Puri, R., LeGresley, P., Casper, J., & Catanzaro, B. (2020). Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism. ArXiv:1909.08053 [Cs]. http://arxiv.org/abs/1909.08053 [7] Edunov, S., Ott, M., Auli, M., & Grangier, D. (2018). Understanding Back-Translation at Scale. ArXiv:1808.09381 [Cs]. http://arxiv.org/abs/1808.09381 [8] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., & Polosukhin, I. (2017). Attention Is All You Need. ArXiv:1706.03762 [Cs]. http://arxiv.org/abs/1706.03762 [9] Touvron, H., Vedaldi, A., Douze, M., & Jégou, H. (2020b). Fixing the train-test resolution discrepancy: FixEfficientNet. ArXiv:2003.08237 [Cs]. http://arxiv.org/abs/2003.08237 [10] Raffel, C., Shazeer, N., Roberts, A., Lee, K., Narang, S., Matena, M., Zhou, Y., Li, W., & Liu, P. J. (2020). Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer. ArXiv:1910.10683 [Cs, Stat]. http://arxiv.org/abs/1910.10683 [11] https://ai.googleblog.com/2020/02/exploring-transfer-learning-with-t5.html [12] Rendle, S., Zhang, L., & Koren, Y. (2019). On the Difficulty of Evaluating Baselines: A Study on Recommender Systems. ArXiv:1905.01395 [Cs]. http://arxiv.org/abs/1905.01395 [13] Park, D. S., Zhang, Y., Jia, Y., Han, W., Chiu, C.-C., Li, B., Wu, Y., & Le, Q. V. (2020). Improved Noisy Student Training for Automatic Speech Recognition. ArXiv:2005.09629 [Cs, Eess]. http://arxiv.org/abs/2005.09629
[ { "code": null, "e": 1084, "s": 172, "text": "Machine Learning algorithms are on the rise. Every year new techniques are presented that outdate the current leading algorithms. Some of them are only little advances or combinations of existing algorithms and others are newly created and lead to astonishing progress. For most techniques exist already great articles that explain the theory behind it and some of them offer also an implementation with code and tutorial. None did yet offer an overview of the current leading algorithms, so the idea came up to present the best algorithms per task based on the results achieved (performance scores are used). Of course, there are many more tasks and not all tasks can be presented. I tried to select the most popular fields and tasks and hope this might help to get a better understanding. The metiers on which this article will lay a focus are Computer Vision, Natural Language Processing, Speech Recognition." }, { "code": null, "e": 1249, "s": 1084, "text": "All the fields, tasks and some of the algorithms are presented in the article. If you are interested only in a subpart, skip the to the section you want to dive in." }, { "code": null, "e": 1621, "s": 1249, "text": "Computer Vision is one of the most researched and most popular fields in machine learning. It is utilized to solve many everyday problems and consecutively involved in multiple applications, from which the most popular is currently the vision of self-driving cars. The tasks on which we’ll take a look are semantic segmentation, image classification and object detection." }, { "code": null, "e": 1924, "s": 1621, "text": "Semantic Segmentation can be seen as understanding the structures and components of an image on a pixel level. Methods for semantic segmentation try to make predictions about the structures and objects in an image. For a better understanding a semantic segmentation of a street scene can be seen below:" }, { "code": null, "e": 2360, "s": 1924, "text": "The current leading algorithm HRNet-OCR was presented in 2020 by Tao et al. from Nvidia. It achieved a Mean Intersection Over Union (Mean IOU) of 85,1%. HRNet-OCR scales the image and uses a dense mask for each scale. The predictions of all scales are then “combined by performing pixel-wise multiplication between masks with the predictions followed by pixel-wise summation among the different scales to obtain the final results” [1]." }, { "code": null, "e": 2451, "s": 2360, "text": "Check out the Github to the technique:https://github.com/HRNet/HRNet-Semantic-Segmentation" }, { "code": null, "e": 2497, "s": 2451, "text": "Other top-tier techniques (Method — Dataset):" }, { "code": null, "e": 2535, "s": 2497, "text": "Efficient-Net-L2+NAS-FPN — PASCAL VOC" }, { "code": null, "e": 2564, "s": 2535, "text": "ResNeSt-269 — PASCAL Context" }, { "code": null, "e": 2578, "s": 2564, "text": "VMVF —ScanNet" }, { "code": null, "e": 2772, "s": 2578, "text": "Other than Semantic Segmentation, Image Classification, does not focus on the areas on the image, but on the image as a whole. This discipline tries to classify each image by assigning a label." }, { "code": null, "e": 3356, "s": 2772, "text": "The FixEfficientNet has been presented first with the corresponding paper on the 20th April 2020 from the Facebook AI Research Team [2][3]. It is currently the state-of-the-art and has the best results on the ImageNet Dataset with 480M params, a top-1 accuracy of 88.5%, and top-5 accuracy of 98,7%. FixRes is the short form for Fix Resolution and tries to keep a fixed size for either the RoC (Region of Classification) used for train time or the crop used for test time. The EfficientNet is a compound scaling of the dimensions of a CNN which improves both accuracy and efficiency." }, { "code": null, "e": 3412, "s": 3356, "text": "For more information to the FixEfficientNet, read this." }, { "code": null, "e": 3458, "s": 3412, "text": "Other top-tier techniques (Method — Dataset):" }, { "code": null, "e": 3475, "s": 3458, "text": "BiT-L — CIFAR-10" }, { "code": null, "e": 3500, "s": 3475, "text": "Wide-ResNet-101 — STL-10" }, { "code": null, "e": 3560, "s": 3500, "text": "Branching/Merging CNN + Homogeneous Filter Capsules — MNIST" }, { "code": null, "e": 3661, "s": 3560, "text": "Object detection is the task of recognizing instances of objects of a certain class within an image." }, { "code": null, "e": 4027, "s": 3661, "text": "The current leading Object Detection technique is the Efficient-Det D7x first presented by the Google Brain Team (Tan et al.) in 2020 [4]. It achieved an AP50 (For more on AP50: Average Precision with a fixed IoU threshold at 50) of 74,3 and a box AP of 55,1. The Efficient-Det is a combination of EfficientNets with Bidirectional Feature Pyramid Networks (BiFPNs)." }, { "code": null, "e": 4212, "s": 4027, "text": "As shortly explained above, the EfficientNet is a compound scaling of the dimensions of a CNN which improves both accuracy and efficiency. For more on EfficientNet, you can click here." }, { "code": null, "e": 4835, "s": 4212, "text": "In Computer Vision a typical approach to increase the accuracy is the creation of multiple copies of the same image with different resolutions. This results in a so-called Pyramid due to the arrangement of the smallest image as the top layer and the biggest image as the bottom layer. The Feature Pyramid Network represents such a pyramid. Bidirectional means that there is not only a top-down approach but simultaneously a bottom-up approach. Every bidirectional path is used as a feature network layer and this leads to the BiFPNs. It helps with increasing accuracy and speed. For more information on BiFPNs, click here." }, { "code": null, "e": 4881, "s": 4835, "text": "Other top-tier techniques (Method — Dataset):" }, { "code": null, "e": 4900, "s": 4881, "text": "RODEO — PASCAL VOC" }, { "code": null, "e": 4935, "s": 4900, "text": "Patch Refinement — KITTI Cars Easy" }, { "code": null, "e": 4956, "s": 4935, "text": "IterDet — CrowdHuman" }, { "code": null, "e": 5026, "s": 4956, "text": "A common definition for Natural Language Processing is the following:" }, { "code": null, "e": 5147, "s": 5026, "text": "NLP is a subfield of AI that gives the machines the ability to read, understand and derive meaning from human languages." }, { "code": null, "e": 5619, "s": 5147, "text": "NLP tasks vary in a broad range and as the definition reveals, all of them try to deduct some meaning from our language and perform calculations based on our language and its components. Algorithms based on NLP can be found in various applications and industries. Just to name a few applications which you might encounter every day such as translators, social media monitoring, chatbots, spam filters, grammar check in Microsoft word or messengers and virtual assistants." }, { "code": null, "e": 5924, "s": 5619, "text": "Sentiment Analysis is a field of Text Mining and is used to interpret and classify emotions in text data. One of the current leading algorithms is BERT which achieved an accuracy of 55.5 on the SST-5 Fine-grained classification dataset in 2019. The original paper was published by the Google AI Team [5]." }, { "code": null, "e": 6294, "s": 5924, "text": "BERT stands for Bidirectional Encoder Representations from Transformers and applies a bidirectional training of the Transformer technique. Transformer technique is an attention model used for language modeling which was previously only applied in one direction. Either to parse a text from left-to-right or from right-to-left. For more details, read this great article." }, { "code": null, "e": 6340, "s": 6294, "text": "Other top-tier techniques (Method — Dataset):" }, { "code": null, "e": 6376, "s": 6340, "text": "T5–3B — SST-2 Binary classification" }, { "code": null, "e": 6411, "s": 6376, "text": "NB-weighted-BON + dv-cosine — IMDb" }, { "code": null, "e": 6678, "s": 6411, "text": "Language Modeling is the task of predicting the next words or letters in a text based on the existing text/previous words.The GPT-2 model was given two sentences about a herd of unicorns living in the Andens and it created an astonishing story. You can read it here." }, { "code": null, "e": 7043, "s": 6678, "text": "In Language Modeling one of the best performing algorithms can be found in Megatron-LM. This model and the paper were first presented in 2019 by the Nvidia team. A model similar to GPT-2 was trained on 8300 billion params. It was able to reduce the current state-of-the-art score of 15.8 to a test perplexity of only 10.8. The dataset used was the WikiText103 [6]." }, { "code": null, "e": 7415, "s": 7043, "text": "The model makes use of the Transformer Network. In their work, a transformer layer is made up of a self-attention block followed by a two-layer, multi-layer perceptron (MLP). In each of the blocks, model parallelism is used. This helps to reduce communication and keeps the GPUs compute-bound. The computation of the GPUs is duplicated to increase the speed of the model." }, { "code": null, "e": 7461, "s": 7415, "text": "Other top-tier techniques (Method — Dataset):" }, { "code": null, "e": 7483, "s": 7461, "text": "GPT-3 — Penn Treebank" }, { "code": null, "e": 7516, "s": 7483, "text": "GPT-2 — WikiText2, Text8, enwik8" }, { "code": null, "e": 7674, "s": 7516, "text": "Machine Translation is used in applications such as Google Translate or www.deepl.com. It is used to translate a text in another language using an algorithm." }, { "code": null, "e": 8009, "s": 7674, "text": "One of the most promising algorithms in this field is the Transformer Big +BT. It was presented in this paper in 2018 by the Google Brain Team. In general, Transformers are state-of-the-art for dealing sequences and for machine translation. Transformers do not use recurrent connections but parse instead sequences simultaneously [7]." }, { "code": null, "e": 8761, "s": 8009, "text": "As you can see in the gif above the input and output differ. This is due to the two different languages, the input is for example in English, while the output language is german. For the sake of increasing speed parallelization is a key aspect of the model. This problem is tackled by using CNN together with attention models. The self-attention helps to increase the speed and the focus on certain words, while CNN is used for parallelization [8]. For more on transformers read this great article. The authors applied back-translation (BT) for their training. In this method, the training dataset is translated into the target language and the algorithm translates it back to the original language. The performance can then be observed perfectly [7]." }, { "code": null, "e": 8807, "s": 8761, "text": "Other top-tier techniques (Method — Dataset):" }, { "code": null, "e": 8843, "s": 8807, "text": "MAT+Knee — IWSLT2014 German-English" }, { "code": null, "e": 8873, "s": 8843, "text": "MADL — WMT2016 English-German" }, { "code": null, "e": 8931, "s": 8873, "text": "Attentional encoder-decoder +BPE — WMT2016 German-English" }, { "code": null, "e": 9125, "s": 8931, "text": "Text Classification is the task of assigning a certain category to a sentence, a text, or a word. The current leading algorithm on three different datasets (DBpedia, AG News and IMDb) is XLNet." }, { "code": null, "e": 9663, "s": 9125, "text": "The paper and the technique XLNet was first presented in 2019 by the Google AI Team. It improved the leading algorithm BERT in 20 tasks. The method that XLNet pioneered in is called Permutation Language Modeling. It makes use of a permutation of the words. Imagine you got 3 words in the following order [w1,w2,w3]. All permutations are then retrieved, here 3*2*1 = 6 permutations. Obviously, with long sentences, this leads to numerous permutations. All words positioned before the prediction word (e.g. w2) are used for prediction [9]:" }, { "code": null, "e": 9692, "s": 9663, "text": "w3 w1 w2w1 w2 w3w1 w3 w2 ..." }, { "code": null, "e": 9878, "s": 9692, "text": "In row 1, w3 and w1 are used for the prediction of w2. In row 2 only w1 is used for prediction and so on. To get a better understanding of the technique you can read more about it here." }, { "code": null, "e": 9924, "s": 9878, "text": "Other top-tier techniques (Method — Dataset):" }, { "code": null, "e": 9945, "s": 9924, "text": "USE_T + CNN — TREC-6" }, { "code": null, "e": 9958, "s": 9945, "text": "SGC — 20News" }, { "code": null, "e": 10237, "s": 9958, "text": "Question Answering is the task of training an algorithm to answer questions (often based on reading comprehension). This task is part of Transfer Learning due to the learning on a given text database and the storing of knowledge to answer the questions to a later point in time." }, { "code": null, "e": 10710, "s": 10237, "text": "With the T5–11B the Google AI Team achieved state-of-the-art benchmarks on four different datasets: GLUE, SuperGLUE, SQuAD and CNN/Daily Mail. T5 stands for the five T’s in Text-to-Text Transfer Transformer, while 11B stands for the 11 Billion Dataset with which the algorithm was trained. In contrast to BERT and other great algorithms the T5–11B does not output a label to the input sentence. Instead, as the name already shows, the output is a text string as well [10]." }, { "code": null, "e": 10997, "s": 10710, "text": "The authors of the paper have rigorously evaluated and refined dozens of existing NLP tasks to take the best ideas to their model. These included experiments on model architectures, pre-training objectives, unlabeled datasets, training strategies and scale as the authors describe [10]:" }, { "code": null, "e": 11116, "s": 10997, "text": "model architectures, where we found that encoder-decoder models generally outperformed “decoder-only” language models;" }, { "code": null, "e": 11352, "s": 11116, "text": "pre-training objectives, where we confirmed that fill-in-the-blank-style denoising objectives (where the model is trained to recover missing words in the input) worked best and that the most important factor was the computational cost;" }, { "code": null, "e": 11517, "s": 11352, "text": "unlabeled datasets, where we showed that training on in-domain data can be beneficial but that pre-training on smaller datasets can lead to detrimental overfitting;" }, { "code": null, "e": 11725, "s": 11517, "text": "training strategies, where we found that multitask learning could be close to competitive with a pre-train-then-fine-tune approach but requires carefully choosing how often the model is trained on each task;" }, { "code": null, "e": 11900, "s": 11725, "text": "and scale, where we compare scaling up the model size, the training time, and the number of ensembled models to determine how to make the best use of fixed compute power [11]" }, { "code": null, "e": 11994, "s": 11900, "text": "The full T5–11B model is more than thirty times the size of existing NLP models such as BERT." }, { "code": null, "e": 12040, "s": 11994, "text": "Other top-tier techniques (Method — Dataset):" }, { "code": null, "e": 12062, "s": 12040, "text": "T5–11B — SQuAD1.1 dev" }, { "code": null, "e": 12090, "s": 12062, "text": "SA-Net on Albert — SQuAD2.0" }, { "code": null, "e": 12113, "s": 12090, "text": "TANDA-RoBERTa — WikiQA" }, { "code": null, "e": 12308, "s": 12113, "text": "YYou have most probably already seen and used diverse kinds of recommendation systems. Your favorite online shop or platform uses it to suggest similar products in which you might be interested." }, { "code": null, "e": 12803, "s": 12308, "text": "One of the current leading algorithms in this field is the Bayesian time SVD++. It was presented in 2019 by the Google Team and achieved SOTA benchmarks on the MovieLens100K Dataset. The Google Team tried multiple diverse methods and combinations of methods until they found the leading combination of a Bayesian Matrix Factorization and a timeSVD++. The Bayesian Matrix Factorization model was trained using a Gibbs sampling. More on the model and all methods tried out you can find here [12]." }, { "code": null, "e": 12849, "s": 12803, "text": "Other top-tier techniques (Method — Dataset):" }, { "code": null, "e": 12878, "s": 12849, "text": "H+Vamp Gated — MovieLens 20M" }, { "code": null, "e": 12906, "s": 12878, "text": "EASE — Million Song Dataset" }, { "code": null, "e": 12977, "s": 12906, "text": "Bayesian timeSVD++ flipped w/ Ordered Probit Regression — MovieLens 1M" }, { "code": null, "e": 13196, "s": 12977, "text": "As well as Recommender Systems Speech Recognition takes part in our everyday life. There are more and more applications utilizing speech recognition in form of virtual assistants such as Siri, Cortana, Bixby, or Alexa." }, { "code": null, "e": 13376, "s": 13196, "text": "One of the leading algorithms in this field is the ContextNet + SpecAugment-based Noisy Student Training with Libri-Light first introduced 2019 by the Google Team, the paper [13]." }, { "code": null, "e": 13840, "s": 13376, "text": "As the name reveals this method combines a ContextNet with Noisy Student Training. The ContextNet is a CNN-RNN-Transducer. The model consists of an audio encoder for the input audio, a label encoder for producing the input label, and a joint network of both to decode. For the label encoder, a LSTM is used and the audio encoder is based on a CNN. The Noisy Student Training is a sort of semi-supervised learning that uses unlabeled data to improve accuracy [13]." }, { "code": null, "e": 14299, "s": 13840, "text": "“In noisy student training, a series of models are trained in succession, such that for each model, the preceding model in the series serves as a teacher model on the unlabeled portion of the dataset. The distinguishing feature of noisy student training is the exploitation of augmentation, where the teacher produces quality labels by reading in clean input, while the student is forced to reproduce those labels with heavily augmented input features.” [13]" }, { "code": null, "e": 14422, "s": 14299, "text": "The Libri Light refers to the unlabeled audio dataset on which the model is trained and which is derived from audio books." }, { "code": null, "e": 14468, "s": 14422, "text": "Other top-tier techniques (Method — Dataset):" }, { "code": null, "e": 14523, "s": 14468, "text": "ResNet + BiLSTMs acoustic model — Switchboard + Hub500" }, { "code": null, "e": 14575, "s": 14523, "text": "LiGRU + Dropout + BatchNorm + Monophone Reg — TIMIT" }, { "code": null, "e": 14617, "s": 14575, "text": "Large-10h-LV-60k — Libri-Light test-clean" }, { "code": null, "e": 15514, "s": 14617, "text": "The last decade has brought a breakthrough in multiple disciplines and tasks. New technologies, algorithms, and applications have been discovered and developed and we are still at the beginning. This was made mainly possible through two developments: 1) growing databases that made it possible to feed the algorithm with enough data and 2) the technological development of processors, RAM, and graphic cards made it possible to train more complex algorithms that need more computing power. Furthermore, the half-life period of an algorithm being state-of-the-art shrinks also with increasing investments in Data Science and with more and more people being interested in the field of Data Science and Machine Learning. Consecutively, this article might be already out of date in a year. But for now, these are leading techniques which help in the progress of creating better and better algorithms." }, { "code": null, "e": 15688, "s": 15514, "text": "For the case you know other methods or disciplines that should be added, you can comment or contact me. I appreciate your feedback and hope you enjoyed reading this article!" }, { "code": null, "e": 15699, "s": 15688, "text": "medium.com" }, { "code": null, "e": 15711, "s": 15699, "text": "References:" }, { "code": null, "e": 15876, "s": 15711, "text": "[1] Tao, A., Sapra, K., & Catanzaro, B. (2020). Hierarchical Multi-Scale Attention for Semantic Segmentation. ArXiv:2005.10821 [Cs]. http://arxiv.org/abs/2005.10821" }, { "code": null, "e": 16057, "s": 15876, "text": "[2] Touvron, H., Vedaldi, A., Douze, M., & Jégou, H. (2020b). Fixing the train-test resolution discrepancy: FixEfficientNet. ArXiv:2003.08237 [Cs]. http://arxiv.org/abs/2003.08237" }, { "code": null, "e": 16221, "s": 16057, "text": "[3] Touvron, H., Vedaldi, A., Douze, M., & Jégou, H. (2020a). Fixing the train-test resolution discrepancy. ArXiv:1906.06423 [Cs]. http://arxiv.org/abs/1906.06423" }, { "code": null, "e": 16380, "s": 16221, "text": "[4] Tan, M., Pang, R., & Le, Q. V. (2020). EfficientDet: Scalable and Efficient Object Detection. ArXiv:1911.09070 [Cs, Eess]. http://arxiv.org/abs/1911.09070" }, { "code": null, "e": 16580, "s": 16380, "text": "[5] Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2019). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. ArXiv:1810.04805 [Cs]. http://arxiv.org/abs/1810.04805" }, { "code": null, "e": 16813, "s": 16580, "text": "[6] Shoeybi, M., Patwary, M., Puri, R., LeGresley, P., Casper, J., & Catanzaro, B. (2020). Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism. ArXiv:1909.08053 [Cs]. http://arxiv.org/abs/1909.08053" }, { "code": null, "e": 16967, "s": 16813, "text": "[7] Edunov, S., Ott, M., Auli, M., & Grangier, D. (2018). Understanding Back-Translation at Scale. ArXiv:1808.09381 [Cs]. http://arxiv.org/abs/1808.09381" }, { "code": null, "e": 17168, "s": 16967, "text": "[8] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., & Polosukhin, I. (2017). Attention Is All You Need. ArXiv:1706.03762 [Cs]. http://arxiv.org/abs/1706.03762" }, { "code": null, "e": 17349, "s": 17168, "text": "[9] Touvron, H., Vedaldi, A., Douze, M., & Jégou, H. (2020b). Fixing the train-test resolution discrepancy: FixEfficientNet. ArXiv:2003.08237 [Cs]. http://arxiv.org/abs/2003.08237" }, { "code": null, "e": 17608, "s": 17349, "text": "[10] Raffel, C., Shazeer, N., Roberts, A., Lee, K., Narang, S., Matena, M., Zhou, Y., Li, W., & Liu, P. J. (2020). Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer. ArXiv:1910.10683 [Cs, Stat]. http://arxiv.org/abs/1910.10683" }, { "code": null, "e": 17688, "s": 17608, "text": "[11] https://ai.googleblog.com/2020/02/exploring-transfer-learning-with-t5.html" }, { "code": null, "e": 17866, "s": 17688, "text": "[12] Rendle, S., Zhang, L., & Koren, Y. (2019). On the Difficulty of Evaluating Baselines: A Study on Recommender Systems. ArXiv:1905.01395 [Cs]. http://arxiv.org/abs/1905.01395" } ]
Batch Script - SET
Displays the list of environment variables on the current system. Set @echo off set The above command displays the list of environment variables on the current system. Print Add Notes Bookmark this page
[ { "code": null, "e": 2235, "s": 2169, "text": "Displays the list of environment variables on the current system." }, { "code": null, "e": 2240, "s": 2235, "text": "Set\n" }, { "code": null, "e": 2255, "s": 2240, "text": "@echo off \nset" }, { "code": null, "e": 2339, "s": 2255, "text": "The above command displays the list of environment variables on the current system." }, { "code": null, "e": 2346, "s": 2339, "text": " Print" }, { "code": null, "e": 2357, "s": 2346, "text": " Add Notes" } ]
Seaborn is actually quite good for data visualization | by Mostafa Gazar | Towards Data Science
Seaborn is a Python data visualization library based on matplotlib (it is the go to library for plotting in Python). Seaborn provides a high-level interface for drawing attractive and informative statistical graphics. %matplotlib inlineimport matplotlib.pyplot as pltimport seaborn as sns sns.set() You can also customize seaborn theme or use one of six variations of the default theme. Which are called deep, muted, pastel, bright, dark, and colorblind. # Plot color palettedef plot_color_palette(palette: str): figure = sns.palplot(sns.color_palette()) plt.xlabel("Color palette: " + palette) plt.show(figure)palettes = ["deep", "muted", "pastel", "bright", "dark", "colorblind"]for palette in palettes: sns.set(palette=palette) plot_color_palette(palette) You can follow the following examples at your own pace by using this colab file. Google’s Colaboratory is a free Jupyter notebook environment that requires no setup and runs entirely in the cloud. We will use the tips dataset here which would help us go through some real examples. tips = sns.load_dataset("tips")tips.head() Let us starting by doing a scatter plot with multiple semantic variables to visualize the dataset we are dealing with. sns.relplot(x="total_bill", y="tip", col="time", # Categorical variables that will determine the faceting of the grid. hue="smoker", # Grouping variable that will produce elements with different colors. style="smoker", # Grouping variable that will produce elements with different styles. size="size", # Grouping variable that will produce elements with different sizes. data=tips) There are several specialized plot types in seaborn that are optimized for visualizing relationship between different variables (numeric and categorical). They can be accessed through relplot. We can also plot linear regression model using lmplot. sns.lmplot(x="total_bill", y="tip", col="time", # Categorical variables that will determine the faceting of the grid. hue="smoker", # Grouping variable that will produce elements with different colors. data=tips) Or simply: sns.lmplot(x="total_bill", y="tip", data=tips) sns.lmplot(x="size", y="tip", data=tips) sns.lmplot(x="size", y="tip", data=tips, x_estimator=np.mean) tips["big_tip"] = (tips.tip / tips.total_bill) > .15sns.lmplot(x="total_bill", y="big_tip", y_jitter=.03, logistic=True, data=tips) There are also other several specialized plot types in seaborn that are optimized for visualizing categorical variables. They can be accessed through catplot. sns.catplot(x="day", y="total_bill", hue="smoker", # Grouping variable that will produce elements with different colors. kind="swarm", # Options are: "point", "bar", "strip", "swarm", "box", "violin", or "boxen" data=tips) Alternately, we could use kernel density estimation to represent the underlying distribution that the points are sampled from. sns.catplot(x="day", y="total_bill", hue="smoker", # Grouping variable that will produce elements with different colors. kind="violin", # Options are: "point", "bar", "strip", "swarm", "box", "violin", or "boxen" split=True, data=tips) Or you could show the only mean value and its confidence interval within each nested category. sns.catplot(x="day", y="total_bill", hue="smoker", # Grouping variable that will produce elements with different colors. kind="bar", # Options are: "point", "bar", "strip", "swarm", "box", "violin", or "boxen" data=tips) jointplot and pairplot make visualizations with multiple plots possible. jointplot focuses on a single relationship while pairplot takes a broader view, showing all pairwise relationships and the marginal distributions, optionally conditioned on a categorical variable. sns.jointplot(x="total_bill", y="tip", kind="reg", # Options are "scatter", "reg", "resid", "kde", "hex" data=tips) sns.pairplot(hue="smoker", # Grouping variable that will produce elements with different colors. data=tips) Plot 2 images side by side figure = plt.figure()figure.add_subplot(1, 2, 1)plt.imshow(image_grey, cmap='gray'), plt.axis("off")figure.add_subplot(1, 2, 2)plt.imshow(image_binarized, cmap='gray'), plt.axis("off")plt.show() You can even plot more complex grids, check the following for example: https://seaborn.pydata.org/tutorial.htmlhttps://seaborn.pydata.org/introduction.html https://seaborn.pydata.org/tutorial.html https://seaborn.pydata.org/introduction.html Check out this story colab file, make changes and share it if you found it helpful. Finally, I created a 3-minute survey to help collect data on what tools and technologies you most use in your Machine Learning projects. Once the data is collected –and if you choose to share your email with me– it will be shared back with you with the goal of identifying trends and best practices. This survey could help identify areas of improvement and pain points in existing workflows. Please take a few moments to fill out this survey http://bit.ly/ml-survey-2019
[ { "code": null, "e": 390, "s": 172, "text": "Seaborn is a Python data visualization library based on matplotlib (it is the go to library for plotting in Python). Seaborn provides a high-level interface for drawing attractive and informative statistical graphics." }, { "code": null, "e": 461, "s": 390, "text": "%matplotlib inlineimport matplotlib.pyplot as pltimport seaborn as sns" }, { "code": null, "e": 471, "s": 461, "text": "sns.set()" }, { "code": null, "e": 627, "s": 471, "text": "You can also customize seaborn theme or use one of six variations of the default theme. Which are called deep, muted, pastel, bright, dark, and colorblind." }, { "code": null, "e": 946, "s": 627, "text": "# Plot color palettedef plot_color_palette(palette: str): figure = sns.palplot(sns.color_palette()) plt.xlabel(\"Color palette: \" + palette) plt.show(figure)palettes = [\"deep\", \"muted\", \"pastel\", \"bright\", \"dark\", \"colorblind\"]for palette in palettes: sns.set(palette=palette) plot_color_palette(palette)" }, { "code": null, "e": 1143, "s": 946, "text": "You can follow the following examples at your own pace by using this colab file. Google’s Colaboratory is a free Jupyter notebook environment that requires no setup and runs entirely in the cloud." }, { "code": null, "e": 1228, "s": 1143, "text": "We will use the tips dataset here which would help us go through some real examples." }, { "code": null, "e": 1271, "s": 1228, "text": "tips = sns.load_dataset(\"tips\")tips.head()" }, { "code": null, "e": 1390, "s": 1271, "text": "Let us starting by doing a scatter plot with multiple semantic variables to visualize the dataset we are dealing with." }, { "code": null, "e": 1828, "s": 1390, "text": "sns.relplot(x=\"total_bill\", y=\"tip\", col=\"time\", # Categorical variables that will determine the faceting of the grid. hue=\"smoker\", # Grouping variable that will produce elements with different colors. style=\"smoker\", # Grouping variable that will produce elements with different styles. size=\"size\", # Grouping variable that will produce elements with different sizes. data=tips)" }, { "code": null, "e": 2021, "s": 1828, "text": "There are several specialized plot types in seaborn that are optimized for visualizing relationship between different variables (numeric and categorical). They can be accessed through relplot." }, { "code": null, "e": 2076, "s": 2021, "text": "We can also plot linear regression model using lmplot." }, { "code": null, "e": 2320, "s": 2076, "text": "sns.lmplot(x=\"total_bill\", y=\"tip\", col=\"time\", # Categorical variables that will determine the faceting of the grid. hue=\"smoker\", # Grouping variable that will produce elements with different colors. data=tips)" }, { "code": null, "e": 2331, "s": 2320, "text": "Or simply:" }, { "code": null, "e": 2378, "s": 2331, "text": "sns.lmplot(x=\"total_bill\", y=\"tip\", data=tips)" }, { "code": null, "e": 2419, "s": 2378, "text": "sns.lmplot(x=\"size\", y=\"tip\", data=tips)" }, { "code": null, "e": 2481, "s": 2419, "text": "sns.lmplot(x=\"size\", y=\"tip\", data=tips, x_estimator=np.mean)" }, { "code": null, "e": 2645, "s": 2481, "text": "tips[\"big_tip\"] = (tips.tip / tips.total_bill) > .15sns.lmplot(x=\"total_bill\", y=\"big_tip\", y_jitter=.03, logistic=True, data=tips)" }, { "code": null, "e": 2804, "s": 2645, "text": "There are also other several specialized plot types in seaborn that are optimized for visualizing categorical variables. They can be accessed through catplot." }, { "code": null, "e": 3061, "s": 2804, "text": "sns.catplot(x=\"day\", y=\"total_bill\", hue=\"smoker\", # Grouping variable that will produce elements with different colors. kind=\"swarm\", # Options are: \"point\", \"bar\", \"strip\", \"swarm\", \"box\", \"violin\", or \"boxen\" data=tips)" }, { "code": null, "e": 3188, "s": 3061, "text": "Alternately, we could use kernel density estimation to represent the underlying distribution that the points are sampled from." }, { "code": null, "e": 3470, "s": 3188, "text": "sns.catplot(x=\"day\", y=\"total_bill\", hue=\"smoker\", # Grouping variable that will produce elements with different colors. kind=\"violin\", # Options are: \"point\", \"bar\", \"strip\", \"swarm\", \"box\", \"violin\", or \"boxen\" split=True, data=tips)" }, { "code": null, "e": 3565, "s": 3470, "text": "Or you could show the only mean value and its confidence interval within each nested category." }, { "code": null, "e": 3820, "s": 3565, "text": "sns.catplot(x=\"day\", y=\"total_bill\", hue=\"smoker\", # Grouping variable that will produce elements with different colors. kind=\"bar\", # Options are: \"point\", \"bar\", \"strip\", \"swarm\", \"box\", \"violin\", or \"boxen\" data=tips)" }, { "code": null, "e": 4090, "s": 3820, "text": "jointplot and pairplot make visualizations with multiple plots possible. jointplot focuses on a single relationship while pairplot takes a broader view, showing all pairwise relationships and the marginal distributions, optionally conditioned on a categorical variable." }, { "code": null, "e": 4233, "s": 4090, "text": "sns.jointplot(x=\"total_bill\", y=\"tip\", kind=\"reg\", # Options are \"scatter\", \"reg\", \"resid\", \"kde\", \"hex\" data=tips)" }, { "code": null, "e": 4353, "s": 4233, "text": "sns.pairplot(hue=\"smoker\", # Grouping variable that will produce elements with different colors. data=tips)" }, { "code": null, "e": 4380, "s": 4353, "text": "Plot 2 images side by side" }, { "code": null, "e": 4575, "s": 4380, "text": "figure = plt.figure()figure.add_subplot(1, 2, 1)plt.imshow(image_grey, cmap='gray'), plt.axis(\"off\")figure.add_subplot(1, 2, 2)plt.imshow(image_binarized, cmap='gray'), plt.axis(\"off\")plt.show()" }, { "code": null, "e": 4646, "s": 4575, "text": "You can even plot more complex grids, check the following for example:" }, { "code": null, "e": 4731, "s": 4646, "text": "https://seaborn.pydata.org/tutorial.htmlhttps://seaborn.pydata.org/introduction.html" }, { "code": null, "e": 4772, "s": 4731, "text": "https://seaborn.pydata.org/tutorial.html" }, { "code": null, "e": 4817, "s": 4772, "text": "https://seaborn.pydata.org/introduction.html" }, { "code": null, "e": 4901, "s": 4817, "text": "Check out this story colab file, make changes and share it if you found it helpful." }, { "code": null, "e": 5201, "s": 4901, "text": "Finally, I created a 3-minute survey to help collect data on what tools and technologies you most use in your Machine Learning projects. Once the data is collected –and if you choose to share your email with me– it will be shared back with you with the goal of identifying trends and best practices." }, { "code": null, "e": 5293, "s": 5201, "text": "This survey could help identify areas of improvement and pain points in existing workflows." } ]
How to left align components vertically using BoxLayout with Java?
To align components vertically, use the BoxLayout − JFrame frame = new JFrame(); frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS)); Now, create a Panel and add some buttons to it. After that set left alignment of components which are already arranged vertically using Component.LEFT_ALIGNMENT constant − JPanel panel = new JPanel(); JButton btn1 = new JButton("One"); JButton btn2 = new JButton("Two"); JButton btn3 = new JButton("Three"); JButton btn4 = new JButton("Four"); JButton btn5 = new JButton("Five"); panel.add(btn1); panel.add(btn2); panel.add(btn3); panel.add(btn4); panel.add(btn5); panel.setAlignmentX(Component.LEFT_ALIGNMENT); The following is an example to left align components vertically with BoxLayout − package my; import java.awt.Component; import java.awt.Dimension; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS)); JPanel panel = new JPanel(); JButton btn1 = new JButton("One"); JButton btn2 = new JButton("Two"); JButton btn3 = new JButton("Three"); JButton btn4 = new JButton("Four"); JButton btn5 = new JButton("Five"); panel.add(btn1); panel.add(btn2); panel.add(btn3); panel.add(btn4); panel.add(btn5); panel.setAlignmentX(Component.LEFT_ALIGNMENT); panel.setPreferredSize(new Dimension(100, 500)); panel.setMaximumSize(new Dimension(100, 500)); panel.setBorder(BorderFactory.createTitledBorder("demo")); frame.getContentPane().add(panel); frame.setSize(550, 300); frame.setVisible(true); } }
[ { "code": null, "e": 1114, "s": 1062, "text": "To align components vertically, use the BoxLayout −" }, { "code": null, "e": 1234, "s": 1114, "text": "JFrame frame = new JFrame();\nframe.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));" }, { "code": null, "e": 1406, "s": 1234, "text": "Now, create a Panel and add some buttons to it. After that set left alignment of components which are already arranged vertically using Component.LEFT_ALIGNMENT constant −" }, { "code": null, "e": 1746, "s": 1406, "text": "JPanel panel = new JPanel();\nJButton btn1 = new JButton(\"One\");\nJButton btn2 = new JButton(\"Two\");\nJButton btn3 = new JButton(\"Three\");\nJButton btn4 = new JButton(\"Four\");\nJButton btn5 = new JButton(\"Five\");\npanel.add(btn1);\npanel.add(btn2);\npanel.add(btn3);\npanel.add(btn4);\npanel.add(btn5);\npanel.setAlignmentX(Component.LEFT_ALIGNMENT);" }, { "code": null, "e": 1827, "s": 1746, "text": "The following is an example to left align components vertically with BoxLayout −" }, { "code": null, "e": 2994, "s": 1827, "text": "package my;\nimport java.awt.Component;\nimport java.awt.Dimension;\nimport javax.swing.BorderFactory;\nimport javax.swing.BoxLayout;\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));\n JPanel panel = new JPanel();\n JButton btn1 = new JButton(\"One\");\n JButton btn2 = new JButton(\"Two\");\n JButton btn3 = new JButton(\"Three\");\n JButton btn4 = new JButton(\"Four\");\n JButton btn5 = new JButton(\"Five\");\n panel.add(btn1);\n panel.add(btn2);\n panel.add(btn3);\n panel.add(btn4);\n panel.add(btn5);\n panel.setAlignmentX(Component.LEFT_ALIGNMENT);\n panel.setPreferredSize(new Dimension(100, 500));\n panel.setMaximumSize(new Dimension(100, 500));\n panel.setBorder(BorderFactory.createTitledBorder(\"demo\"));\n frame.getContentPane().add(panel);\n frame.setSize(550, 300);\n frame.setVisible(true);\n }\n}" } ]
Access to Python’s configuration information
Configuration information of Python's installation can be accessed by the sysconfig module. For example the list of installation paths and the configuration variables specific to the installation platform. The sysconfig module provides the following functions to access Configuration variables With no arguments, this function returns a dictionary of all configuration variables relevant for the current platform. >>> import sysconfig >>> sysconfig.get_config_vars() {'prefix': 'E:\\python37', 'exec_prefix': 'E:\\python37', 'py_version': '3.7.2', 'py_version_short': '3.7', 'py_version_nodot': '37', 'installed_base': 'E:\\python37', 'base': 'E:\\python37', 'installed_platbase': 'E:\\python37', 'platbase': 'E:\\python37', 'projectbase': 'E:\\python37', 'abiflags': '', 'LIBDEST': 'E:\\python37\\Lib', 'BINLIBDEST': 'E:\\python37\\Lib', 'INCLUDEPY': 'E:\\python37\\Include', 'EXT_SUFFIX': '.pyd', 'EXE': '.exe', 'VERSION': '37', 'BINDIR': 'E:\\python37', 'SO': '.pyd', 'userbase': 'C:\\Users\\acer\\AppData\\Roaming\\Python', 'srcdir': 'E:\\python37'} With arguments, return a list of values for specific keys. For each argument, if the value is not found, return None. >>> sysconfig.get_config_vars('base','EXE') ['E:\\python37', '.exe'] This function returns the value of a single variable name. This is equivalent to get_config_vars().get(name). If name is not found, the function returns None. >>> sysconfig.get_config_var('VERSION') '37' >>> sysconfig.get_config_var('srcdir') 'E:\\python37' Python uses an installation scheme that differs depending on the platform and on the installation options. Following schemes are currently supported: This function returns a tuple containing all path names currently supported in sysconfig. >>> sysconfig.get_path_names() ('stdlib', 'platstdlib', 'purelib', 'platlib', 'include', 'scripts', 'data') Each scheme is composed of a various paths having unique identifier. The path names are as below: This function returns installation path corresponding to the path name, from the install scheme named scheme. >>> sysconfig.get_path('include') 'E:\\python37\\Include' >>> sysconfig.get_platform() 'win-amd64' This function returns the MAJOR.MINOR Python version number as a string. This function returns a string that identifies the current platform. The configuration variables and their values can also be accessed using sysconfig module with –m option. E:\python37>python -m sysconfig Platform: "win-amd64" Python version: "3.7" Current installation scheme: "nt" Paths: data = "E:\python37" include = "E:\python37\Include" platinclude = "E:\python37\Include" platlib = "E:\python37\Lib\site-packages" platstdlib = "E:\python37\Lib" purelib = "E:\python37\Lib\site-packages" scripts = "E:\python37\Scripts" stdlib = "E:\python37\Lib" Variables: BINDIR = "E:\python37" BINLIBDEST = "E:\python37\Lib" EXE = ".exe" EXT_SUFFIX = ".pyd" INCLUDEPY = "E:\python37\Include" LIBDEST = "E:\python37\Lib" SO = ".pyd" VERSION = "37" abiflags = "" base = "E:\python37" exec_prefix = "E:\python37" installed_base = "E:\python37" installed_platbase = "E:\python37" platbase = "E:\python37" prefix = "E:\python37" projectbase = "E:\python37" py_version = "3.7.2" py_version_nodot = "37" py_version_short = "3.7" srcdir = "E:\python37" userbase = "C:\Users\acer\AppData\Roaming\Python"
[ { "code": null, "e": 1268, "s": 1062, "text": "Configuration information of Python's installation can be accessed by the sysconfig module. For example the list of installation paths and the configuration variables specific to the installation platform." }, { "code": null, "e": 1356, "s": 1268, "text": "The sysconfig module provides the following functions to access Configuration variables" }, { "code": null, "e": 1476, "s": 1356, "text": "With no arguments, this function returns a dictionary of all configuration variables relevant for the current platform." }, { "code": null, "e": 2116, "s": 1476, "text": ">>> import sysconfig\n>>> sysconfig.get_config_vars()\n{'prefix': 'E:\\\\python37', 'exec_prefix': 'E:\\\\python37', 'py_version': '3.7.2', 'py_version_short':\n'3.7', 'py_version_nodot': '37', 'installed_base': 'E:\\\\python37', 'base': 'E:\\\\python37',\n'installed_platbase': 'E:\\\\python37', 'platbase': 'E:\\\\python37', 'projectbase': 'E:\\\\python37',\n'abiflags': '', 'LIBDEST': 'E:\\\\python37\\\\Lib', 'BINLIBDEST': 'E:\\\\python37\\\\Lib', 'INCLUDEPY':\n'E:\\\\python37\\\\Include', 'EXT_SUFFIX': '.pyd', 'EXE': '.exe', 'VERSION': '37', 'BINDIR':\n'E:\\\\python37', 'SO': '.pyd', 'userbase': 'C:\\\\Users\\\\acer\\\\AppData\\\\Roaming\\\\Python', 'srcdir':\n'E:\\\\python37'}" }, { "code": null, "e": 2234, "s": 2116, "text": "With arguments, return a list of values for specific keys. For each argument, if the value is not found, return None." }, { "code": null, "e": 2303, "s": 2234, "text": ">>> sysconfig.get_config_vars('base','EXE')\n['E:\\\\python37', '.exe']" }, { "code": null, "e": 2462, "s": 2303, "text": "This function returns the value of a single variable name. This is equivalent to get_config_vars().get(name). If name is not found, the function returns None." }, { "code": null, "e": 2561, "s": 2462, "text": ">>> sysconfig.get_config_var('VERSION')\n'37'\n>>> sysconfig.get_config_var('srcdir')\n'E:\\\\python37'" }, { "code": null, "e": 2711, "s": 2561, "text": "Python uses an installation scheme that differs depending on the platform and on the installation options. Following schemes are currently supported:" }, { "code": null, "e": 2801, "s": 2711, "text": "This function returns a tuple containing all path names currently supported in sysconfig." }, { "code": null, "e": 2909, "s": 2801, "text": ">>> sysconfig.get_path_names()\n('stdlib', 'platstdlib', 'purelib', 'platlib', 'include', 'scripts', 'data')" }, { "code": null, "e": 3007, "s": 2909, "text": "Each scheme is composed of a various paths having unique identifier. The path names are as below:" }, { "code": null, "e": 3117, "s": 3007, "text": "This function returns installation path corresponding to the path name, from the install scheme named scheme." }, { "code": null, "e": 3175, "s": 3117, "text": ">>> sysconfig.get_path('include')\n'E:\\\\python37\\\\Include'" }, { "code": null, "e": 3216, "s": 3175, "text": ">>> sysconfig.get_platform()\n'win-amd64'" }, { "code": null, "e": 3289, "s": 3216, "text": "This function returns the MAJOR.MINOR Python version number as a string." }, { "code": null, "e": 3358, "s": 3289, "text": "This function returns a string that identifies the current platform." }, { "code": null, "e": 3463, "s": 3358, "text": "The configuration variables and their values can also be accessed using sysconfig module with –m option." }, { "code": null, "e": 4465, "s": 3463, "text": "E:\\python37>python -m sysconfig\nPlatform: \"win-amd64\"\nPython version: \"3.7\"\nCurrent installation scheme: \"nt\"\nPaths:\n data = \"E:\\python37\"\n include = \"E:\\python37\\Include\"\n platinclude = \"E:\\python37\\Include\"\n platlib = \"E:\\python37\\Lib\\site-packages\"\n platstdlib = \"E:\\python37\\Lib\"\n purelib = \"E:\\python37\\Lib\\site-packages\"\n scripts = \"E:\\python37\\Scripts\"\n stdlib = \"E:\\python37\\Lib\"\nVariables:\n BINDIR = \"E:\\python37\"\n BINLIBDEST = \"E:\\python37\\Lib\"\n EXE = \".exe\"\n EXT_SUFFIX = \".pyd\"\n INCLUDEPY = \"E:\\python37\\Include\"\n LIBDEST = \"E:\\python37\\Lib\"\n SO = \".pyd\"\n VERSION = \"37\"\n abiflags = \"\"\n base = \"E:\\python37\"\n exec_prefix = \"E:\\python37\"\n installed_base = \"E:\\python37\"\n installed_platbase = \"E:\\python37\"\n platbase = \"E:\\python37\"\n prefix = \"E:\\python37\"\n projectbase = \"E:\\python37\"\n py_version = \"3.7.2\"\n py_version_nodot = \"37\"\n py_version_short = \"3.7\"\n srcdir = \"E:\\python37\"\n userbase = \"C:\\Users\\acer\\AppData\\Roaming\\Python\"" } ]
SQL - Comparison Operators
Consider the CUSTOMERS table having the following records − SQL> SELECT * FROM CUSTOMERS; +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ 7 rows in set (0.00 sec) Here are some simple examples showing the usage of SQL Comparison Operators − SQL> SELECT * FROM CUSTOMERS WHERE SALARY > 5000; +----+----------+-----+---------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+---------+----------+ | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+---------+----------+ 3 rows in set (0.00 sec) SQL> SELECT * FROM CUSTOMERS WHERE SALARY = 2000; +----+---------+-----+-----------+---------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+---------+-----+-----------+---------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 3 | kaushik | 23 | Kota | 2000.00 | +----+---------+-----+-----------+---------+ 2 rows in set (0.00 sec) SQL> SELECT * FROM CUSTOMERS WHERE SALARY != 2000; +----+----------+-----+---------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+---------+----------+ | 2 | Khilan | 25 | Delhi | 1500.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+---------+----------+ 5 rows in set (0.00 sec) SQL> SELECT * FROM CUSTOMERS WHERE SALARY <> 2000; +----+----------+-----+---------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+---------+----------+ | 2 | Khilan | 25 | Delhi | 1500.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+---------+----------+ 5 rows in set (0.00 sec) SQL> SELECT * FROM CUSTOMERS WHERE SALARY >= 6500; +----+----------+-----+---------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+---------+----------+ | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+---------+----------+ 3 rows in set (0.00 sec) 42 Lectures 5 hours Anadi Sharma 14 Lectures 2 hours Anadi Sharma 44 Lectures 4.5 hours Anadi Sharma 94 Lectures 7 hours Abhishek And Pukhraj 80 Lectures 6.5 hours Oracle Master Training | 150,000+ Students Worldwide 31 Lectures 6 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2513, "s": 2453, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 2543, "s": 2513, "text": "SQL> SELECT * FROM CUSTOMERS;" }, { "code": null, "e": 3086, "s": 2543, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n7 rows in set (0.00 sec)\n" }, { "code": null, "e": 3164, "s": 3086, "text": "Here are some simple examples showing the usage of SQL Comparison Operators −" }, { "code": null, "e": 3214, "s": 3164, "text": "SQL> SELECT * FROM CUSTOMERS WHERE SALARY > 5000;" }, { "code": null, "e": 3555, "s": 3214, "text": "+----+----------+-----+---------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+---------+----------+\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+---------+----------+\n3 rows in set (0.00 sec)\n" }, { "code": null, "e": 3606, "s": 3555, "text": "SQL> SELECT * FROM CUSTOMERS WHERE SALARY = 2000;" }, { "code": null, "e": 3902, "s": 3606, "text": "+----+---------+-----+-----------+---------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+---------+-----+-----------+---------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n+----+---------+-----+-----------+---------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 3954, "s": 3902, "text": "SQL> SELECT * FROM CUSTOMERS WHERE SALARY != 2000;" }, { "code": null, "e": 4385, "s": 3954, "text": "+----+----------+-----+---------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+---------+----------+\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+---------+----------+\n5 rows in set (0.00 sec)\n" }, { "code": null, "e": 4436, "s": 4385, "text": "SQL> SELECT * FROM CUSTOMERS WHERE SALARY <> 2000;" }, { "code": null, "e": 4867, "s": 4436, "text": "+----+----------+-----+---------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+---------+----------+\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+---------+----------+\n5 rows in set (0.00 sec)\n" }, { "code": null, "e": 4918, "s": 4867, "text": "SQL> SELECT * FROM CUSTOMERS WHERE SALARY >= 6500;" }, { "code": null, "e": 5259, "s": 4918, "text": "+----+----------+-----+---------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+---------+----------+\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+---------+----------+\n3 rows in set (0.00 sec)\n" }, { "code": null, "e": 5292, "s": 5259, "text": "\n 42 Lectures \n 5 hours \n" }, { "code": null, "e": 5306, "s": 5292, "text": " Anadi Sharma" }, { "code": null, "e": 5339, "s": 5306, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 5353, "s": 5339, "text": " Anadi Sharma" }, { "code": null, "e": 5388, "s": 5353, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5402, "s": 5388, "text": " Anadi Sharma" }, { "code": null, "e": 5435, "s": 5402, "text": "\n 94 Lectures \n 7 hours \n" }, { "code": null, "e": 5457, "s": 5435, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 5492, "s": 5457, "text": "\n 80 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5546, "s": 5492, "text": " Oracle Master Training | 150,000+ Students Worldwide" }, { "code": null, "e": 5579, "s": 5546, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 5607, "s": 5579, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5614, "s": 5607, "text": " Print" }, { "code": null, "e": 5625, "s": 5614, "text": " Add Notes" } ]
grubby - Unix, Linux Command
On Intel x86 platforms, grub is the default bootloader and the configuration file is in /boot/grub/grub.conf. On Intel ia64 platforms, elilo mode is used and the default location for the configuration file is /boot/grub/grub.conf. On PowerPC platforms, yaboot parsing is used and the configuration file should be in /etc/yaboot.conf. There are a number of ways to specify the kernel used for --info, --remove-kernel, and --update-kernel. Specificying DEFAULT or ALL selects the default entry and all of the entries, respectively. If a comma separated list of numbers is given, the boot entries indexed by those numbers are selected. Finally, the title of a boot entry may be specified by using TITLE=title as the argument; all entries with that title are used. grub (8) grub (8) lilo (8) lilo (8) yaboot (8) yaboot (8) mkinitrd (8) mkinitrd (8) Erik Troan <[email protected]> Jeremy Katz <[email protected]> Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10917, "s": 10581, "text": "\nOn Intel x86 platforms, grub is the default bootloader and the\nconfiguration file is in /boot/grub/grub.conf. On Intel ia64 platforms,\nelilo mode is used and the default location for the configuration file\nis /boot/grub/grub.conf. On PowerPC platforms, yaboot parsing\nis used and the configuration file should be in /etc/yaboot.conf.\n" }, { "code": null, "e": 11346, "s": 10917, "text": "\nThere are a number of ways to specify the kernel used for --info,\n--remove-kernel, and --update-kernel. Specificying DEFAULT\nor ALL selects the default entry and all of the entries, respectively.\nIf a comma separated list of numbers is given, the boot entries indexed\nby those numbers are selected. Finally, the title of a boot entry may\nbe specified by using TITLE=title as the argument; all entries\nwith that title are used.\n" }, { "code": null, "e": 11417, "s": 11408, "text": "grub (8)" }, { "code": null, "e": 11426, "s": 11417, "text": "grub (8)" }, { "code": null, "e": 11435, "s": 11426, "text": "lilo (8)" }, { "code": null, "e": 11444, "s": 11435, "text": "lilo (8)" }, { "code": null, "e": 11455, "s": 11444, "text": "yaboot (8)" }, { "code": null, "e": 11466, "s": 11455, "text": "yaboot (8)" }, { "code": null, "e": 11479, "s": 11466, "text": "mkinitrd (8)" }, { "code": null, "e": 11492, "s": 11479, "text": "mkinitrd (8)" }, { "code": null, "e": 11552, "s": 11492, "text": "Erik Troan <[email protected]>\nJeremy Katz <[email protected]>\n" }, { "code": null, "e": 11569, "s": 11552, "text": "\nAdvertisements\n" }, { "code": null, "e": 11604, "s": 11569, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 11632, "s": 11604, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11666, "s": 11632, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11683, "s": 11666, "text": " Frahaan Hussain" }, { "code": null, "e": 11716, "s": 11683, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 11727, "s": 11716, "text": " Pradeep D" }, { "code": null, "e": 11762, "s": 11727, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11778, "s": 11762, "text": " Musab Zayadneh" }, { "code": null, "e": 11811, "s": 11778, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 11823, "s": 11811, "text": " GUHARAJANM" }, { "code": null, "e": 11855, "s": 11823, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 11863, "s": 11855, "text": " Uplatz" }, { "code": null, "e": 11870, "s": 11863, "text": " Print" }, { "code": null, "e": 11881, "s": 11870, "text": " Add Notes" } ]
Groovy - find()
The find method finds the first value in a collection that matches some criterion. Object find(Closure closure) The condition to be met by the collection element is specified in the closure that must be some Boolean expression. Return Value − The find method returns the first value found or null if no such element exists. Following is an example of the usage of this method − class Example { static void main(String[] args) { def lst = [1,2,3,4]; def value; value = lst.find {element -> element > 2} println(value); } } When we run the above program, we will get the following result − 3 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2321, "s": 2238, "text": "The find method finds the first value in a collection that matches some criterion." }, { "code": null, "e": 2351, "s": 2321, "text": "Object find(Closure closure)\n" }, { "code": null, "e": 2467, "s": 2351, "text": "The condition to be met by the collection element is specified in the closure that must be some Boolean expression." }, { "code": null, "e": 2563, "s": 2467, "text": "Return Value − The find method returns the first value found or null if no such element exists." }, { "code": null, "e": 2617, "s": 2563, "text": "Following is an example of the usage of this method −" }, { "code": null, "e": 2795, "s": 2617, "text": "class Example {\n static void main(String[] args) {\n def lst = [1,2,3,4];\n def value;\n\t\t\n value = lst.find {element -> element > 2}\n println(value);\n } \n}" }, { "code": null, "e": 2861, "s": 2795, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 2864, "s": 2861, "text": "3\n" }, { "code": null, "e": 2897, "s": 2864, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 2915, "s": 2897, "text": " Krishna Sakinala" }, { "code": null, "e": 2950, "s": 2915, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2968, "s": 2950, "text": " Packt Publishing" }, { "code": null, "e": 2975, "s": 2968, "text": " Print" }, { "code": null, "e": 2986, "s": 2975, "text": " Add Notes" } ]
MySQL - LOAD DATA Statement
Using the LOAD DATA statement, you can insert the contents of a file (from the server or a host) into a MySQL table. If you use the LOCAL clause, you can upload the local files contents int to a table. Following is the syntax of the above statement − LOAD DATA [LOCAL] INFILE 'file_name' [REPLACE | IGNORE] INTO TABLE tble_name [{FIELDS | COLUMNS} [TERMINATED BY 'string'] [[OPTIONALLY] ENCLOSED BY 'char'] [ESCAPED BY 'char'] Before discussing some examples first of all, let us verify whether loading local data is enabled, if not you can observe the local_infile variable value as − mysql> SHOW GLOBAL VARIABLES LIKE 'local_infile'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | local_infile | OFF | +---------------+-------+ 1 row in set (0.57 sec) Before you load data from a file make sure you have enabled local_infile option as − mysql> SET GLOBAL local_infile = 'ON'; Query OK, 0 rows affected (0.09 sec) Make you grant file (or, all) privileges to the database in which your table exist − GRANT ALL ON test.* TO 'root'@'localhost'; Assume we have created a table using the CREATE statement as shown below − mysql> CREATE TABLE DEMO (NAME VARCHAR(20)); Query OK, 0 rows affected (6.72 sec) And if we have a file named test.txt with contents as − 'Raju' 'Swami' 'Deva' 'Vanaja' Following query loads the contents of the test.txt file in the above created table − mysql> load data infile "directory path/test.txt" into table DEMO; Query OK, 4 rows affected (1.35 sec) Records: 4 Deleted: 0 Skipped: 0 Warnings: 0 If you verify the contents of the DEMO table you can observe the records in it as − mysql> select * from DEMO; +----------+ | NAME | +----------+ | Raju | | Swami | | Deva | | Vanaja | +----------+ 4 rows in set (0.00 sec) Using the clauses FIELDS and LINES you can choose the field and line terminators in the file from which you need to load data. Assume we have created a table using the CREATE statement as shown below − mysql> CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, INCOME INT); Query OK, 0 rows affected (0.36 sec) And if we have a file named data.csv with contents as − Krishna,Sharma,19,2000 Raj,Kandukuri,20,7000 Ramya,Ramapriya,25,5000 Alexandra,Botez,26,2000 Following query loads the contents of the data.csv file in to the above created table − load data infile "Data Directory Path/data.csv" into table employee FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'; If you verify the contents of the DEMO table you can observe the records in it as − mysql> select * from employee; +-------------+-------------+------+--------+ | FIRST_NAME | LAST_NAME | AGE | INCOME | +-------------+-------------+------+--------+ | Krishna | Sharma | 19 | 2000 | | Raj | Kandukuri | 20 | 7000 | | Ramya | Ramapriya | 25 | 5000 | | Alexandra | Botez | 26 | 2000 | +-------------+-------------+------+--------+ 4 rows in set (0.00 sec) Using the STARTING BY clause you can use a particular sting to mark the starting of a record or a field. Assume we have a text file sample.txt with the following contents − $Krishna,Sharma,19,2000 $Raj,Kandukuri,20,7000 $Ramya,Ramapriya,25,5000 $Alexandra,Botez,26,2000 Following query inserts the contents of the above text file into the employee table − mysql> load data infile "directory path/sample.txt" into table employee FIELDS TERMINATED BY ',' LINES STARTING BY '$'; Query OK, 4 rows affected (0.25 sec) Records: 4 Deleted: 0 Skipped: 0 Warnings: 0 If you verify the contents of the EMPLOYEE table you can observe the records in it as − mysql> SELECT * FROM employee; +------------+-----------+------+--------+ | FIRST_NAME | LAST_NAME | AGE | INCOME | +------------+-----------+------+--------+ | Krishna | Sharma | 19 | 2000 | | Raj | Kandukuri | 20 | 7000 | | Ramya | Ramapriya | 25 | 5000 | | Alexandra | Botez | 26 | 2000 | +------------+-----------+------+--------+ 4 rows in set (0.00 sec) You can also upload only specific column values from a text file. To do so you need to specify the column names in the query. Assume we have text file named test.txt with the following contents − 100,Thomas,5000 200,Jason,5500 30,Mayla,7000 40,Nisha,9500 50,Randy,6000 You need to place the names of the columns at the end of the query following query inserts the contents of the test.txt file in the employee table − mysql> LOAD DATA INFILE 'Directory Path/test.txt' INTO TABLE employee FIELDS TERMINATED BY ',' (age, first_name, income); Query OK, 5 rows affected (2.47 sec) Records: 5 Deleted: 0 Skipped: 0 Warnings: 0 Since we didn’t have values for the column last_name in the file all the values for this column will be NULL as shown below. mysql> SELECT * FROM EMPLOYEE; +------------+-----------+------+--------+ | FIRST_NAME | LAST_NAME | AGE | INCOME | +------------+-----------+------+--------+ | Thomas | NULL | 100 | 5000 | | Jason | NULL | 200 | 5500 | | Mayla | NULL | 30 | 7000 | | Nisha | NULL | 40 | 9500 | | Randy | NULL | 50 | 6000 | +------------+-----------+------+--------+ 9 rows in set (0.00 sec) In the LOAD statement you can treat the values from the file as user variables, preprocess them and generate value for other columns. Then you can assign this generated value to the desired column using the SET clause. Assume we have created a table with name test which stores name average score of a person (in 3 subjects) as shown below − mysql> CREATE TABLE TEST (NAME VARCHAR(10), AVG INT); Query OK, 0 rows affected (5.71 sec) Assume we have a file containing name and scores (in all 3 subjects) of a person as follow − Radha, 25, 30, 35 Swami, 28, 36, 31 Deva, 32, 30, 29 Vanaja, 31, 24, 14 Following query reads the scores of each employee as variables, calculates the average score and stores the result in the avg column using the SET clause. mysql> LOAD DATA INFILE 'Data Directory/test.txt' INTO TABLE test FIELDS TERMINATED BY ',' (name, @m1, @m2, @m3, @avg) SET avg = (@m1+@m2+@m3)/3; Query OK, 4 rows affected (2.85 sec) Records: 4 Deleted: 0 Skipped: 0 Warnings: 0 After executing the LOAD statement, you can verify the contents of the test table as shown below − mysql> select * from test; +---------+------+ | NAME | AVG | +---------+------+ | Radha | 30 | | Swami | 32 | | Deva | 30 | | Vanaja | 23 | +---------+------+ 4 rows in set (0.00 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2535, "s": 2333, "text": "Using the LOAD DATA statement, you can insert the contents of a file (from the server or a host) into a MySQL table. If you use the LOCAL clause, you can upload the local files contents int to a table." }, { "code": null, "e": 2584, "s": 2535, "text": "Following is the syntax of the above statement −" }, { "code": null, "e": 2815, "s": 2584, "text": "LOAD DATA\n [LOCAL]\n INFILE 'file_name'\n [REPLACE | IGNORE]\n INTO TABLE tble_name\n [{FIELDS | COLUMNS}\n [TERMINATED BY 'string']\n [[OPTIONALLY] ENCLOSED BY 'char']\n [ESCAPED BY 'char']\n" }, { "code": null, "e": 2974, "s": 2815, "text": "Before discussing some examples first of all, let us verify whether loading local data is enabled, if not you can observe the local_infile variable value as −" }, { "code": null, "e": 3179, "s": 2974, "text": "mysql> SHOW GLOBAL VARIABLES LIKE 'local_infile';\n+---------------+-------+\n| Variable_name | Value |\n+---------------+-------+\n| local_infile | OFF |\n+---------------+-------+\n1 row in set (0.57 sec)\n" }, { "code": null, "e": 3264, "s": 3179, "text": "Before you load data from a file make sure you have enabled local_infile option as −" }, { "code": null, "e": 3341, "s": 3264, "text": "mysql> SET GLOBAL local_infile = 'ON';\nQuery OK, 0 rows affected (0.09 sec)\n" }, { "code": null, "e": 3426, "s": 3341, "text": "Make you grant file (or, all) privileges to the database in which your table exist −" }, { "code": null, "e": 3470, "s": 3426, "text": "GRANT ALL ON test.* TO 'root'@'localhost';\n" }, { "code": null, "e": 3545, "s": 3470, "text": "Assume we have created a table using the CREATE statement as shown below −" }, { "code": null, "e": 3627, "s": 3545, "text": "mysql> CREATE TABLE DEMO (NAME VARCHAR(20));\nQuery OK, 0 rows affected (6.72 sec)" }, { "code": null, "e": 3683, "s": 3627, "text": "And if we have a file named test.txt with contents as −" }, { "code": null, "e": 3714, "s": 3683, "text": "'Raju'\n'Swami'\n'Deva'\n'Vanaja'" }, { "code": null, "e": 3799, "s": 3714, "text": "Following query loads the contents of the test.txt file in the above created table −" }, { "code": null, "e": 3948, "s": 3799, "text": "mysql> load data infile \"directory path/test.txt\" into table DEMO;\nQuery OK, 4 rows affected (1.35 sec)\nRecords: 4 Deleted: 0 Skipped: 0 Warnings: 0" }, { "code": null, "e": 4032, "s": 3948, "text": "If you verify the contents of the DEMO table you can observe the records in it as −" }, { "code": null, "e": 4188, "s": 4032, "text": "mysql> select * from DEMO;\n+----------+\n| NAME |\n+----------+\n| Raju |\n| Swami |\n| Deva |\n| Vanaja |\n+----------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 4315, "s": 4188, "text": "Using the clauses FIELDS and LINES you can choose the field and line terminators in the file from which you need to load data." }, { "code": null, "e": 4390, "s": 4315, "text": "Assume we have created a table using the CREATE statement as shown below −" }, { "code": null, "e": 4541, "s": 4390, "text": "mysql> CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n INCOME INT);\nQuery OK, 0 rows affected (0.36 sec)" }, { "code": null, "e": 4597, "s": 4541, "text": "And if we have a file named data.csv with contents as −" }, { "code": null, "e": 4690, "s": 4597, "text": "Krishna,Sharma,19,2000\nRaj,Kandukuri,20,7000\nRamya,Ramapriya,25,5000\nAlexandra,Botez,26,2000" }, { "code": null, "e": 4778, "s": 4690, "text": "Following query loads the contents of the data.csv file in to the above created table −" }, { "code": null, "e": 4897, "s": 4778, "text": "load data infile \"Data Directory Path/data.csv\" into table employee\nFIELDS TERMINATED BY ','\nLINES TERMINATED BY '\\n';" }, { "code": null, "e": 4981, "s": 4897, "text": "If you verify the contents of the DEMO table you can observe the records in it as −" }, { "code": null, "e": 5405, "s": 4981, "text": "mysql> select * from employee;\n+-------------+-------------+------+--------+\n| FIRST_NAME | LAST_NAME | AGE | INCOME |\n+-------------+-------------+------+--------+\n| Krishna | Sharma | 19 | 2000 |\n| Raj | Kandukuri | 20 | 7000 |\n| Ramya | Ramapriya | 25 | 5000 |\n| Alexandra | Botez | 26 | 2000 |\n+-------------+-------------+------+--------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 5510, "s": 5405, "text": "Using the STARTING BY clause you can use a particular sting to mark the starting of a record or a field." }, { "code": null, "e": 5578, "s": 5510, "text": "Assume we have a text file sample.txt with the following contents −" }, { "code": null, "e": 5675, "s": 5578, "text": "$Krishna,Sharma,19,2000\n$Raj,Kandukuri,20,7000\n$Ramya,Ramapriya,25,5000\n$Alexandra,Botez,26,2000" }, { "code": null, "e": 5761, "s": 5675, "text": "Following query inserts the contents of the above text file into the employee table −" }, { "code": null, "e": 5963, "s": 5761, "text": "mysql> load data infile \"directory path/sample.txt\" into table employee FIELDS TERMINATED BY ',' LINES STARTING BY '$';\nQuery OK, 4 rows affected (0.25 sec)\nRecords: 4 Deleted: 0 Skipped: 0 Warnings: 0" }, { "code": null, "e": 6051, "s": 5963, "text": "If you verify the contents of the EMPLOYEE table you can observe the records in it as −" }, { "code": null, "e": 6451, "s": 6051, "text": "mysql> SELECT * FROM employee;\n+------------+-----------+------+--------+\n| FIRST_NAME | LAST_NAME | AGE | INCOME |\n+------------+-----------+------+--------+\n| Krishna | Sharma | 19 | 2000 |\n| Raj | Kandukuri | 20 | 7000 |\n| Ramya | Ramapriya | 25 | 5000 |\n| Alexandra | Botez | 26 | 2000 |\n+------------+-----------+------+--------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 6577, "s": 6451, "text": "You can also upload only specific column values from a text file. To do so you need to specify the column names in the query." }, { "code": null, "e": 6647, "s": 6577, "text": "Assume we have text file named test.txt with the following contents −" }, { "code": null, "e": 6721, "s": 6647, "text": "100,Thomas,5000\n200,Jason,5500\n30,Mayla,7000\n40,Nisha,9500\n50,Randy,6000\n" }, { "code": null, "e": 6870, "s": 6721, "text": "You need to place the names of the columns at the end of the query following query inserts the contents of the test.txt file in the employee table −" }, { "code": null, "e": 7074, "s": 6870, "text": "mysql> LOAD DATA INFILE 'Directory Path/test.txt'\nINTO TABLE employee\nFIELDS TERMINATED BY ','\n(age, first_name, income);\nQuery OK, 5 rows affected (2.47 sec)\nRecords: 5 Deleted: 0 Skipped: 0 Warnings: 0" }, { "code": null, "e": 7199, "s": 7074, "text": "Since we didn’t have values for the column last_name in the file all the values for this column will be NULL as shown below." }, { "code": null, "e": 7642, "s": 7199, "text": "mysql> SELECT * FROM EMPLOYEE;\n+------------+-----------+------+--------+\n| FIRST_NAME | LAST_NAME | AGE | INCOME |\n+------------+-----------+------+--------+\n| Thomas | NULL | 100 | 5000 |\n| Jason | NULL | 200 | 5500 |\n| Mayla | NULL | 30 | 7000 |\n| Nisha | NULL | 40 | 9500 |\n| Randy | NULL | 50 | 6000 |\n+------------+-----------+------+--------+\n9 rows in set (0.00 sec)" }, { "code": null, "e": 7861, "s": 7642, "text": "In the LOAD statement you can treat the values from the file as user variables, preprocess them and generate value for other columns. Then you can assign this generated value to the desired column using the SET clause." }, { "code": null, "e": 7984, "s": 7861, "text": "Assume we have created a table with name test which stores name average score of a person (in 3 subjects) as shown below −" }, { "code": null, "e": 8075, "s": 7984, "text": "mysql> CREATE TABLE TEST (NAME VARCHAR(10), AVG INT);\nQuery OK, 0 rows affected (5.71 sec)" }, { "code": null, "e": 8168, "s": 8075, "text": "Assume we have a file containing name and scores (in all 3 subjects) of a person as follow −" }, { "code": null, "e": 8241, "s": 8168, "text": "Radha, 25, 30, 35\nSwami, 28, 36, 31\nDeva, 32, 30, 29\nVanaja, 31, 24, 14\n" }, { "code": null, "e": 8396, "s": 8241, "text": "Following query reads the scores of each employee as variables, calculates the average score and stores the result in the avg column using the SET clause." }, { "code": null, "e": 8636, "s": 8396, "text": "mysql> LOAD DATA INFILE 'Data Directory/test.txt'\n INTO TABLE test\n FIELDS TERMINATED BY ','\n (name, @m1, @m2, @m3, @avg)\n SET avg = (@m1+@m2+@m3)/3;\nQuery OK, 4 rows affected (2.85 sec)\nRecords: 4 Deleted: 0 Skipped: 0 Warnings: 0" }, { "code": null, "e": 8735, "s": 8636, "text": "After executing the LOAD statement, you can verify the contents of the test table as shown below −" }, { "code": null, "e": 8939, "s": 8735, "text": "mysql> select * from test;\n+---------+------+\n| NAME | AVG |\n+---------+------+\n| Radha | 30 |\n| Swami | 32 |\n| Deva | 30 |\n| Vanaja | 23 |\n+---------+------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 8972, "s": 8939, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 9000, "s": 8972, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 9035, "s": 9000, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9052, "s": 9035, "text": " Frahaan Hussain" }, { "code": null, "e": 9086, "s": 9052, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9121, "s": 9086, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 9155, "s": 9121, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 9183, "s": 9155, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 9216, "s": 9183, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 9236, "s": 9216, "text": " Harshit Srivastava" }, { "code": null, "e": 9269, "s": 9236, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 9287, "s": 9269, "text": " Trevoir Williams" }, { "code": null, "e": 9294, "s": 9287, "text": " Print" }, { "code": null, "e": 9305, "s": 9294, "text": " Add Notes" } ]
Logstash - Supported Inputs
Logstash supports a huge range of logs from different sources. It is working with famous sources as explained below. System events and other time activities are recorded in metrics. Logstash can access the log from system metrics and process them using filters. This helps to show the user the live feed of the events in a customized manner. Metrics are flushed according to the flush_interval setting of metrics filter and by default; it is set to 5 seconds. We are tracking the test metrics generated by Logstash, by gathering and analyzing the events running through Logstash and showing the live feed on the command prompt. This configuration contains a generator plugin, which is offered by Logstash for test metrics and set the type setting to “generated” for parsing. In the filtering phase, we are only processing the lines with a generated type by using the ‘if’ statement. Then, the metrics plugin counts the field specified in meter settings. The metrics plugin flushes the count after every 5 seconds specified in the flush_interval. Lastly, output the filter events to a standard output like command prompt using the codec plugin for formatting. The Codec plugin is using [events][rate_1m] value to output the per second events in a 1-minute sliding window. input { generator { type => "generated" } } filter { if [type] == "generated" { metrics { meter => "events" add_tag => "metric" } } } output { # only emit events with the 'metric' tag if "metric" in [tags] { stdout { codec => line { format => "rate: %{[events][rate_1m]}" } } } We can run Logstash by using the following command. >logsaths –f logstash.conf rate: 1308.4 rate: 1308.4 rate: 1368.654529135342 rate: 1416.4796003951449 rate: 1464.974293984808 rate: 1523.3119444107458 rate: 1564.1602979542715 rate: 1610.6496496890895 rate: 1645.2184750334154 rate: 1688.7768007612485 rate: 1714.652283095914 rate: 1752.5150680019278 rate: 1785.9432934744932 rate: 1806.912181962126 rate: 1836.0070454626025 rate: 1849.5669494173826 rate: 1871.3814756851832 rate: 1883.3443123790712 rate: 1906.4879113216743 rate: 1925.9420717997118 rate: 1934.166137658981 rate: 1954.3176526556897 rate: 1957.0107444542625 Web servers generate a large number of logs regarding user access and errors. Logstash helps to extract the logs from different servers using input plugins and stash them in a centralized location. We are extracting the data from the stderr logs of the local Apache Tomcat Server and stashing it in the output.log. This Logstash configuration file directs Logstash to read apache error logs and add a tag named “apache-error”. We can simply send it to the output.log using the file output plugin. input { file { path => "C:/Program Files/Apache Software Foundation/Tomcat 7.0 /logs/*stderr*" type => "apache-error" } } output { file { path => "C:/tpwork/logstash/bin/log/output.log" } } We can run Logstash by using the following command. >Logstash –f Logstash.conf This is the sample stderr log, which generates when the server events occur in Apache Tomcat. C:\Program Files\Apache Software Foundation\Tomcat 7.0\logs\ tomcat7-stderr.2016-12-25.log Dec 25, 2016 7:05:14 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["http-bio-9999"] Dec 25, 2016 7:05:14 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["ajp-bio-8009"] Dec 25, 2016 7:05:14 PM org.apache.catalina.startup.Catalina start INFO: Server startup in 823 ms { "path":"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/ tomcat7-stderr.2016-12-25.log","@timestamp":"2016-12-25T11:05:27.045Z", "@version":"1","host":"Dell-PC", "message":"Dec 25, 2016 7:05:14 PM org.apache.coyote.AbstractProtocol start\r", "type":"apache-error","tags":[] } { "path":"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/ tomcat7-stderr.2016-12-25.log","@timestamp":"2016-12-25T11:05:27.045Z", "@version":"1","host":"Dell-PC", "message":"INFO: Starting ProtocolHandler [ \"ajp-bio-8009\"]\r","type":"apache-error","tags":[] } { "path":"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/ tomcat7-stderr.2016-12-25.log","@timestamp":"2016-12-25T11:05:27.045Z", "@version":"1","host":"Dell-PC", "message":"Dec 25, 2016 7:05:14 PM org.apache.catalina.startup.Catalina start\r", "type":"apache-error","tags":[] } { "path":"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/ tomcat7-stderr.2016-12-25.log","@timestamp":"2016-12-25T11:05:27.045Z", "@version":"1","host":"Dell-PC", "message":"INFO: Server startup in 823 ms\r","type":"apache-error","tags":[] } To start with, let us understand how to Configure MySQL for logging. Add the following lines in my.ini file of the MySQL database server under [mysqld]. In windows, it is present inside the installation directory of MySQL, which is in − C:\wamp\bin\mysql\mysql5.7.11 In UNIX, you can find it in – /etc/mysql/my.cnf general_log_file = "C:/wamp/logs/queries.log" general_log = 1 In this config file, file plugin is used to read the MySQL log and write it to the ouput.log. input { file { path => "C:/wamp/logs/queries.log" } } output { file { path => "C:/tpwork/logstash/bin/log/output.log" } } This is the log generated by queries executed in the MySQL database. 2016-12-25T13:05:36.854619Z 2 Query select * from test1_users 2016-12-25T13:05:51.822475Z 2 Query select count(*) from users 2016-12-25T13:05:59.998942Z 2 Query select count(*) from test1_users { "path":"C:/wamp/logs/queries.log","@timestamp":"2016-12-25T13:05:37.905Z", "@version":"1","host":"Dell-PC", "message":"2016-12-25T13:05:36.854619Z 2 Query\tselect * from test1_users", "tags":[] } { "path":"C:/wamp/logs/queries.log","@timestamp":"2016-12-25T13:05:51.938Z", "@version":"1","host":"Dell-PC", "message":"2016-12-25T13:05:51.822475Z 2 Query\tselect count(*) from users", "tags":[] } { "path":"C:/wamp/logs/queries.log","@timestamp":"2016-12-25T13:06:00.950Z", "@version":"1","host":"Dell-PC", "message":"2016-12-25T13:05:59.998942Z 2 Query\tselect count(*) from test1_users", "tags":[] } Print Add Notes Bookmark this page
[ { "code": null, "e": 2172, "s": 2055, "text": "Logstash supports a huge range of logs from different sources. It is working with famous sources as explained below." }, { "code": null, "e": 2515, "s": 2172, "text": "System events and other time activities are recorded in metrics. Logstash can access the log from system metrics and process them using filters. This helps to show the user the live feed of the events in a customized manner. Metrics are flushed according to the flush_interval setting of metrics filter and by default; it is set to 5 seconds." }, { "code": null, "e": 2683, "s": 2515, "text": "We are tracking the test metrics generated by Logstash, by gathering and analyzing the events running through Logstash and showing the live feed on the command prompt." }, { "code": null, "e": 3101, "s": 2683, "text": "This configuration contains a generator plugin, which is offered by Logstash for test metrics and set the type setting to “generated” for parsing. In the filtering phase, we are only processing the lines with a generated type by using the ‘if’ statement. Then, the metrics plugin counts the field specified in meter settings. The metrics plugin flushes the count after every 5 seconds specified in the flush_interval." }, { "code": null, "e": 3326, "s": 3101, "text": "Lastly, output the filter events to a standard output like command prompt using the codec plugin for formatting. The Codec plugin is using [events][rate_1m] value to output the per second events in a 1-minute sliding window." }, { "code": null, "e": 3682, "s": 3326, "text": "input {\n generator {\n \ttype => \"generated\"\n }\n}\nfilter {\n if [type] == \"generated\" {\n metrics {\n meter => \"events\"\n add_tag => \"metric\"\n }\n }\n}\noutput {\n # only emit events with the 'metric' tag\n if \"metric\" in [tags] {\n stdout {\n codec => line { format => \"rate: %{[events][rate_1m]}\"\n }\n }\n}" }, { "code": null, "e": 3734, "s": 3682, "text": "We can run Logstash by using the following command." }, { "code": null, "e": 3762, "s": 3734, "text": ">logsaths –f logstash.conf\n" }, { "code": null, "e": 4309, "s": 3762, "text": "rate: 1308.4\nrate: 1308.4\nrate: 1368.654529135342\nrate: 1416.4796003951449\nrate: 1464.974293984808\nrate: 1523.3119444107458\nrate: 1564.1602979542715\nrate: 1610.6496496890895\nrate: 1645.2184750334154\nrate: 1688.7768007612485\nrate: 1714.652283095914\nrate: 1752.5150680019278\nrate: 1785.9432934744932\nrate: 1806.912181962126\nrate: 1836.0070454626025\nrate: 1849.5669494173826\nrate: 1871.3814756851832\nrate: 1883.3443123790712\nrate: 1906.4879113216743\nrate: 1925.9420717997118\nrate: 1934.166137658981\nrate: 1954.3176526556897\nrate: 1957.0107444542625\n" }, { "code": null, "e": 4507, "s": 4309, "text": "Web servers generate a large number of logs regarding user access and errors. Logstash helps to extract the logs from different servers using input plugins and stash them in a centralized location." }, { "code": null, "e": 4624, "s": 4507, "text": "We are extracting the data from the stderr logs of the local Apache Tomcat Server and stashing it in the output.log." }, { "code": null, "e": 4806, "s": 4624, "text": "This Logstash configuration file directs Logstash to read apache error logs and add a tag named “apache-error”. We can simply send it to the output.log using the file output plugin." }, { "code": null, "e": 5029, "s": 4806, "text": "input {\n file {\n path => \"C:/Program Files/Apache Software Foundation/Tomcat 7.0 /logs/*stderr*\"\n type => \"apache-error\" \n }\n} \noutput {\n file {\n path => \"C:/tpwork/logstash/bin/log/output.log\"\n }\n}" }, { "code": null, "e": 5081, "s": 5029, "text": "We can run Logstash by using the following command." }, { "code": null, "e": 5109, "s": 5081, "text": ">Logstash –f Logstash.conf\n" }, { "code": null, "e": 5203, "s": 5109, "text": "This is the sample stderr log, which generates when the server events occur in Apache Tomcat." }, { "code": null, "e": 5294, "s": 5203, "text": "C:\\Program Files\\Apache Software Foundation\\Tomcat 7.0\\logs\\ tomcat7-stderr.2016-12-25.log" }, { "code": null, "e": 5620, "s": 5294, "text": "Dec 25, 2016 7:05:14 PM org.apache.coyote.AbstractProtocol start\nINFO: Starting ProtocolHandler [\"http-bio-9999\"]\nDec 25, 2016 7:05:14 PM org.apache.coyote.AbstractProtocol start\nINFO: Starting ProtocolHandler [\"ajp-bio-8009\"]\nDec 25, 2016 7:05:14 PM org.apache.catalina.startup.Catalina start\nINFO: Server startup in 823 ms\n" }, { "code": null, "e": 6792, "s": 5620, "text": "{\n \"path\":\"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/\n tomcat7-stderr.2016-12-25.log\",\"@timestamp\":\"2016-12-25T11:05:27.045Z\",\n \"@version\":\"1\",\"host\":\"Dell-PC\",\n \"message\":\"Dec 25, 2016 7:05:14 PM org.apache.coyote.AbstractProtocol start\\r\",\n \"type\":\"apache-error\",\"tags\":[]\n}\n{\n \"path\":\"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/\n tomcat7-stderr.2016-12-25.log\",\"@timestamp\":\"2016-12-25T11:05:27.045Z\",\n \"@version\":\"1\",\"host\":\"Dell-PC\",\n \"message\":\"INFO: Starting ProtocolHandler [\n \\\"ajp-bio-8009\\\"]\\r\",\"type\":\"apache-error\",\"tags\":[]\n}\n{\n \"path\":\"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/\n tomcat7-stderr.2016-12-25.log\",\"@timestamp\":\"2016-12-25T11:05:27.045Z\",\n \"@version\":\"1\",\"host\":\"Dell-PC\",\n \"message\":\"Dec 25, 2016 7:05:14 PM org.apache.catalina.startup.Catalina start\\r\",\n \"type\":\"apache-error\",\"tags\":[]\n}\n{\n \"path\":\"C:/Program Files/Apache Software Foundation/Tomcat 7.0/logs/\n tomcat7-stderr.2016-12-25.log\",\"@timestamp\":\"2016-12-25T11:05:27.045Z\",\n \"@version\":\"1\",\"host\":\"Dell-PC\",\n \"message\":\"INFO: Server startup in 823 ms\\r\",\"type\":\"apache-error\",\"tags\":[]\n}" }, { "code": null, "e": 6945, "s": 6792, "text": "To start with, let us understand how to Configure MySQL for logging. Add the following lines in my.ini file of the MySQL database server under [mysqld]." }, { "code": null, "e": 7029, "s": 6945, "text": "In windows, it is present inside the installation directory of MySQL, which is in −" }, { "code": null, "e": 7060, "s": 7029, "text": "C:\\wamp\\bin\\mysql\\mysql5.7.11\n" }, { "code": null, "e": 7108, "s": 7060, "text": "In UNIX, you can find it in – /etc/mysql/my.cnf" }, { "code": null, "e": 7173, "s": 7108, "text": "general_log_file = \"C:/wamp/logs/queries.log\"\ngeneral_log = 1\n" }, { "code": null, "e": 7267, "s": 7173, "text": "In this config file, file plugin is used to read the MySQL log and write it to the ouput.log." }, { "code": null, "e": 7413, "s": 7267, "text": "input {\n file {\n path => \"C:/wamp/logs/queries.log\"\n }\n}\noutput {\n file {\n path => \"C:/tpwork/logstash/bin/log/output.log\"\n }\n}" }, { "code": null, "e": 7482, "s": 7413, "text": "This is the log generated by queries executed in the MySQL database." }, { "code": null, "e": 7694, "s": 7482, "text": "2016-12-25T13:05:36.854619Z 2 Query\t\tselect * from test1_users\n2016-12-25T13:05:51.822475Z 2 Query\tselect count(*) from users\n2016-12-25T13:05:59.998942Z 2 Query select count(*) from test1_users\n" }, { "code": null, "e": 8341, "s": 7694, "text": "{\n \"path\":\"C:/wamp/logs/queries.log\",\"@timestamp\":\"2016-12-25T13:05:37.905Z\",\n \"@version\":\"1\",\"host\":\"Dell-PC\",\n \"message\":\"2016-12-25T13:05:36.854619Z 2 Query\\tselect * from test1_users\",\n \"tags\":[]\n}\n{\n \"path\":\"C:/wamp/logs/queries.log\",\"@timestamp\":\"2016-12-25T13:05:51.938Z\",\n \"@version\":\"1\",\"host\":\"Dell-PC\",\n \"message\":\"2016-12-25T13:05:51.822475Z 2 Query\\tselect count(*) from users\",\n \"tags\":[]\n}\n{\n \"path\":\"C:/wamp/logs/queries.log\",\"@timestamp\":\"2016-12-25T13:06:00.950Z\",\n \"@version\":\"1\",\"host\":\"Dell-PC\",\n \"message\":\"2016-12-25T13:05:59.998942Z 2 Query\\tselect count(*) from test1_users\",\n \"tags\":[]\n}" }, { "code": null, "e": 8348, "s": 8341, "text": " Print" }, { "code": null, "e": 8359, "s": 8348, "text": " Add Notes" } ]
Convolutional Neural Network: Good Understanding of the Layers and an Image Classification Example | by Rashida Nasrin Sucky | Towards Data Science
The Convolutional Neural Network (CNN) is a multi-layered neural network that is known to be able to detect patterns and complex features. It has been useful in face detection, self-driving cars, and a lot more very complex tasks. In this article, I will give you a high-level idea of how a Convolutional Neural Network works. This article will cover: How a convolution layer works in the forward pass.How Pooling layer works.A complete model structure of a convolutional neural network for an Image Classification project.Analysis of the model summary.Training the model and displaying the result. How a convolution layer works in the forward pass. How Pooling layer works. A complete model structure of a convolutional neural network for an Image Classification project. Analysis of the model summary. Training the model and displaying the result. CNN can be used in so many different areas but in this article, we will talk about image classification examples. Image data can be expressed as numeric pixel values. Then these numeric values are passed into the CNN for processing. A normal neural network is also able to detect images but CNN is much more efficient both in terms of accuracy and speed. Convolution layers are very important layers in CNN because that’s what makes it a convolution neural network. In this layer, a filter or kernel is used to detect important features. The purpose is to make the dataset smaller and send only the important features to the next layer. This way it saves a lot of calculation in the dense layer and also ensures higher accuracy. Let’s have a look at a picture illustration. The picture above shows the input data of depth 3, a kernel of the same depth and bias terms. The next few pictures will show that step by step. Here is how the calculation works: Let’s fill up the rest three of the output. Here is how to move the filter or kernel to calculate the y12. I am not showing the calculation part. It is the same items-wise multiplication and then summing up as shown before. The following picture shows the kernel placement and bias for y21: Lastly, kernel and bias for y22 calculation: In the illustration above, only one kernel was used. But in the real model, several kernels can be used. In that case, there will be more outputs of the same size. The type of padding I used here is called “valid”. That means I actually did not use any padding at all. There are two other major types called “full” and “same”. I am not going to discuss those in this article. But in the exercise section, I will use the ‘valid’. In a high label idea, the padding ‘same’ means, adding a layer of zero at all sides of the input data and then using the kernel on it. The pooling layer reduces the dimensionality of the data and also detects the features irrespective of the location of the features in the image. Here is an example of how a MaxPooling2D works. The picture above shows how MaxPooling works. The maximum value of the purple box is 15, so it takes only 15. The maximum of green box is 19, so only 19 remains. The same goes for two other boxes as well. There are other types of pooling like average pooling or min pooling. The name indicates how they work. In average pooling, we would take the average of the values of each box and in the min pooling, we would take the minimum value from each box. These are the major ideas that are important to understand the exercise in this article. For this exercise, I will use the ‘cifar’ dataset that is free and comes with the TensorFlow library itself. This dataset includes the pixel values of images of objects and labels include numbers. Each object is represented by a number. We will train the network first and check the accuracy using the test dataset. The dataset is already segregated by training set and test set. Here I am loading the data: import tensorflow as tf(X_train, y_train), (X_test, y_test) = tf.keras.datasets.cifar10.load_data() The dataset contains the following classes: 'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck' Each of the classes is represented by a number. If you print y_train data, it looks like this: Checking one image from the training set: import matplotlib.pyplot as pltimage=X_train[3]plt.imshow(image)plt.show() Output: It is always good to scale the input data. As we have pixel values, I would divide them by 255. X_train = X_train/255X_test = X_test/255 Let’s check the shape of the training input: X_train.shape Output: (50000, 32, 32, 3) What do we know from this shape? We have 50000 training data. The input size is 32x32 and the depth is 3. That means the images are colored images. We have RGB values. For this project, I am going to use a Kernel size of 3x3 and I will use 32 output windows in the first convolution layer. Here is how it will look like: In the demonstration before I only explained with one kernel for simplicity. But you can use as many Kernels as you need. I will use 32 Kernels for this exercise. For clarification, the picture above shows the input data of 3x3 and depth 3. Our data also has a depth of three as you can see from the X-train shape. But the size is 32x32 not 3x3 as shown in this picture. In the picture all the kernels are 2x2. But I will use 3x3 Kernels. You can try with any other size. In fact kernels do not have to be squares. They can be 4x2 or any other rectangular shape as well. But kernels definitely cannot be bigger than the input shape. In this example, the input shape is 32x32. So, kernels cannot be bigger than that. Also, when we used one Kernel, we had one output window. As I used 32 Kernels here, I will have 32 output windows. After the convolution layer, there will be a MaxPooling layer. Where I used a 2x2 filter. Also, a stride of 2 means that there will be 2 steps. You can try with different strides. I will have two other convolution and MaxPooling layers. Then there will be a ‘flatten’ layer. It does what it sounds like. It will flatten the three-dimensional data into a one-dimensional column. Because after that we will pass this one-dimensional data to the dense layer. I am assuming you know the regular neural network. A dense layer takes one-dimensional data. For this project, there will be three dense layers. In the end, the output layer. The output layer will use ‘softmax’ activation. All the other layers will use ‘relu’ activation function. Here is the model: model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, (3, 3), padding="valid", activation="relu", input_shape=(32, 32, 3)), tf.keras.layers.MaxPooling2D((2, 2), strides=2), tf.keras.layers.Conv2D(48, (3, 3), padding="valid", activation="relu"), tf.keras.layers.MaxPooling2D((2, 2), strides=2), tf.keras.layers.Conv2D(48, (3, 3), padding="valid", activation="relu"), tf.keras.layers.MaxPooling2D((2, 2), strides=2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(100, activation="relu"), tf.keras.layers.Dense(100, activation="relu"), tf.keras.layers.Dense(100, activation="relu"), tf.keras.layers.Dense(10, activation="softmax")]) Here is the summary of the model: model.summary() Output: Model: "sequential_25"_________________________________________________________________Layer (type) Output Shape Param # =================================================================conv2d_81 (Conv2D) (None, 30, 30, 32) 896 _________________________________________________________________max_pooling2d_79 (MaxPooling (None, 15, 15, 32) 0 _________________________________________________________________conv2d_82 (Conv2D) (None, 13, 13, 48) 13872 _________________________________________________________________max_pooling2d_80 (MaxPooling (None, 6, 6, 48) 0 _________________________________________________________________conv2d_83 (Conv2D) (None, 4, 4, 48) 20784 _________________________________________________________________max_pooling2d_81 (MaxPooling (None, 2, 2, 48) 0 _________________________________________________________________flatten_27 (Flatten) (None, 192) 0 _________________________________________________________________dense_98 (Dense) (None, 100) 19300 _________________________________________________________________dense_99 (Dense) (None, 100) 10100 _________________________________________________________________dense_100 (Dense) (None, 100) 10100 _________________________________________________________________dense_101 (Dense) (None, 10) 1010 =================================================================Total params: 76,062Trainable params: 76,062Non-trainable params: 0_________________________________________________________________ Let’s try to understand this summary. I will discuss one convolution layer and one MaxPooling layer for your understanding. After the first convolution layer output shape is (None, 30, 30, 32). Let’s underdtand this 30, 30, and 32. The last element here is 32. That is easily understandable. Because we used 32 kernels, 32 output windows are expected. What is this 30, 30? Because we used padding of ‘valid’, the output shape should be: input size — kernel size + 1 Here input size 32, kernel size is 3, so, 32–3+1 = 30 This formula is for a padding of ‘valid’ only. If you use the padding of ‘same’ or ‘full’ the formula is different. The next element is a MaxPooling layer. The output shape from the first MaxPooling layer is (None, 15, 15, 32). As mentioned before 32 comes from the 32 kernels. As we used a 2x2 filter in the MaxPooling layer the data becomes half on both sides. So, 30, 30 of convolution layer becomes 15, 15. Before I move to train the model. I want to use an EarlyStopping condition. Assume, I set my model training for 100 epochs but my model does not need 100 epochs. May be it converges after 50 epochs. In that case, if I leave it running for 100 epochs, it will cause overfitting. We can set an EarlyStopping condition with a patience value of our choice. I will use a patience value of 5 here. That means if the model loss does not change enough for 5 epochs the model will stop training even if it only ran for 30 epochs or 50 epochs. from tensorflow.keras.callbacks import EarlyStoppingcallbacks=[EarlyStopping(patience=5)] First, we need to compile and then start training: model.compile(optimizer="adam", loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=['accuracy'])history = model.fit(X_train, y_train, epochs = 50, validation_data=(X_test, y_test), callbacks=callbacks) I set the model for 50 epochs. But it stopped after 17 epochs because of the EarlyStopping condition which saves a lot of time. Here is the summary of the results: met_df1 = pd.DataFrame(history.history)met_df1 Output: Here is the plot of training accuracy and validation accuracy per epoch: met_df1[["accuracy", "val_accuracy"]].plot()plt.xlabel("Epochs")plt.ylabel("Accuracy")plt.title("Accuracies per Epoch")plt.show() As you can see from the plot above training accuracy was consistently going up but validation accuracy was almost settled after a few epochs. There are so many things you can try at the range of the ideas explained in this article. If you want to experiment with it, here are some ideas for you: Change the kernel shape. You can try with 2x2, 4x4, 2x4, 3x2, or any other shape of your choice.Instead of ‘valid’ please feel free to try with ‘same’ or ‘full’ as padding value.Change the number of kernels and use different numbers such as 48, 64, 56, or any other number instead of 32, 48, and 48.Add or remove convolution layers.Instead of max pooling try with average pooling.Add or remove the dense layers and change the number of neurons.Try other activation functions like tanh, elu, or leakyRelu. Change the kernel shape. You can try with 2x2, 4x4, 2x4, 3x2, or any other shape of your choice. Instead of ‘valid’ please feel free to try with ‘same’ or ‘full’ as padding value. Change the number of kernels and use different numbers such as 48, 64, 56, or any other number instead of 32, 48, and 48. Add or remove convolution layers. Instead of max pooling try with average pooling. Add or remove the dense layers and change the number of neurons. Try other activation functions like tanh, elu, or leakyRelu. I am sure, if you try hard enough you may get a much better validation accuracy than the result I displayed here. I tried to make the idea of the convolutional neural network, how it works behind the scene. Though if you have to implement it from scratch, there is a lot more mathematics involved. Especially, for the parameters update. But luckily we have TensorFlow. That updates the parameters for us and we do not have to do the partial differentiation of all the elements. Please feel free to try with some different model architecture as I suggested above and share your findings if you find them interesting! Feel free to follow me on Twitter and check out my new YouTube channel.
[ { "code": null, "e": 498, "s": 171, "text": "The Convolutional Neural Network (CNN) is a multi-layered neural network that is known to be able to detect patterns and complex features. It has been useful in face detection, self-driving cars, and a lot more very complex tasks. In this article, I will give you a high-level idea of how a Convolutional Neural Network works." }, { "code": null, "e": 523, "s": 498, "text": "This article will cover:" }, { "code": null, "e": 770, "s": 523, "text": "How a convolution layer works in the forward pass.How Pooling layer works.A complete model structure of a convolutional neural network for an Image Classification project.Analysis of the model summary.Training the model and displaying the result." }, { "code": null, "e": 821, "s": 770, "text": "How a convolution layer works in the forward pass." }, { "code": null, "e": 846, "s": 821, "text": "How Pooling layer works." }, { "code": null, "e": 944, "s": 846, "text": "A complete model structure of a convolutional neural network for an Image Classification project." }, { "code": null, "e": 975, "s": 944, "text": "Analysis of the model summary." }, { "code": null, "e": 1021, "s": 975, "text": "Training the model and displaying the result." }, { "code": null, "e": 1376, "s": 1021, "text": "CNN can be used in so many different areas but in this article, we will talk about image classification examples. Image data can be expressed as numeric pixel values. Then these numeric values are passed into the CNN for processing. A normal neural network is also able to detect images but CNN is much more efficient both in terms of accuracy and speed." }, { "code": null, "e": 1795, "s": 1376, "text": "Convolution layers are very important layers in CNN because that’s what makes it a convolution neural network. In this layer, a filter or kernel is used to detect important features. The purpose is to make the dataset smaller and send only the important features to the next layer. This way it saves a lot of calculation in the dense layer and also ensures higher accuracy. Let’s have a look at a picture illustration." }, { "code": null, "e": 1889, "s": 1795, "text": "The picture above shows the input data of depth 3, a kernel of the same depth and bias terms." }, { "code": null, "e": 1940, "s": 1889, "text": "The next few pictures will show that step by step." }, { "code": null, "e": 1975, "s": 1940, "text": "Here is how the calculation works:" }, { "code": null, "e": 2082, "s": 1975, "text": "Let’s fill up the rest three of the output. Here is how to move the filter or kernel to calculate the y12." }, { "code": null, "e": 2266, "s": 2082, "text": "I am not showing the calculation part. It is the same items-wise multiplication and then summing up as shown before. The following picture shows the kernel placement and bias for y21:" }, { "code": null, "e": 2311, "s": 2266, "text": "Lastly, kernel and bias for y22 calculation:" }, { "code": null, "e": 2875, "s": 2311, "text": "In the illustration above, only one kernel was used. But in the real model, several kernels can be used. In that case, there will be more outputs of the same size. The type of padding I used here is called “valid”. That means I actually did not use any padding at all. There are two other major types called “full” and “same”. I am not going to discuss those in this article. But in the exercise section, I will use the ‘valid’. In a high label idea, the padding ‘same’ means, adding a layer of zero at all sides of the input data and then using the kernel on it." }, { "code": null, "e": 3069, "s": 2875, "text": "The pooling layer reduces the dimensionality of the data and also detects the features irrespective of the location of the features in the image. Here is an example of how a MaxPooling2D works." }, { "code": null, "e": 3521, "s": 3069, "text": "The picture above shows how MaxPooling works. The maximum value of the purple box is 15, so it takes only 15. The maximum of green box is 19, so only 19 remains. The same goes for two other boxes as well. There are other types of pooling like average pooling or min pooling. The name indicates how they work. In average pooling, we would take the average of the values of each box and in the min pooling, we would take the minimum value from each box." }, { "code": null, "e": 3610, "s": 3521, "text": "These are the major ideas that are important to understand the exercise in this article." }, { "code": null, "e": 4018, "s": 3610, "text": "For this exercise, I will use the ‘cifar’ dataset that is free and comes with the TensorFlow library itself. This dataset includes the pixel values of images of objects and labels include numbers. Each object is represented by a number. We will train the network first and check the accuracy using the test dataset. The dataset is already segregated by training set and test set. Here I am loading the data:" }, { "code": null, "e": 4118, "s": 4018, "text": "import tensorflow as tf(X_train, y_train), (X_test, y_test) = tf.keras.datasets.cifar10.load_data()" }, { "code": null, "e": 4162, "s": 4118, "text": "The dataset contains the following classes:" }, { "code": null, "e": 4253, "s": 4162, "text": "'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'" }, { "code": null, "e": 4301, "s": 4253, "text": "Each of the classes is represented by a number." }, { "code": null, "e": 4348, "s": 4301, "text": "If you print y_train data, it looks like this:" }, { "code": null, "e": 4390, "s": 4348, "text": "Checking one image from the training set:" }, { "code": null, "e": 4465, "s": 4390, "text": "import matplotlib.pyplot as pltimage=X_train[3]plt.imshow(image)plt.show()" }, { "code": null, "e": 4473, "s": 4465, "text": "Output:" }, { "code": null, "e": 4569, "s": 4473, "text": "It is always good to scale the input data. As we have pixel values, I would divide them by 255." }, { "code": null, "e": 4610, "s": 4569, "text": "X_train = X_train/255X_test = X_test/255" }, { "code": null, "e": 4655, "s": 4610, "text": "Let’s check the shape of the training input:" }, { "code": null, "e": 4669, "s": 4655, "text": "X_train.shape" }, { "code": null, "e": 4677, "s": 4669, "text": "Output:" }, { "code": null, "e": 4696, "s": 4677, "text": "(50000, 32, 32, 3)" }, { "code": null, "e": 4729, "s": 4696, "text": "What do we know from this shape?" }, { "code": null, "e": 4864, "s": 4729, "text": "We have 50000 training data. The input size is 32x32 and the depth is 3. That means the images are colored images. We have RGB values." }, { "code": null, "e": 5017, "s": 4864, "text": "For this project, I am going to use a Kernel size of 3x3 and I will use 32 output windows in the first convolution layer. Here is how it will look like:" }, { "code": null, "e": 5180, "s": 5017, "text": "In the demonstration before I only explained with one kernel for simplicity. But you can use as many Kernels as you need. I will use 32 Kernels for this exercise." }, { "code": null, "e": 5388, "s": 5180, "text": "For clarification, the picture above shows the input data of 3x3 and depth 3. Our data also has a depth of three as you can see from the X-train shape. But the size is 32x32 not 3x3 as shown in this picture." }, { "code": null, "e": 5588, "s": 5388, "text": "In the picture all the kernels are 2x2. But I will use 3x3 Kernels. You can try with any other size. In fact kernels do not have to be squares. They can be 4x2 or any other rectangular shape as well." }, { "code": null, "e": 5733, "s": 5588, "text": "But kernels definitely cannot be bigger than the input shape. In this example, the input shape is 32x32. So, kernels cannot be bigger than that." }, { "code": null, "e": 5848, "s": 5733, "text": "Also, when we used one Kernel, we had one output window. As I used 32 Kernels here, I will have 32 output windows." }, { "code": null, "e": 6028, "s": 5848, "text": "After the convolution layer, there will be a MaxPooling layer. Where I used a 2x2 filter. Also, a stride of 2 means that there will be 2 steps. You can try with different strides." }, { "code": null, "e": 6479, "s": 6028, "text": "I will have two other convolution and MaxPooling layers. Then there will be a ‘flatten’ layer. It does what it sounds like. It will flatten the three-dimensional data into a one-dimensional column. Because after that we will pass this one-dimensional data to the dense layer. I am assuming you know the regular neural network. A dense layer takes one-dimensional data. For this project, there will be three dense layers. In the end, the output layer." }, { "code": null, "e": 6585, "s": 6479, "text": "The output layer will use ‘softmax’ activation. All the other layers will use ‘relu’ activation function." }, { "code": null, "e": 6604, "s": 6585, "text": "Here is the model:" }, { "code": null, "e": 7310, "s": 6604, "text": "model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, (3, 3), padding=\"valid\", activation=\"relu\", input_shape=(32, 32, 3)), tf.keras.layers.MaxPooling2D((2, 2), strides=2), tf.keras.layers.Conv2D(48, (3, 3), padding=\"valid\", activation=\"relu\"), tf.keras.layers.MaxPooling2D((2, 2), strides=2), tf.keras.layers.Conv2D(48, (3, 3), padding=\"valid\", activation=\"relu\"), tf.keras.layers.MaxPooling2D((2, 2), strides=2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(100, activation=\"relu\"), tf.keras.layers.Dense(100, activation=\"relu\"), tf.keras.layers.Dense(100, activation=\"relu\"), tf.keras.layers.Dense(10, activation=\"softmax\")])" }, { "code": null, "e": 7344, "s": 7310, "text": "Here is the summary of the model:" }, { "code": null, "e": 7360, "s": 7344, "text": "model.summary()" }, { "code": null, "e": 7368, "s": 7360, "text": "Output:" }, { "code": null, "e": 9148, "s": 7368, "text": "Model: \"sequential_25\"_________________________________________________________________Layer (type) Output Shape Param # =================================================================conv2d_81 (Conv2D) (None, 30, 30, 32) 896 _________________________________________________________________max_pooling2d_79 (MaxPooling (None, 15, 15, 32) 0 _________________________________________________________________conv2d_82 (Conv2D) (None, 13, 13, 48) 13872 _________________________________________________________________max_pooling2d_80 (MaxPooling (None, 6, 6, 48) 0 _________________________________________________________________conv2d_83 (Conv2D) (None, 4, 4, 48) 20784 _________________________________________________________________max_pooling2d_81 (MaxPooling (None, 2, 2, 48) 0 _________________________________________________________________flatten_27 (Flatten) (None, 192) 0 _________________________________________________________________dense_98 (Dense) (None, 100) 19300 _________________________________________________________________dense_99 (Dense) (None, 100) 10100 _________________________________________________________________dense_100 (Dense) (None, 100) 10100 _________________________________________________________________dense_101 (Dense) (None, 10) 1010 =================================================================Total params: 76,062Trainable params: 76,062Non-trainable params: 0_________________________________________________________________" }, { "code": null, "e": 9342, "s": 9148, "text": "Let’s try to understand this summary. I will discuss one convolution layer and one MaxPooling layer for your understanding. After the first convolution layer output shape is (None, 30, 30, 32)." }, { "code": null, "e": 9500, "s": 9342, "text": "Let’s underdtand this 30, 30, and 32. The last element here is 32. That is easily understandable. Because we used 32 kernels, 32 output windows are expected." }, { "code": null, "e": 9585, "s": 9500, "text": "What is this 30, 30? Because we used padding of ‘valid’, the output shape should be:" }, { "code": null, "e": 9614, "s": 9585, "text": "input size — kernel size + 1" }, { "code": null, "e": 9656, "s": 9614, "text": "Here input size 32, kernel size is 3, so," }, { "code": null, "e": 9668, "s": 9656, "text": "32–3+1 = 30" }, { "code": null, "e": 9784, "s": 9668, "text": "This formula is for a padding of ‘valid’ only. If you use the padding of ‘same’ or ‘full’ the formula is different." }, { "code": null, "e": 10079, "s": 9784, "text": "The next element is a MaxPooling layer. The output shape from the first MaxPooling layer is (None, 15, 15, 32). As mentioned before 32 comes from the 32 kernels. As we used a 2x2 filter in the MaxPooling layer the data becomes half on both sides. So, 30, 30 of convolution layer becomes 15, 15." }, { "code": null, "e": 10155, "s": 10079, "text": "Before I move to train the model. I want to use an EarlyStopping condition." }, { "code": null, "e": 10613, "s": 10155, "text": "Assume, I set my model training for 100 epochs but my model does not need 100 epochs. May be it converges after 50 epochs. In that case, if I leave it running for 100 epochs, it will cause overfitting. We can set an EarlyStopping condition with a patience value of our choice. I will use a patience value of 5 here. That means if the model loss does not change enough for 5 epochs the model will stop training even if it only ran for 30 epochs or 50 epochs." }, { "code": null, "e": 10703, "s": 10613, "text": "from tensorflow.keras.callbacks import EarlyStoppingcallbacks=[EarlyStopping(patience=5)]" }, { "code": null, "e": 10754, "s": 10703, "text": "First, we need to compile and then start training:" }, { "code": null, "e": 11012, "s": 10754, "text": "model.compile(optimizer=\"adam\", loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=['accuracy'])history = model.fit(X_train, y_train, epochs = 50, validation_data=(X_test, y_test), callbacks=callbacks)" }, { "code": null, "e": 11140, "s": 11012, "text": "I set the model for 50 epochs. But it stopped after 17 epochs because of the EarlyStopping condition which saves a lot of time." }, { "code": null, "e": 11176, "s": 11140, "text": "Here is the summary of the results:" }, { "code": null, "e": 11223, "s": 11176, "text": "met_df1 = pd.DataFrame(history.history)met_df1" }, { "code": null, "e": 11231, "s": 11223, "text": "Output:" }, { "code": null, "e": 11304, "s": 11231, "text": "Here is the plot of training accuracy and validation accuracy per epoch:" }, { "code": null, "e": 11434, "s": 11304, "text": "met_df1[[\"accuracy\", \"val_accuracy\"]].plot()plt.xlabel(\"Epochs\")plt.ylabel(\"Accuracy\")plt.title(\"Accuracies per Epoch\")plt.show()" }, { "code": null, "e": 11576, "s": 11434, "text": "As you can see from the plot above training accuracy was consistently going up but validation accuracy was almost settled after a few epochs." }, { "code": null, "e": 11730, "s": 11576, "text": "There are so many things you can try at the range of the ideas explained in this article. If you want to experiment with it, here are some ideas for you:" }, { "code": null, "e": 12235, "s": 11730, "text": "Change the kernel shape. You can try with 2x2, 4x4, 2x4, 3x2, or any other shape of your choice.Instead of ‘valid’ please feel free to try with ‘same’ or ‘full’ as padding value.Change the number of kernels and use different numbers such as 48, 64, 56, or any other number instead of 32, 48, and 48.Add or remove convolution layers.Instead of max pooling try with average pooling.Add or remove the dense layers and change the number of neurons.Try other activation functions like tanh, elu, or leakyRelu." }, { "code": null, "e": 12332, "s": 12235, "text": "Change the kernel shape. You can try with 2x2, 4x4, 2x4, 3x2, or any other shape of your choice." }, { "code": null, "e": 12415, "s": 12332, "text": "Instead of ‘valid’ please feel free to try with ‘same’ or ‘full’ as padding value." }, { "code": null, "e": 12537, "s": 12415, "text": "Change the number of kernels and use different numbers such as 48, 64, 56, or any other number instead of 32, 48, and 48." }, { "code": null, "e": 12571, "s": 12537, "text": "Add or remove convolution layers." }, { "code": null, "e": 12620, "s": 12571, "text": "Instead of max pooling try with average pooling." }, { "code": null, "e": 12685, "s": 12620, "text": "Add or remove the dense layers and change the number of neurons." }, { "code": null, "e": 12746, "s": 12685, "text": "Try other activation functions like tanh, elu, or leakyRelu." }, { "code": null, "e": 12860, "s": 12746, "text": "I am sure, if you try hard enough you may get a much better validation accuracy than the result I displayed here." }, { "code": null, "e": 13362, "s": 12860, "text": "I tried to make the idea of the convolutional neural network, how it works behind the scene. Though if you have to implement it from scratch, there is a lot more mathematics involved. Especially, for the parameters update. But luckily we have TensorFlow. That updates the parameters for us and we do not have to do the partial differentiation of all the elements. Please feel free to try with some different model architecture as I suggested above and share your findings if you find them interesting!" } ]
Writing First C++ Program – Hello World Example
15 Jul, 2022 C++ is a widely used Object Oriented Programming language and is fairly easy to understand. Learning C++ programming can be simplified into: Writing your program in a text editor and saving it with correct extension(.CPP, .C, .CP) Compiling your program using a compiler or online IDE Understanding the basic terminologies. The “Hello World” program is the first step towards learning any programming language and is also one of the simplest programs you will learn. All you have to do is display the message “Hello World” on the screen. Let us now look at the program: 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. CPP // C++ program to display "Hello World" // Header file for input output functions#include <iostream>using namespace std; // Main() function: where the execution of program beginsint main(){ // prints hello world cout << "Hello World"; return 0;} Hello World Let us now understand every line and the terminologies of the above program: 1) // C++ program to display “Hello World”: This line is a comment line. A comment is used to display additional information about the program. A comment does not contain any programming logic. When a comment is encountered by a compiler, the compiler simply skips that line of code. Any line beginning with ‘//’ without quotes OR in between /*...*/ in C++ is comment. Click to know More about Comments. 2) #include: In C++, all lines that start with pound (#) sign are called directives and are processed by a preprocessor which is a program invoked by the compiler. The #include directive tells the compiler to include a file and #include<iostream>. It tells the compiler to include the standard iostream file which contains declarations of all the standard input/output library functions. Click to Know More on Preprocessors. 3) using namespace std: This is used to import the entirety of the std namespace into the current namespace of the program. The statement using namespace std is generally considered a bad practice. When we import a namespace we are essentially pulling all type definitions into the current scope. The std namespace is huge. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type. Click to know More about using namespace std. 4) int main(): This line is used to declare a function named “main” which returns data of integer type. A function is a group of statements that are designed to perform a specific task. Execution of every C++ program begins with the main() function, no matter where the function is located in the program. So, every C++ program must have a main() function. Click to know More about the main() function. 5) { and }: The opening braces ‘{‘ indicates the beginning of the main function and the closing braces ‘}’ indicates the ending of the main function. Everything between these two comprises the body of the main function. 6) std::cout<<“Hello World”;: This line tells the compiler to display the message “Hello World” on the screen. This line is called a statement in C++. Every statement is meant to perform some task. A semi-colon ‘;’ is used to end a statement. Semi-colon character at the end of the statement is used to indicate that the statement is ending there. The std::cout is used to identify the standard character output device which is usually the desktop screen. Everything followed by the character “<<” is displayed to the output device. Click to know More on Input/Output. 7) return 0; : This is also a statement. This statement is used to return a value from a function and indicates the finishing of a function. This statement is basically used in functions to return the results of the operations performed by a function. 8) Indentation: As you can see the cout and the return statement have been indented or moved to the right side. This is done to make the code more readable. In a program as Hello World, it does not hold much relevance, but as the programs become more complex, it makes the code more readable, less error-prone. Therefore, you must always use indentations and comments to make the code more readable. Must read the FAQ on the style of writing programs. Important Points to Note while Writing a C++ Program: Always include the necessary header files for the smooth execution of functions. For example, <iostream> must be included to use std::cin and std::cout.The execution of code begins from the main() function.It is a good practice to use Indentation and comments in programs for easy understanding.cout is used to print statements and cin is used to take inputs. Always include the necessary header files for the smooth execution of functions. For example, <iostream> must be included to use std::cin and std::cout. The execution of code begins from the main() function. It is a good practice to use Indentation and comments in programs for easy understanding. cout is used to print statements and cin is used to take inputs. This article is contributed by Harsh Agarwal. 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 have more information about the topic discussed above. Dedsec727 Tarandeepsingh5 tshubham805 anshikajain26 C Basics CBSE - Class 11 CPP-Basics school-programming C++ School Programming CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n15 Jul, 2022" }, { "code": null, "e": 197, "s": 53, "text": "C++ is a widely used Object Oriented Programming language and is fairly easy to understand. Learning C++ programming can be simplified into: " }, { "code": null, "e": 287, "s": 197, "text": "Writing your program in a text editor and saving it with correct extension(.CPP, .C, .CP)" }, { "code": null, "e": 341, "s": 287, "text": "Compiling your program using a compiler or online IDE" }, { "code": null, "e": 380, "s": 341, "text": "Understanding the basic terminologies." }, { "code": null, "e": 627, "s": 380, "text": "The “Hello World” program is the first step towards learning any programming language and is also one of the simplest programs you will learn. All you have to do is display the message “Hello World” on the screen. Let us now look at the program: " }, { "code": null, "e": 636, "s": 627, "text": "Chapters" }, { "code": null, "e": 663, "s": 636, "text": "descriptions off, selected" }, { "code": null, "e": 713, "s": 663, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 736, "s": 713, "text": "captions off, selected" }, { "code": null, "e": 744, "s": 736, "text": "English" }, { "code": null, "e": 768, "s": 744, "text": "This is a modal window." }, { "code": null, "e": 837, "s": 768, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 859, "s": 837, "text": "End of dialog window." }, { "code": null, "e": 863, "s": 859, "text": "CPP" }, { "code": "// C++ program to display \"Hello World\" // Header file for input output functions#include <iostream>using namespace std; // Main() function: where the execution of program beginsint main(){ // prints hello world cout << \"Hello World\"; return 0;}", "e": 1122, "s": 863, "text": null }, { "code": null, "e": 1134, "s": 1122, "text": "Hello World" }, { "code": null, "e": 1212, "s": 1134, "text": "Let us now understand every line and the terminologies of the above program: " }, { "code": null, "e": 1617, "s": 1212, "text": "1) // C++ program to display “Hello World”: This line is a comment line. A comment is used to display additional information about the program. A comment does not contain any programming logic. When a comment is encountered by a compiler, the compiler simply skips that line of code. Any line beginning with ‘//’ without quotes OR in between /*...*/ in C++ is comment. Click to know More about Comments. " }, { "code": null, "e": 2043, "s": 1617, "text": "2) #include: In C++, all lines that start with pound (#) sign are called directives and are processed by a preprocessor which is a program invoked by the compiler. The #include directive tells the compiler to include a file and #include<iostream>. It tells the compiler to include the standard iostream file which contains declarations of all the standard input/output library functions. Click to Know More on Preprocessors." }, { "code": null, "e": 2565, "s": 2043, "text": "3) using namespace std: This is used to import the entirety of the std namespace into the current namespace of the program. The statement using namespace std is generally considered a bad practice. When we import a namespace we are essentially pulling all type definitions into the current scope. The std namespace is huge. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type. Click to know More about using namespace std." }, { "code": null, "e": 2968, "s": 2565, "text": "4) int main(): This line is used to declare a function named “main” which returns data of integer type. A function is a group of statements that are designed to perform a specific task. Execution of every C++ program begins with the main() function, no matter where the function is located in the program. So, every C++ program must have a main() function. Click to know More about the main() function." }, { "code": null, "e": 3188, "s": 2968, "text": "5) { and }: The opening braces ‘{‘ indicates the beginning of the main function and the closing braces ‘}’ indicates the ending of the main function. Everything between these two comprises the body of the main function." }, { "code": null, "e": 3758, "s": 3188, "text": "6) std::cout<<“Hello World”;: This line tells the compiler to display the message “Hello World” on the screen. This line is called a statement in C++. Every statement is meant to perform some task. A semi-colon ‘;’ is used to end a statement. Semi-colon character at the end of the statement is used to indicate that the statement is ending there. The std::cout is used to identify the standard character output device which is usually the desktop screen. Everything followed by the character “<<” is displayed to the output device. Click to know More on Input/Output." }, { "code": null, "e": 4011, "s": 3758, "text": "7) return 0; : This is also a statement. This statement is used to return a value from a function and indicates the finishing of a function. This statement is basically used in functions to return the results of the operations performed by a function. " }, { "code": null, "e": 4463, "s": 4011, "text": "8) Indentation: As you can see the cout and the return statement have been indented or moved to the right side. This is done to make the code more readable. In a program as Hello World, it does not hold much relevance, but as the programs become more complex, it makes the code more readable, less error-prone. Therefore, you must always use indentations and comments to make the code more readable. Must read the FAQ on the style of writing programs." }, { "code": null, "e": 4517, "s": 4463, "text": "Important Points to Note while Writing a C++ Program:" }, { "code": null, "e": 4878, "s": 4517, "text": "Always include the necessary header files for the smooth execution of functions. For example, <iostream> must be included to use std::cin and std::cout.The execution of code begins from the main() function.It is a good practice to use Indentation and comments in programs for easy understanding.cout is used to print statements and cin is used to take inputs. " }, { "code": null, "e": 5031, "s": 4878, "text": "Always include the necessary header files for the smooth execution of functions. For example, <iostream> must be included to use std::cin and std::cout." }, { "code": null, "e": 5086, "s": 5031, "text": "The execution of code begins from the main() function." }, { "code": null, "e": 5176, "s": 5086, "text": "It is a good practice to use Indentation and comments in programs for easy understanding." }, { "code": null, "e": 5242, "s": 5176, "text": "cout is used to print statements and cin is used to take inputs. " }, { "code": null, "e": 5652, "s": 5242, "text": "This article is contributed by Harsh Agarwal. 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 have more information about the topic discussed above. " }, { "code": null, "e": 5662, "s": 5652, "text": "Dedsec727" }, { "code": null, "e": 5678, "s": 5662, "text": "Tarandeepsingh5" }, { "code": null, "e": 5690, "s": 5678, "text": "tshubham805" }, { "code": null, "e": 5704, "s": 5690, "text": "anshikajain26" }, { "code": null, "e": 5713, "s": 5704, "text": "C Basics" }, { "code": null, "e": 5729, "s": 5713, "text": "CBSE - Class 11" }, { "code": null, "e": 5740, "s": 5729, "text": "CPP-Basics" }, { "code": null, "e": 5759, "s": 5740, "text": "school-programming" }, { "code": null, "e": 5763, "s": 5759, "text": "C++" }, { "code": null, "e": 5782, "s": 5763, "text": "School Programming" }, { "code": null, "e": 5786, "s": 5782, "text": "CPP" } ]
Minimum and Maximum Number of Nodes Between Critical Points
25 Feb, 2022 Given an array arr[], return an array of size 2 consisting of 2 values, the first one the minDistance and the second one maxDistance. Here minDistance is the minimum distance between any two distinct critical points and maxDistance is the maximum distance between any two distinct critical points and by chance, if there are less than two critical points then it should return [-1, -1]. Examples: Input: arr[] = {3, 1}Output: {-1, -1}Explanation: There are no critical points in ArrayInput: arr[] = {5, 3, 1, 2, 5, 1, 2}Output: {1, 3}Explanation: There are three critical points at indexes 2, 4 and 5 in the Array (0 Based Indexing). So the minimum distance is between 4 and 5 which is 1 and the maximum distance is 2. Approach: The task can be solved by storing the indices of critical points. Follow the below steps to solve the problem: Iterate over the array and if we get a critical point then we will insert it in the position array Check if its size is less than or equal to 1, if this is true then we simply need to return the array which contains -1 and -1 Else we will get the maximum distance by subtracting the last value and the first value of the position array and the minimum distance we can get by using the equation mval=min(mval, pos[i]-pos[i-1]), for all i>1. 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 check whether that point is a critical// point or not based on the present, previous and next// value.bool isCriticalPoint(int prev, int pres, int next){ // Critical point condition if ((prev < pres && pres > next) || (prev > pres && pres < next)) return true; return false;} // Function to find the required distancesvector<int> maxmincriticaldis(vector<int>& arr, int n){ // Store the position vector<int> pos; // Start from index 1 as we are gonna pass // arr[i-1] and at i=0 i-1 becomes -ve // to avoid that error we start from index 1 for (int i = 1; i < n - 1; i++) { // If this point is critical point then it's // index is inserted in the pos array if (isCriticalPoint(arr[i - 1], arr[i], arr[i + 1])) pos.push_back(i); } vector<int> ans; // If the pos array size is either 0 or 1 // then we will simply add -1 and -1 to the answer array // as it is not possible to find the max and min // distance with 1 or 0 elements in the array. if (pos.size() <= 1) { ans.push_back(-1); ans.push_back(-1); } else { // We find the minimum difference between the // positions of the critical points based on the // values of indexes. int mval = INT_MAX; for (int i = 1; i < pos.size(); i++) mval = min(mval, pos[i] - pos[i - 1]); ans.push_back(mval); // Maximum difference will obviously be between // the first and the last element of the pos array. ans.push_back(pos[pos.size() - 1] - pos[0]); } return ans;} // Driver Codeint main(){ vector<int> arr = { 5, 3, 1, 2, 5, 1, 2 }; int n = arr.size(); vector<int> ans = maxmincriticaldis(arr, n); for (int i = 0; i < ans.size(); i++) cout << ans[i] << " ";}// This Code is contributed by Omkar Subhash Ghongade. // Java program for the above approachimport java.util.*; class GFG{ // Function to check whether that point is a critical// point or not based on the present, previous and next// value.static boolean isCriticalPoint(int prev, int pres, int next){ // Critical point condition if ((prev < pres && pres > next) || (prev > pres && pres < next)) return true; return false;} // Function to find the required distancesstatic Vector<Integer> maxmincriticaldis(int[] arr, int n){ // Store the position Vector<Integer> pos = new Vector<Integer>(); // Start from index 1 as we are gonna pass // arr[i-1] and at i=0 i-1 becomes -ve // to astatic void that error we start from index 1 for (int i = 1; i < n - 1; i++) { // If this point is critical point then it's // index is inserted in the pos array if (isCriticalPoint(arr[i - 1], arr[i], arr[i + 1])) pos.add(i); } Vector<Integer> ans = new Vector<Integer>(); // If the pos array size is either 0 or 1 // then we will simply add -1 and -1 to the answer array // as it is not possible to find the max and min // distance with 1 or 0 elements in the array. if (pos.size() <= 1) { ans.add(-1); ans.add(-1); } else { // We find the minimum difference between the // positions of the critical points based on the // values of indexes. int mval = Integer.MAX_VALUE; for (int i = 1; i < pos.size(); i++) mval = Math.min(mval, pos.get(i) - pos.get(i-1)); ans.add(mval); // Maximum difference will obviously be between // the first and the last element of the pos array. ans.add(pos.get(pos.size() - 1) - pos.get(0)); } return ans;} // Driver Codepublic static void main(String[] args){ int[] arr = { 5, 3, 1, 2, 5, 1, 2 }; int n = arr.length; Vector<Integer> ans = maxmincriticaldis(arr, n); for (int i = 0; i < ans.size(); i++) System.out.print(ans.get(i)+ " ");}} // This code is contributed by 29AjayKumar # Python 3 program for the above approachimport sys # Function to check whether that point is a critical# point or not based on the present, previous and next# value.def isCriticalPoint(prev, pres, next): # Critical point condition if ((prev < pres and pres > next) or (prev > pres and pres < next)): return True return False # Function to find the required distancesdef maxmincriticaldis(arr, n): # Store the position pos = [] # Start from index 1 as we are gonna pass # arr[i-1] and at i=0 i-1 becomes -ve # to avoid that error we start from index 1 for i in range(1, n - 1): # If this point is critical point then it's # index is inserted in the pos array if (isCriticalPoint(arr[i - 1], arr[i], arr[i + 1])): pos.append(i) ans = [] # If the pos array size is either 0 or 1 # then we will simply add -1 and -1 to the answer array # as it is not possible to find the max and min # distance with 1 or 0 elements in the array. if (len(pos) <= 1): ans.append(-1) ans.append(-1) else: # We find the minimum difference between the # positions of the critical points based on the # values of indexes. mval = sys.maxsize for i in range(1, len(pos)): mval = min(mval, pos[i] - pos[i - 1]) ans.append(mval) # Maximum difference will obviously be between # the first and the last element of the pos array. ans.append(pos[len(pos) - 1] - pos[0]) return ans # Driver Codeif __name__ == "__main__": arr = [5, 3, 1, 2, 5, 1, 2] n = len(arr) ans = maxmincriticaldis(arr, n) for i in range(len(ans)): print(ans[i], end=" ") # This code is contributed by ukasp. // C# program for the above approachusing System;using System.Collections; class GFG{ // Function to check whether that point is a critical// point or not based on the present, previous and next// value.static bool isCriticalPoint(int prev, int pres, int next){ // Critical point condition if ((prev < pres && pres > next) || (prev > pres && pres < next)) return true; return false;} // Function to find the required distancesstatic ArrayList maxmincriticaldis(ArrayList arr, int n){ // Store the position ArrayList pos = new ArrayList(); // Start from index 1 as we are gonna pass // arr[i-1] and at i=0 i-1 becomes -ve // to avoid that error we start from index 1 for (int i = 1; i < n - 1; i++) { // If this point is critical point then it's // index is inserted in the pos array if (isCriticalPoint((int)arr[i - 1], (int)arr[i], (int)arr[i + 1])) pos.Add(i); } ArrayList ans = new ArrayList(); // If the pos array size is either 0 or 1 // then we will simply add -1 and -1 to the answer array // as it is not possible to find the max and min // distance with 1 or 0 elements in the array. if (pos.Count <= 1) { ans.Add(-1); ans.Add(-1); } else { // We find the minimum difference between the // positions of the critical points based on the // values of indexes. int mval = Int32.MaxValue; for (int i = 1; i < pos.Count; i++) mval = Math.Min(mval, (int)pos[i] - (int)pos[i - 1]); ans.Add(mval); // Maximum difference will obviously be between // the first and the last element of the pos array. ans.Add((int)pos[pos.Count - 1] - (int)pos[0]); } return ans;} // Driver Codepublic static void Main(){ ArrayList arr = new ArrayList(); arr.Add(5); arr.Add(3); arr.Add(1); arr.Add(2); arr.Add(5); arr.Add(1); arr.Add(2); int n = arr.Count; ArrayList ans = maxmincriticaldis(arr, n); for (int i = 0; i < ans.Count; i++) Console.Write(ans[i] + " ");}} // This Code is contributed by Samim Hossain Mondal. <script> // JavaScript code for the above approach // Function to check whether that point is a critical // point or not based on the present, previous and next // value. function isCriticalPoint(prev, pres, next) { // Critical point condition if ((prev < pres && pres > next) || (prev > pres && pres < next)) return true; return false; } // Function to find the required distances function maxmincriticaldis(arr, n) { // Store the position let pos = []; // Start from index 1 as we are gonna pass // arr[i-1] and at i=0 i-1 becomes -ve // to avoid that error we start from index 1 for (let i = 1; i < n - 1; i++) { // If this point is critical point then it's // index is inserted in the pos array if (isCriticalPoint(arr[i - 1], arr[i], arr[i + 1])) pos.push(i); } let ans = []; // If the pos array size is either 0 or 1 // then we will simply add -1 and -1 to the answer array // as it is not possible to find the max and min // distance with 1 or 0 elements in the array. if (pos.length <= 1) { ans.push(-1); ans.push(-1); } else { // We find the minimum difference between the // positions of the critical points based on the // values of indexes. let mval = Number.MAX_VALUE; for (let i = 1; i < pos.length; i++) mval = Math.min(mval, pos[i] - pos[i - 1]); ans.push(mval); // Maximum difference will obviously be between // the first and the last element of the pos array. ans.push(pos[pos.length - 1] - pos[0]); } return ans; } // Driver Code let arr = [5, 3, 1, 2, 5, 1, 2]; let n = arr.length; let ans = maxmincriticaldis(arr, n); for (let i = 0; i < ans.length; i++) document.write(ans[i] + " ") // This code is contributed by Potta Lokesh </script> 1 3 Time Complexity: O(n), n is the number of elements in the Array.Auxiliary Space: O(n), we are using extra space in the function. lokeshpotta20 samim2000 ukasp varshagumber28 29AjayKumar simmytarika5 surinderdawra388 Arrays Greedy Mathematical Arrays Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Feb, 2022" }, { "code": null, "e": 415, "s": 28, "text": "Given an array arr[], return an array of size 2 consisting of 2 values, the first one the minDistance and the second one maxDistance. Here minDistance is the minimum distance between any two distinct critical points and maxDistance is the maximum distance between any two distinct critical points and by chance, if there are less than two critical points then it should return [-1, -1]." }, { "code": null, "e": 425, "s": 415, "text": "Examples:" }, { "code": null, "e": 747, "s": 425, "text": "Input: arr[] = {3, 1}Output: {-1, -1}Explanation: There are no critical points in ArrayInput: arr[] = {5, 3, 1, 2, 5, 1, 2}Output: {1, 3}Explanation: There are three critical points at indexes 2, 4 and 5 in the Array (0 Based Indexing). So the minimum distance is between 4 and 5 which is 1 and the maximum distance is 2." }, { "code": null, "e": 868, "s": 747, "text": "Approach: The task can be solved by storing the indices of critical points. Follow the below steps to solve the problem:" }, { "code": null, "e": 967, "s": 868, "text": "Iterate over the array and if we get a critical point then we will insert it in the position array" }, { "code": null, "e": 1094, "s": 967, "text": "Check if its size is less than or equal to 1, if this is true then we simply need to return the array which contains -1 and -1" }, { "code": null, "e": 1308, "s": 1094, "text": "Else we will get the maximum distance by subtracting the last value and the first value of the position array and the minimum distance we can get by using the equation mval=min(mval, pos[i]-pos[i-1]), for all i>1." }, { "code": null, "e": 1359, "s": 1308, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1363, "s": 1359, "text": "C++" }, { "code": null, "e": 1368, "s": 1363, "text": "Java" }, { "code": null, "e": 1376, "s": 1368, "text": "Python3" }, { "code": null, "e": 1379, "s": 1376, "text": "C#" }, { "code": null, "e": 1390, "s": 1379, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether that point is a critical// point or not based on the present, previous and next// value.bool isCriticalPoint(int prev, int pres, int next){ // Critical point condition if ((prev < pres && pres > next) || (prev > pres && pres < next)) return true; return false;} // Function to find the required distancesvector<int> maxmincriticaldis(vector<int>& arr, int n){ // Store the position vector<int> pos; // Start from index 1 as we are gonna pass // arr[i-1] and at i=0 i-1 becomes -ve // to avoid that error we start from index 1 for (int i = 1; i < n - 1; i++) { // If this point is critical point then it's // index is inserted in the pos array if (isCriticalPoint(arr[i - 1], arr[i], arr[i + 1])) pos.push_back(i); } vector<int> ans; // If the pos array size is either 0 or 1 // then we will simply add -1 and -1 to the answer array // as it is not possible to find the max and min // distance with 1 or 0 elements in the array. if (pos.size() <= 1) { ans.push_back(-1); ans.push_back(-1); } else { // We find the minimum difference between the // positions of the critical points based on the // values of indexes. int mval = INT_MAX; for (int i = 1; i < pos.size(); i++) mval = min(mval, pos[i] - pos[i - 1]); ans.push_back(mval); // Maximum difference will obviously be between // the first and the last element of the pos array. ans.push_back(pos[pos.size() - 1] - pos[0]); } return ans;} // Driver Codeint main(){ vector<int> arr = { 5, 3, 1, 2, 5, 1, 2 }; int n = arr.size(); vector<int> ans = maxmincriticaldis(arr, n); for (int i = 0; i < ans.size(); i++) cout << ans[i] << \" \";}// This Code is contributed by Omkar Subhash Ghongade.", "e": 3387, "s": 1390, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to check whether that point is a critical// point or not based on the present, previous and next// value.static boolean isCriticalPoint(int prev, int pres, int next){ // Critical point condition if ((prev < pres && pres > next) || (prev > pres && pres < next)) return true; return false;} // Function to find the required distancesstatic Vector<Integer> maxmincriticaldis(int[] arr, int n){ // Store the position Vector<Integer> pos = new Vector<Integer>(); // Start from index 1 as we are gonna pass // arr[i-1] and at i=0 i-1 becomes -ve // to astatic void that error we start from index 1 for (int i = 1; i < n - 1; i++) { // If this point is critical point then it's // index is inserted in the pos array if (isCriticalPoint(arr[i - 1], arr[i], arr[i + 1])) pos.add(i); } Vector<Integer> ans = new Vector<Integer>(); // If the pos array size is either 0 or 1 // then we will simply add -1 and -1 to the answer array // as it is not possible to find the max and min // distance with 1 or 0 elements in the array. if (pos.size() <= 1) { ans.add(-1); ans.add(-1); } else { // We find the minimum difference between the // positions of the critical points based on the // values of indexes. int mval = Integer.MAX_VALUE; for (int i = 1; i < pos.size(); i++) mval = Math.min(mval, pos.get(i) - pos.get(i-1)); ans.add(mval); // Maximum difference will obviously be between // the first and the last element of the pos array. ans.add(pos.get(pos.size() - 1) - pos.get(0)); } return ans;} // Driver Codepublic static void main(String[] args){ int[] arr = { 5, 3, 1, 2, 5, 1, 2 }; int n = arr.length; Vector<Integer> ans = maxmincriticaldis(arr, n); for (int i = 0; i < ans.size(); i++) System.out.print(ans.get(i)+ \" \");}} // This code is contributed by 29AjayKumar", "e": 5475, "s": 3387, "text": null }, { "code": "# Python 3 program for the above approachimport sys # Function to check whether that point is a critical# point or not based on the present, previous and next# value.def isCriticalPoint(prev, pres, next): # Critical point condition if ((prev < pres and pres > next) or (prev > pres and pres < next)): return True return False # Function to find the required distancesdef maxmincriticaldis(arr, n): # Store the position pos = [] # Start from index 1 as we are gonna pass # arr[i-1] and at i=0 i-1 becomes -ve # to avoid that error we start from index 1 for i in range(1, n - 1): # If this point is critical point then it's # index is inserted in the pos array if (isCriticalPoint(arr[i - 1], arr[i], arr[i + 1])): pos.append(i) ans = [] # If the pos array size is either 0 or 1 # then we will simply add -1 and -1 to the answer array # as it is not possible to find the max and min # distance with 1 or 0 elements in the array. if (len(pos) <= 1): ans.append(-1) ans.append(-1) else: # We find the minimum difference between the # positions of the critical points based on the # values of indexes. mval = sys.maxsize for i in range(1, len(pos)): mval = min(mval, pos[i] - pos[i - 1]) ans.append(mval) # Maximum difference will obviously be between # the first and the last element of the pos array. ans.append(pos[len(pos) - 1] - pos[0]) return ans # Driver Codeif __name__ == \"__main__\": arr = [5, 3, 1, 2, 5, 1, 2] n = len(arr) ans = maxmincriticaldis(arr, n) for i in range(len(ans)): print(ans[i], end=\" \") # This code is contributed by ukasp.", "e": 7280, "s": 5475, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections; class GFG{ // Function to check whether that point is a critical// point or not based on the present, previous and next// value.static bool isCriticalPoint(int prev, int pres, int next){ // Critical point condition if ((prev < pres && pres > next) || (prev > pres && pres < next)) return true; return false;} // Function to find the required distancesstatic ArrayList maxmincriticaldis(ArrayList arr, int n){ // Store the position ArrayList pos = new ArrayList(); // Start from index 1 as we are gonna pass // arr[i-1] and at i=0 i-1 becomes -ve // to avoid that error we start from index 1 for (int i = 1; i < n - 1; i++) { // If this point is critical point then it's // index is inserted in the pos array if (isCriticalPoint((int)arr[i - 1], (int)arr[i], (int)arr[i + 1])) pos.Add(i); } ArrayList ans = new ArrayList(); // If the pos array size is either 0 or 1 // then we will simply add -1 and -1 to the answer array // as it is not possible to find the max and min // distance with 1 or 0 elements in the array. if (pos.Count <= 1) { ans.Add(-1); ans.Add(-1); } else { // We find the minimum difference between the // positions of the critical points based on the // values of indexes. int mval = Int32.MaxValue; for (int i = 1; i < pos.Count; i++) mval = Math.Min(mval, (int)pos[i] - (int)pos[i - 1]); ans.Add(mval); // Maximum difference will obviously be between // the first and the last element of the pos array. ans.Add((int)pos[pos.Count - 1] - (int)pos[0]); } return ans;} // Driver Codepublic static void Main(){ ArrayList arr = new ArrayList(); arr.Add(5); arr.Add(3); arr.Add(1); arr.Add(2); arr.Add(5); arr.Add(1); arr.Add(2); int n = arr.Count; ArrayList ans = maxmincriticaldis(arr, n); for (int i = 0; i < ans.Count; i++) Console.Write(ans[i] + \" \");}} // This Code is contributed by Samim Hossain Mondal.", "e": 9457, "s": 7280, "text": null }, { "code": " <script> // JavaScript code for the above approach // Function to check whether that point is a critical // point or not based on the present, previous and next // value. function isCriticalPoint(prev, pres, next) { // Critical point condition if ((prev < pres && pres > next) || (prev > pres && pres < next)) return true; return false; } // Function to find the required distances function maxmincriticaldis(arr, n) { // Store the position let pos = []; // Start from index 1 as we are gonna pass // arr[i-1] and at i=0 i-1 becomes -ve // to avoid that error we start from index 1 for (let i = 1; i < n - 1; i++) { // If this point is critical point then it's // index is inserted in the pos array if (isCriticalPoint(arr[i - 1], arr[i], arr[i + 1])) pos.push(i); } let ans = []; // If the pos array size is either 0 or 1 // then we will simply add -1 and -1 to the answer array // as it is not possible to find the max and min // distance with 1 or 0 elements in the array. if (pos.length <= 1) { ans.push(-1); ans.push(-1); } else { // We find the minimum difference between the // positions of the critical points based on the // values of indexes. let mval = Number.MAX_VALUE; for (let i = 1; i < pos.length; i++) mval = Math.min(mval, pos[i] - pos[i - 1]); ans.push(mval); // Maximum difference will obviously be between // the first and the last element of the pos array. ans.push(pos[pos.length - 1] - pos[0]); } return ans; } // Driver Code let arr = [5, 3, 1, 2, 5, 1, 2]; let n = arr.length; let ans = maxmincriticaldis(arr, n); for (let i = 0; i < ans.length; i++) document.write(ans[i] + \" \") // This code is contributed by Potta Lokesh </script>", "e": 11671, "s": 9457, "text": null }, { "code": null, "e": 11676, "s": 11671, "text": "1 3 " }, { "code": null, "e": 11805, "s": 11676, "text": "Time Complexity: O(n), n is the number of elements in the Array.Auxiliary Space: O(n), we are using extra space in the function." }, { "code": null, "e": 11819, "s": 11805, "text": "lokeshpotta20" }, { "code": null, "e": 11829, "s": 11819, "text": "samim2000" }, { "code": null, "e": 11835, "s": 11829, "text": "ukasp" }, { "code": null, "e": 11850, "s": 11835, "text": "varshagumber28" }, { "code": null, "e": 11862, "s": 11850, "text": "29AjayKumar" }, { "code": null, "e": 11875, "s": 11862, "text": "simmytarika5" }, { "code": null, "e": 11892, "s": 11875, "text": "surinderdawra388" }, { "code": null, "e": 11899, "s": 11892, "text": "Arrays" }, { "code": null, "e": 11906, "s": 11899, "text": "Greedy" }, { "code": null, "e": 11919, "s": 11906, "text": "Mathematical" }, { "code": null, "e": 11926, "s": 11919, "text": "Arrays" }, { "code": null, "e": 11933, "s": 11926, "text": "Greedy" }, { "code": null, "e": 11946, "s": 11933, "text": "Mathematical" } ]
How to install requests in Python – For windows, linux, mac
06 Oct, 2021 Requests is an elegant and simple HTTP library for Python, built for human beings. One of the most famous libraries for python used by developers al over the world. This article revolves around how one can install requests library of python in Windows/ Linux/ macOS, etc. For installing requests in windows, one would require Python (preferably latest version), so if you don’t have python installed, head to – How to download and install Python Latest Version on Windows. Now open command prompt from the windows and run following command – python -m pip install requests Booom..!! Done Now, requests library is downloaded successfully. For installing requests in linux, one would require Python (preferably latest version) and pip latest version, so if you don’t have python installed, head to – How to download and install Python Latest Version on Linux. To install pip in linux – How to install PIP in Linux?. Now run, pip install requests For installing requests in mac, one would require Python (preferably latest version) and pip latest version, so if you don’t have python installed, head to – How to download and install Python Latest Version on mac. To install pip mac Os. Run, sudo easy_install pip sudo pip install --upgrade pip Now to install requests, pip install requests THe last method for installation of requests on any operating system is to grab the base files and install requests manually and Requests is actively developed on GitHub, where the code is always available. For code – visit here.You can either clone the public repository: git clone git://github.com/psf/requests.git Or, download the tarball: curl -OL https://github.com/psf/requests/tarball/master # optionally, zipball is also available (for Windows users). Once you have a copy of the source, you can embed it in your own Python package, or install it into your site-packages easily: cd requests pip install . For documentation of requests library – visit here how-to-install Python-requests How To Installation Guide Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Oct, 2021" }, { "code": null, "e": 300, "s": 28, "text": "Requests is an elegant and simple HTTP library for Python, built for human beings. One of the most famous libraries for python used by developers al over the world. This article revolves around how one can install requests library of python in Windows/ Linux/ macOS, etc." }, { "code": null, "e": 570, "s": 300, "text": "For installing requests in windows, one would require Python (preferably latest version), so if you don’t have python installed, head to – How to download and install Python Latest Version on Windows. Now open command prompt from the windows and run following command –" }, { "code": null, "e": 601, "s": 570, "text": "python -m pip install requests" }, { "code": null, "e": 666, "s": 601, "text": "Booom..!! Done Now, requests library is downloaded successfully." }, { "code": null, "e": 951, "s": 666, "text": "For installing requests in linux, one would require Python (preferably latest version) and pip latest version, so if you don’t have python installed, head to – How to download and install Python Latest Version on Linux. To install pip in linux – How to install PIP in Linux?. Now run," }, { "code": null, "e": 972, "s": 951, "text": "pip install requests" }, { "code": null, "e": 1216, "s": 972, "text": "For installing requests in mac, one would require Python (preferably latest version) and pip latest version, so if you don’t have python installed, head to – How to download and install Python Latest Version on mac. To install pip mac Os. Run," }, { "code": null, "e": 1270, "s": 1216, "text": "sudo easy_install pip\nsudo pip install --upgrade pip " }, { "code": null, "e": 1295, "s": 1270, "text": "Now to install requests," }, { "code": null, "e": 1316, "s": 1295, "text": "pip install requests" }, { "code": null, "e": 1589, "s": 1316, "text": "THe last method for installation of requests on any operating system is to grab the base files and install requests manually and Requests is actively developed on GitHub, where the code is always available. For code – visit here.You can either clone the public repository:" }, { "code": null, "e": 1633, "s": 1589, "text": "git clone git://github.com/psf/requests.git" }, { "code": null, "e": 1659, "s": 1633, "text": "Or, download the tarball:" }, { "code": null, "e": 1776, "s": 1659, "text": "curl -OL https://github.com/psf/requests/tarball/master\n# optionally, zipball is also available (for Windows users)." }, { "code": null, "e": 1903, "s": 1776, "text": "Once you have a copy of the source, you can embed it in your own Python package, or install it into your site-packages easily:" }, { "code": null, "e": 1929, "s": 1903, "text": "cd requests\npip install ." }, { "code": null, "e": 1980, "s": 1929, "text": "For documentation of requests library – visit here" }, { "code": null, "e": 1995, "s": 1980, "text": "how-to-install" }, { "code": null, "e": 2011, "s": 1995, "text": "Python-requests" }, { "code": null, "e": 2018, "s": 2011, "text": "How To" }, { "code": null, "e": 2037, "s": 2018, "text": "Installation Guide" }, { "code": null, "e": 2044, "s": 2037, "text": "Python" } ]
How to animate 3D Graph using Matplotlib?
20 Apr, 2022 Prerequisites: Matplotlib, NumPy Graphical representations are always easy to understand and are adopted and preferable before any written or verbal communication. With Matplotlib we can draw different types of Graphical data. In this article, we will try to understand, How can we create a beautiful graph using matplotlib and create a 3D animated Graph using Matplotlib. Approach: Import required module. Create a 3d figure Create sample data Animate 360 views of the graph. Display Graph. Step 1: Import library. Python3 from numpy import linspaceimport matplotlib.pyplot as pltfrom mpl_toolkits import mplot3d Step 2: The purpose of using plt.figure() is to create a figure object. We will use plt.axes () to create separate sets of axes in which you will draw each. Python3 from numpy import linspaceimport matplotlib.pyplot as pltfrom mpl_toolkits import mplot3d fig = plt.figure(figsize = (8,8))ax = plt.axes(projection = '3d') Step 3: In this step, we will create our data and plot different graphs. Python3 from numpy import linspaceimport matplotlib.pyplot as pltfrom mpl_toolkits import mplot3dfrom scipy import signal fig = plt.figure(figsize = (8,8))ax = plt.axes(projection='3d') t = np.linspace(0, 1, 1000, endpoint=True)ax.plot3D(t, signal.square(2 * np.pi * 5 * t)) Step 4: 360-degree movement of the graph. view_init(elev=, azim=)This can be used to rotate the axes programmatically.‘elev’ stores the elevation angle in the z plane. ‘azim’ stores the azimuth angle in the x,y plane.D constructor. The draw() function in pyplot module of the matplotlib library is used to redraw the current figure Python3 from numpy import linspaceimport matplotlib.pyplot as pltfrom mpl_toolkits import mplot3dfrom scipy import signal fig = plt.figure(figsize = (8,8))ax = plt.axes(projection='3d') t = np.linspace(0, 1, 1000, endpoint=True)ax.plot3D(t, signal.square(2 * np.pi * 5 * t)) for angle in range(0, 360): ax.view_init(angle,30) plt.draw() plt.pause(.001) Example 1: In this example, we plot a square wave, and we will see its 360-degree view. Linspace(): A linspace function is a tool in Python for creating numeric sequences.The plot3D() function of matplotlib library is used to make a 3D plotting. Python3 from numpy import linspaceimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits import mplot3dfrom scipy import signal # Creating 3D figurefig = plt.figure(figsize = (8, 8))ax = plt.axes(projection = '3d') # Creating Datasett = np.linspace(0, 1, 1000, endpoint = True)ax.plot3D(t, signal.square(2 * np.pi * 5 * t)) # 360 Degree viewfor angle in range(0, 360): ax.view_init(angle, 30) plt.draw() plt.pause(.001) plt.show() Output: Example 2: In this example, we plot a spiral graph, and we will see its 360-degree view Python3 from numpy import linspaceimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits import mplot3dfrom scipy import signal # Creating 3D figurefig = plt.figure(figsize = (8,8))ax = plt.axes(projection='3d') # Creating Datasetz = np.linspace(0, 15, 1000)x = np.sin(z)y = np.cos(z)ax.plot3D(x, y, z, 'green') # 360 Degree viewfor angle in range(0, 360): ax.view_init(angle, 30) plt.draw() plt.pause(.001) plt.show() Output: Example 3: In this example, we will display the Parabola Graph. plt.rcParams(axes.prop_cycle):- Calling the ‘axes.prop_cycle’ which returns an itertoools.cycle.Linspace(): A linspace function is a tool in Python for creating numeric sequences. Python3 from numpy import linspaceimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits import mplot3dfrom scipy import signal # Creating 3D figurefig = plt.figure(figsize = (8,8))ax = plt.axes(projection = '3d') # Creating Datasetcolor_cycle = plt.rcParams['axes.prop_cycle']()x = linspace(0, 1, 51)a = x*( 1 - x) b = 0.25 - a c = x*x*(1 - x)d = 0.25-c ax.plot3D(x, a, **next(color_cycle)) # 360 Degree viewfor angle in range(0, 360): ax.view_init(angle, 30) plt.draw() plt.pause(.001) plt.show() Output: rkbhola5 Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Apr, 2022" }, { "code": null, "e": 61, "s": 28, "text": "Prerequisites: Matplotlib, NumPy" }, { "code": null, "e": 401, "s": 61, "text": "Graphical representations are always easy to understand and are adopted and preferable before any written or verbal communication. With Matplotlib we can draw different types of Graphical data. In this article, we will try to understand, How can we create a beautiful graph using matplotlib and create a 3D animated Graph using Matplotlib." }, { "code": null, "e": 411, "s": 401, "text": "Approach:" }, { "code": null, "e": 435, "s": 411, "text": "Import required module." }, { "code": null, "e": 454, "s": 435, "text": "Create a 3d figure" }, { "code": null, "e": 473, "s": 454, "text": "Create sample data" }, { "code": null, "e": 505, "s": 473, "text": "Animate 360 views of the graph." }, { "code": null, "e": 520, "s": 505, "text": "Display Graph." }, { "code": null, "e": 544, "s": 520, "text": "Step 1: Import library." }, { "code": null, "e": 552, "s": 544, "text": "Python3" }, { "code": "from numpy import linspaceimport matplotlib.pyplot as pltfrom mpl_toolkits import mplot3d", "e": 642, "s": 552, "text": null }, { "code": null, "e": 799, "s": 642, "text": "Step 2: The purpose of using plt.figure() is to create a figure object. We will use plt.axes () to create separate sets of axes in which you will draw each." }, { "code": null, "e": 807, "s": 799, "text": "Python3" }, { "code": "from numpy import linspaceimport matplotlib.pyplot as pltfrom mpl_toolkits import mplot3d fig = plt.figure(figsize = (8,8))ax = plt.axes(projection = '3d')", "e": 964, "s": 807, "text": null }, { "code": null, "e": 1037, "s": 964, "text": "Step 3: In this step, we will create our data and plot different graphs." }, { "code": null, "e": 1045, "s": 1037, "text": "Python3" }, { "code": "from numpy import linspaceimport matplotlib.pyplot as pltfrom mpl_toolkits import mplot3dfrom scipy import signal fig = plt.figure(figsize = (8,8))ax = plt.axes(projection='3d') t = np.linspace(0, 1, 1000, endpoint=True)ax.plot3D(t, signal.square(2 * np.pi * 5 * t))", "e": 1312, "s": 1045, "text": null }, { "code": null, "e": 1354, "s": 1312, "text": "Step 4: 360-degree movement of the graph." }, { "code": null, "e": 1644, "s": 1354, "text": "view_init(elev=, azim=)This can be used to rotate the axes programmatically.‘elev’ stores the elevation angle in the z plane. ‘azim’ stores the azimuth angle in the x,y plane.D constructor. The draw() function in pyplot module of the matplotlib library is used to redraw the current figure" }, { "code": null, "e": 1652, "s": 1644, "text": "Python3" }, { "code": "from numpy import linspaceimport matplotlib.pyplot as pltfrom mpl_toolkits import mplot3dfrom scipy import signal fig = plt.figure(figsize = (8,8))ax = plt.axes(projection='3d') t = np.linspace(0, 1, 1000, endpoint=True)ax.plot3D(t, signal.square(2 * np.pi * 5 * t)) for angle in range(0, 360): ax.view_init(angle,30) plt.draw() plt.pause(.001)", "e": 2003, "s": 1652, "text": null }, { "code": null, "e": 2091, "s": 2003, "text": "Example 1: In this example, we plot a square wave, and we will see its 360-degree view." }, { "code": null, "e": 2250, "s": 2091, "text": "Linspace(): A linspace function is a tool in Python for creating numeric sequences.The plot3D() function of matplotlib library is used to make a 3D plotting." }, { "code": null, "e": 2258, "s": 2250, "text": "Python3" }, { "code": "from numpy import linspaceimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits import mplot3dfrom scipy import signal # Creating 3D figurefig = plt.figure(figsize = (8, 8))ax = plt.axes(projection = '3d') # Creating Datasett = np.linspace(0, 1, 1000, endpoint = True)ax.plot3D(t, signal.square(2 * np.pi * 5 * t)) # 360 Degree viewfor angle in range(0, 360): ax.view_init(angle, 30) plt.draw() plt.pause(.001) plt.show()", "e": 2703, "s": 2258, "text": null }, { "code": null, "e": 2711, "s": 2703, "text": "Output:" }, { "code": null, "e": 2799, "s": 2711, "text": "Example 2: In this example, we plot a spiral graph, and we will see its 360-degree view" }, { "code": null, "e": 2807, "s": 2799, "text": "Python3" }, { "code": "from numpy import linspaceimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits import mplot3dfrom scipy import signal # Creating 3D figurefig = plt.figure(figsize = (8,8))ax = plt.axes(projection='3d') # Creating Datasetz = np.linspace(0, 15, 1000)x = np.sin(z)y = np.cos(z)ax.plot3D(x, y, z, 'green') # 360 Degree viewfor angle in range(0, 360): ax.view_init(angle, 30) plt.draw() plt.pause(.001) plt.show()", "e": 3239, "s": 2807, "text": null }, { "code": null, "e": 3247, "s": 3239, "text": "Output:" }, { "code": null, "e": 3311, "s": 3247, "text": "Example 3: In this example, we will display the Parabola Graph." }, { "code": null, "e": 3491, "s": 3311, "text": "plt.rcParams(axes.prop_cycle):- Calling the ‘axes.prop_cycle’ which returns an itertoools.cycle.Linspace(): A linspace function is a tool in Python for creating numeric sequences." }, { "code": null, "e": 3499, "s": 3491, "text": "Python3" }, { "code": "from numpy import linspaceimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits import mplot3dfrom scipy import signal # Creating 3D figurefig = plt.figure(figsize = (8,8))ax = plt.axes(projection = '3d') # Creating Datasetcolor_cycle = plt.rcParams['axes.prop_cycle']()x = linspace(0, 1, 51)a = x*( 1 - x) b = 0.25 - a c = x*x*(1 - x)d = 0.25-c ax.plot3D(x, a, **next(color_cycle)) # 360 Degree viewfor angle in range(0, 360): ax.view_init(angle, 30) plt.draw() plt.pause(.001) plt.show()", "e": 4015, "s": 3499, "text": null }, { "code": null, "e": 4023, "s": 4015, "text": "Output:" }, { "code": null, "e": 4032, "s": 4023, "text": "rkbhola5" }, { "code": null, "e": 4050, "s": 4032, "text": "Python-matplotlib" }, { "code": null, "e": 4057, "s": 4050, "text": "Python" } ]
How to clear all cookies using JavaScript ?
29 Jan, 2020 Cookies provide a way for a client and server to interact and pass information via HTTP. This enables the client to store state information despite using HTTP which is a stateless protocol. When a browser requests a web page from a server, the server services the request and “forgets” about the visit. But it passes some information to the user’s browser. The browser stores the information in the form of key=value pairs and also manages this information. Cookie information is passed in the HTTP request header during every subsequent visit to the domain from the user’s browser. Information like login details, consent, other preferences are used to enhance and customize the user experience. HTTP cookies expire, the date and time are specified in the “expires” attribute. As a result, the browser automatically deletes the cookies when the date and time exceed the expiration date (and time). As this attribute is configurable*, it is possible to delete all the cookies by setting the “expiry” to any value that has already passed. The cookie property of the current document is used to modify the attributes of the cookies buy using HTML DOM cookie Property. The document.cookie returns a single string of all the cookies separated by semicolons associated with the current document. Syntax: document.cookie = "key=value"; Code: The code below illustrates how cookies can be deleted using JavaScript. The code is run on an online editor to demonstrate that only cookies created by your site can be deleted by the code. <!DOCTYPE html><html> <head> <meta charset="utf-8"> <title> Clear cookies using Javascript </title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <script type="text/javascript"> document.cookie = "1P_JAR=akjdsbJKHdjhbk"; document.cookie = "CONSENT=YES+IN.en+20170903-09-0"; function displayCookies() { var displayCookies = document.getElementById("display"); displayCookies.innerHTML = document.cookie; } function deleteCookies() { var allCookies = document.cookie.split(';'); // The "expire" attribute of every cookie is // Set to "Thu, 01 Jan 1970 00:00:00 GMT" for (var i = 0; i < allCookies.length; i++) document.cookie = allCookies[i] + "=;expires=" + new Date(0).toUTCString(); displayCookies.innerHTML = document.cookie; } </script> <button onclick="displayCookies()">Display Cookies</button> <button onclick="deleteCookies()">Delete Cookies</button> <p id="display"></p> </center></body> </html> Output:Note: If the attribute “HTTP” of a cookie is set to “True”, it is not possible to modify any of its attributes using JavaScript. Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jan, 2020" }, { "code": null, "e": 486, "s": 28, "text": "Cookies provide a way for a client and server to interact and pass information via HTTP. This enables the client to store state information despite using HTTP which is a stateless protocol. When a browser requests a web page from a server, the server services the request and “forgets” about the visit. But it passes some information to the user’s browser. The browser stores the information in the form of key=value pairs and also manages this information." }, { "code": null, "e": 611, "s": 486, "text": "Cookie information is passed in the HTTP request header during every subsequent visit to the domain from the user’s browser." }, { "code": null, "e": 725, "s": 611, "text": "Information like login details, consent, other preferences are used to enhance and customize the user experience." }, { "code": null, "e": 1066, "s": 725, "text": "HTTP cookies expire, the date and time are specified in the “expires” attribute. As a result, the browser automatically deletes the cookies when the date and time exceed the expiration date (and time). As this attribute is configurable*, it is possible to delete all the cookies by setting the “expiry” to any value that has already passed." }, { "code": null, "e": 1319, "s": 1066, "text": "The cookie property of the current document is used to modify the attributes of the cookies buy using HTML DOM cookie Property. The document.cookie returns a single string of all the cookies separated by semicolons associated with the current document." }, { "code": null, "e": 1327, "s": 1319, "text": "Syntax:" }, { "code": null, "e": 1358, "s": 1327, "text": "document.cookie = \"key=value\";" }, { "code": null, "e": 1554, "s": 1358, "text": "Code: The code below illustrates how cookies can be deleted using JavaScript. The code is run on an online editor to demonstrate that only cookies created by your site can be deleted by the code." }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <title> Clear cookies using Javascript </title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <script type=\"text/javascript\"> document.cookie = \"1P_JAR=akjdsbJKHdjhbk\"; document.cookie = \"CONSENT=YES+IN.en+20170903-09-0\"; function displayCookies() { var displayCookies = document.getElementById(\"display\"); displayCookies.innerHTML = document.cookie; } function deleteCookies() { var allCookies = document.cookie.split(';'); // The \"expire\" attribute of every cookie is // Set to \"Thu, 01 Jan 1970 00:00:00 GMT\" for (var i = 0; i < allCookies.length; i++) document.cookie = allCookies[i] + \"=;expires=\" + new Date(0).toUTCString(); displayCookies.innerHTML = document.cookie; } </script> <button onclick=\"displayCookies()\">Display Cookies</button> <button onclick=\"deleteCookies()\">Delete Cookies</button> <p id=\"display\"></p> </center></body> </html> ", "e": 2805, "s": 1554, "text": null }, { "code": null, "e": 2941, "s": 2805, "text": "Output:Note: If the attribute “HTTP” of a cookie is set to “True”, it is not possible to modify any of its attributes using JavaScript." }, { "code": null, "e": 2948, "s": 2941, "text": "Picked" }, { "code": null, "e": 2959, "s": 2948, "text": "JavaScript" }, { "code": null, "e": 2976, "s": 2959, "text": "Web Technologies" }, { "code": null, "e": 3003, "s": 2976, "text": "Web technologies Questions" } ]
Output of C Programs | Set 4
20 Jan, 2022 Predict the output of below programs Question 1 c #include‹stdio.h›int main(){ struct site { char name[] = "GeeksforGeeks"; int no_of_pages = 200; }; struct site *ptr; printf("%d",ptr->no_of_pages); printf("%s",ptr->name); getchar(); return 0;} Output: Compiler errorExplanation: Note the difference between structure/union declaration and variable declaration. When you declare a structure, you actually declare a new data type suitable for your purpose. So you cannot initialize values as it is not a variable declaration but a data type declaration.Reference: http://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/SYNTAX/struct.htmlQuestion 2 c int main(){ char a[2][3][3] = {'g','e','e','k','s','f','o', 'r','g','e','e','k','s'}; printf("%s ", **a); getchar(); return 0;} Output: geeksforgeeksExplanation: We have created a 3D array that should have 2*3*3 (= 18) elements, but we are initializing only 13 of them. In C when we initialize less no of elements in an array all uninitialized elements become ‘\0’ in case of char and 0 in case of integers. Question 3 c int main(){ char str[]= "geeks\nforgeeks"; char *ptr1, *ptr2; ptr1 = &str[3]; ptr2 = str + 5; printf("%c", ++*str - --*ptr1 + *ptr2 + 2); printf("%s", str); getchar(); return 0;} Output: heejs forgeeksExplanation: Initially ptr1 points to ‘k’ and ptr2 points to ‘\n’ in “geeks\nforgeeks”. In print statement value at str is incremented by 1 and value at ptr1 is decremented by 1. So string becomes “heejs\nforgeeks” . First print statement becomes printf(“%c”, ‘h’ – ‘j’ + ‘\n’ + 2)‘h’ – ‘j’ + ‘\n’ + 2 = -2 + ‘\n’ + 2 = ‘\n’First print statements newline character. and next print statement prints “heejs\nforgeeks”. Question 4 c #include <stdio.h>int fun(int n){ int i, j, sum = 0; for(i = 1;i<=n;i++) for(j=i;j<=i;j++) sum=sum+j; return(sum);} int main(){ printf("%d", fun(15)); getchar(); return 0;} Output: 120 Explanation: fun(n) calculates sum of first n integers or we can say it returns n(n+1)/2.Question 5 c #include <stdio.h>int main(){ int c = 5, no = 1000; do { no /= c; } while(c--); printf ("%d\n", no); return 0;} Output: Exception – Divide by zeroExplanation: There is a bug in the above program. It goes inside the do-while loop for c = 0 also. Be careful when you are using do-while loop like this!! notaverageuser C-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Jan, 2022" }, { "code": null, "e": 92, "s": 54, "text": "Predict the output of below programs " }, { "code": null, "e": 105, "s": 92, "text": "Question 1 " }, { "code": null, "e": 107, "s": 105, "text": "c" }, { "code": "#include‹stdio.h›int main(){ struct site { char name[] = \"GeeksforGeeks\"; int no_of_pages = 200; }; struct site *ptr; printf(\"%d\",ptr->no_of_pages); printf(\"%s\",ptr->name); getchar(); return 0;}", "e": 340, "s": 107, "text": null }, { "code": null, "e": 756, "s": 340, "text": "Output: Compiler errorExplanation: Note the difference between structure/union declaration and variable declaration. When you declare a structure, you actually declare a new data type suitable for your purpose. So you cannot initialize values as it is not a variable declaration but a data type declaration.Reference: http://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/SYNTAX/struct.htmlQuestion 2 " }, { "code": null, "e": 758, "s": 756, "text": "c" }, { "code": "int main(){ char a[2][3][3] = {'g','e','e','k','s','f','o', 'r','g','e','e','k','s'}; printf(\"%s \", **a); getchar(); return 0;}", "e": 924, "s": 758, "text": null }, { "code": null, "e": 1217, "s": 924, "text": "Output: geeksforgeeksExplanation: We have created a 3D array that should have 2*3*3 (= 18) elements, but we are initializing only 13 of them. In C when we initialize less no of elements in an array all uninitialized elements become ‘\\0’ in case of char and 0 in case of integers. Question 3 " }, { "code": null, "e": 1219, "s": 1217, "text": "c" }, { "code": "int main(){ char str[]= \"geeks\\nforgeeks\"; char *ptr1, *ptr2; ptr1 = &str[3]; ptr2 = str + 5; printf(\"%c\", ++*str - --*ptr1 + *ptr2 + 2); printf(\"%s\", str); getchar(); return 0;}", "e": 1422, "s": 1219, "text": null }, { "code": null, "e": 1874, "s": 1422, "text": "Output: heejs forgeeksExplanation: Initially ptr1 points to ‘k’ and ptr2 points to ‘\\n’ in “geeks\\nforgeeks”. In print statement value at str is incremented by 1 and value at ptr1 is decremented by 1. So string becomes “heejs\\nforgeeks” . First print statement becomes printf(“%c”, ‘h’ – ‘j’ + ‘\\n’ + 2)‘h’ – ‘j’ + ‘\\n’ + 2 = -2 + ‘\\n’ + 2 = ‘\\n’First print statements newline character. and next print statement prints “heejs\\nforgeeks”. Question 4 " }, { "code": null, "e": 1876, "s": 1874, "text": "c" }, { "code": "#include <stdio.h>int fun(int n){ int i, j, sum = 0; for(i = 1;i<=n;i++) for(j=i;j<=i;j++) sum=sum+j; return(sum);} int main(){ printf(\"%d\", fun(15)); getchar(); return 0;}", "e": 2085, "s": 1876, "text": null }, { "code": null, "e": 2199, "s": 2085, "text": "Output: 120 Explanation: fun(n) calculates sum of first n integers or we can say it returns n(n+1)/2.Question 5 " }, { "code": null, "e": 2201, "s": 2199, "text": "c" }, { "code": "#include <stdio.h>int main(){ int c = 5, no = 1000; do { no /= c; } while(c--); printf (\"%d\\n\", no); return 0;}", "e": 2336, "s": 2201, "text": null }, { "code": null, "e": 2526, "s": 2336, "text": "Output: Exception – Divide by zeroExplanation: There is a bug in the above program. It goes inside the do-while loop for c = 0 also. Be careful when you are using do-while loop like this!! " }, { "code": null, "e": 2541, "s": 2526, "text": "notaverageuser" }, { "code": null, "e": 2550, "s": 2541, "text": "C-Output" }, { "code": null, "e": 2565, "s": 2550, "text": "Program Output" } ]
Create a V8 Heap Snapshot in ElectronJS
23 Jun, 2020 ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. NodeJS is a JavaScript runtime which uses the Chrome’s V8 engine. NodeJS has many advantages which make it quite popular for the first choice for backend solutions including RESTful APIs. However, NodeJS does have some drawbacks associated with it. One of the major disadvantages of NodeJS is Performance bottlenecks due to heavy computation tasks. This is because NodeJS is single-threaded. This results in slow processing which is why NodeJS is not recommended for heavy computation. In an Electron application, we need to ensure that NodeJS does not have a memory leak which will further slow down the performance. Hence, Electron provides us with a way by which we can take V8 Heap Snapshots using the instance methods of the BrowserWindow Object and the webContents property. We can then use this heap to find Memory leaks in our Electron application using the Chrome DevTools. This tutorial will demonstrate how to take V8 Heap Snapshots and upload it to Chrome DevTools for further Inspection in an Electron application. We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system. Project Structure: Example: Follow the Steps given in Drag and Drop Files in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to setup the Electron application remain the same. package.json: { "name": "electron-snapshot", "version": "1.0.0", "description": "Snapshot of Electron", "main": "main.js", "scripts": { "start": "electron ." }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.3.0" } } Create the assets folder according to the project structure. We will be using the assets folder as the default path to store the V8 Heap Snapshot file generated by the application. The file extension for a V8 Heap Snapshot file is .heapsnapshot. Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result. Heap Snapshots in Electron: The BrowserWindow Instance and webContents Property are part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module. index.html: Add the following snippet in that file. The Create V8 Heap Snapshot button does not have any functionality associated with it yet. html <h3> Create a Snapshot in Electron</h3><button id="snap"> Create V8 Heap Snapshot</button> index.js: Add the following snippet in that file. javascript const electron = require('electron')const path = require('path') // Importing BrowserWindow using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow; let win = BrowserWindow.getFocusedWindow(); // let win = BrowserWindow.getAllWindows()[0];const filepath = path.join(__dirname, '../assets/snap.heapsnapshot') var snap = document.getElementById('snap');snap.addEventListener('click', (event) => { win.webContents.takeHeapSnapshot(filepath) .then(console.log('V8 HeapSnapshot taken Successfully')) .catch(err => { console.log(err); });}); The win.webContents.takeHeapSnapshot(file path) Instance method simply takes a V8 Heap Snapshot of the application memory and Saves it to the given file path. This Instance method returns a Promise and it is resolved when the snapshot file has been created successfully at the given file path. It takes in the following parameters. filepath: String This parameter cannot be Empty. It specifies the filepath where we would like to save the generated Heap Snapshot file. In our code, we have saved the generated Heap Snapshot file to the assets folder along with the name of the file using the path module. To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object. BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly refered from the Array as shown in the code. BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred using this method as shown in the code. Output: Upon launching the application, we should see the following result. snap.heapsnapshot: The snap.heapsnapshot file is just a random set of numbers. To make any sense of this file, we need to upload it to the Chrome DevTools so that we can evaluate it for Memory Leaks. Follow the given Steps to upload this file to Chrome Devtools. Step 1: Within the Electron Application, launch Chrome DevTools incase they have been disabled at application Startup. We can launch using the Keyboard Shortcut, Ctrl+Shift+I. In our code, we have enabled them by default on application startup using the win.webContents.openDevTools() Instance method of the webContents property specified in the main.js file. Step 2: Within the DevTools, go to the Memory Tab and within Select profiling type, choose the Heap snapshot option. After that, Click on the Load Button. This should open a native File System dialog. Step 3: Navigate to where we have stored the .heapsnapshot file and click on Open. This will upload the file and we can now view it within the Chrome DevTools. Click on the file to see the Statistics for the application. Output:Note: We can also use the process.takeHeapSnapshot(filePath) method of the process object to create a V8 Heap Snapshot file of the Electron application. The process object in Electron is an extension of the NodeJS process object which provides an additional variety of Instance method and properties which can be used in the Electron application. ElectronJS HTML JavaScript Node.js Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jun, 2020" }, { "code": null, "e": 328, "s": 28, "text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime." }, { "code": null, "e": 1357, "s": 328, "text": "NodeJS is a JavaScript runtime which uses the Chrome’s V8 engine. NodeJS has many advantages which make it quite popular for the first choice for backend solutions including RESTful APIs. However, NodeJS does have some drawbacks associated with it. One of the major disadvantages of NodeJS is Performance bottlenecks due to heavy computation tasks. This is because NodeJS is single-threaded. This results in slow processing which is why NodeJS is not recommended for heavy computation. In an Electron application, we need to ensure that NodeJS does not have a memory leak which will further slow down the performance. Hence, Electron provides us with a way by which we can take V8 Heap Snapshots using the instance methods of the BrowserWindow Object and the webContents property. We can then use this heap to find Memory leaks in our Electron application using the Chrome DevTools. This tutorial will demonstrate how to take V8 Heap Snapshots and upload it to Chrome DevTools for further Inspection in an Electron application. " }, { "code": null, "e": 1527, "s": 1357, "text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system." }, { "code": null, "e": 1548, "s": 1527, "text": "Project Structure: " }, { "code": null, "e": 2009, "s": 1548, "text": "Example: Follow the Steps given in Drag and Drop Files in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to setup the Electron application remain the same. " }, { "code": null, "e": 2024, "s": 2009, "text": "package.json: " }, { "code": null, "e": 2325, "s": 2024, "text": "{\n \"name\": \"electron-snapshot\",\n \"version\": \"1.0.0\",\n \"description\": \"Snapshot of Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}\n" }, { "code": null, "e": 2705, "s": 2325, "text": "Create the assets folder according to the project structure. We will be using the assets folder as the default path to store the V8 Heap Snapshot file generated by the application. The file extension for a V8 Heap Snapshot file is .heapsnapshot. Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result. " }, { "code": null, "e": 2914, "s": 2705, "text": "Heap Snapshots in Electron: The BrowserWindow Instance and webContents Property are part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module. " }, { "code": null, "e": 3057, "s": 2914, "text": "index.html: Add the following snippet in that file. The Create V8 Heap Snapshot button does not have any functionality associated with it yet." }, { "code": null, "e": 3062, "s": 3057, "text": "html" }, { "code": "<h3> Create a Snapshot in Electron</h3><button id=\"snap\"> Create V8 Heap Snapshot</button>", "e": 3155, "s": 3062, "text": null }, { "code": null, "e": 3205, "s": 3155, "text": "index.js: Add the following snippet in that file." }, { "code": null, "e": 3216, "s": 3205, "text": "javascript" }, { "code": "const electron = require('electron')const path = require('path') // Importing BrowserWindow using Electron remoteconst BrowserWindow = electron.remote.BrowserWindow; let win = BrowserWindow.getFocusedWindow(); // let win = BrowserWindow.getAllWindows()[0];const filepath = path.join(__dirname, '../assets/snap.heapsnapshot') var snap = document.getElementById('snap');snap.addEventListener('click', (event) => { win.webContents.takeHeapSnapshot(filepath) .then(console.log('V8 HeapSnapshot taken Successfully')) .catch(err => { console.log(err); });});", "e": 3808, "s": 3216, "text": null }, { "code": null, "e": 4141, "s": 3808, "text": " The win.webContents.takeHeapSnapshot(file path) Instance method simply takes a V8 Heap Snapshot of the application memory and Saves it to the given file path. This Instance method returns a Promise and it is resolved when the snapshot file has been created successfully at the given file path. It takes in the following parameters." }, { "code": null, "e": 4414, "s": 4141, "text": "filepath: String This parameter cannot be Empty. It specifies the filepath where we would like to save the generated Heap Snapshot file. In our code, we have saved the generated Heap Snapshot file to the assets folder along with the name of the file using the path module." }, { "code": null, "e": 4558, "s": 4414, "text": "To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object. " }, { "code": null, "e": 4796, "s": 4558, "text": "BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly refered from the Array as shown in the code." }, { "code": null, "e": 5118, "s": 4796, "text": "BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred using this method as shown in the code." }, { "code": null, "e": 5195, "s": 5118, "text": "Output: Upon launching the application, we should see the following result. " }, { "code": null, "e": 5215, "s": 5195, "text": "snap.heapsnapshot: " }, { "code": null, "e": 5460, "s": 5215, "text": "The snap.heapsnapshot file is just a random set of numbers. To make any sense of this file, we need to upload it to the Chrome DevTools so that we can evaluate it for Memory Leaks. Follow the given Steps to upload this file to Chrome Devtools. " }, { "code": null, "e": 5820, "s": 5460, "text": "Step 1: Within the Electron Application, launch Chrome DevTools incase they have been disabled at application Startup. We can launch using the Keyboard Shortcut, Ctrl+Shift+I. In our code, we have enabled them by default on application startup using the win.webContents.openDevTools() Instance method of the webContents property specified in the main.js file." }, { "code": null, "e": 6021, "s": 5820, "text": "Step 2: Within the DevTools, go to the Memory Tab and within Select profiling type, choose the Heap snapshot option. After that, Click on the Load Button. This should open a native File System dialog." }, { "code": null, "e": 6242, "s": 6021, "text": "Step 3: Navigate to where we have stored the .heapsnapshot file and click on Open. This will upload the file and we can now view it within the Chrome DevTools. Click on the file to see the Statistics for the application." }, { "code": null, "e": 6597, "s": 6242, "text": "Output:Note: We can also use the process.takeHeapSnapshot(filePath) method of the process object to create a V8 Heap Snapshot file of the Electron application. The process object in Electron is an extension of the NodeJS process object which provides an additional variety of Instance method and properties which can be used in the Electron application. " }, { "code": null, "e": 6608, "s": 6597, "text": "ElectronJS" }, { "code": null, "e": 6613, "s": 6608, "text": "HTML" }, { "code": null, "e": 6624, "s": 6613, "text": "JavaScript" }, { "code": null, "e": 6632, "s": 6624, "text": "Node.js" }, { "code": null, "e": 6649, "s": 6632, "text": "Web Technologies" }, { "code": null, "e": 6654, "s": 6649, "text": "HTML" } ]
Python: Weight Conversion GUI using Tkinter
15 Jan, 2021 Prerequisites: Python GUI – tkinterPython offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task. Steps to Create a Tkinter: Importing the module – tkinter Create the main window (container) Add any number of widgets to the main window Apply the event Trigger on the widgets. Below is what the GUI looks like: Let’s create a GUI based weight converter that accepts a kilogram input value and converts that value to grams, pounds, and ounces when the user clicks the Convert button. Below is the implementation. Python3 # Python program to create a simple GUI # weight converter using Tkinter from tkinter import * # Create a GUI windowwindow = Tk() # Function to convert weight# given in kg to grams, pounds# and ouncesdef from_kg(): # convert kg to gram gram = float(e2_value.get())*1000 # convert kg to pound pound = float(e2_value.get())*2.20462 # convert kg to ounce ounce = float(e2_value.get())*35.274 # Enters the converted weight to # the text widget t1.delete("1.0", END) t1.insert(END,gram) t2.delete("1.0", END) t2.insert(END,pound) t3.delete("1.0", END) t3.insert(END,ounce) # Create the Label widgetse1 = Label(window, text = "Enter the weight in Kg")e2_value = StringVar()e2 = Entry(window, textvariable = e2_value)e3 = Label(window, text = 'Gram')e4 = Label(window, text = 'Pounds')e5 = Label(window, text = 'Ounce') # Create the Text Widgetst1 = Text(window, height = 1, width = 20)t2 = Text(window, height = 1, width = 20)t3 = Text(window, height = 1, width = 20) # Create the Button Widgetb1 = Button(window, text = "Convert", command = from_kg) # grid method is used for placing# the widgets at respective positions# in table like structuree1.grid(row = 0, column = 0)e2.grid(row = 0, column = 1)e3.grid(row = 1, column = 0)e4.grid(row = 1, column = 1)e5.grid(row = 1, column = 2)t1.grid(row = 2, column = 0)t2.grid(row = 2, column = 1)t3.grid(row = 2, column = 2)b1.grid(row = 0, column = 2) # Start the GUIwindow.mainloop() Output: abhigoya Python Tkinter-exercises Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jan, 2021" }, { "code": null, "e": 447, "s": 54, "text": "Prerequisites: Python GUI – tkinterPython offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task. " }, { "code": null, "e": 476, "s": 447, "text": "Steps to Create a Tkinter: " }, { "code": null, "e": 507, "s": 476, "text": "Importing the module – tkinter" }, { "code": null, "e": 542, "s": 507, "text": "Create the main window (container)" }, { "code": null, "e": 587, "s": 542, "text": "Add any number of widgets to the main window" }, { "code": null, "e": 629, "s": 587, "text": "Apply the event Trigger on the widgets. " }, { "code": null, "e": 663, "s": 629, "text": "Below is what the GUI looks like:" }, { "code": null, "e": 835, "s": 663, "text": "Let’s create a GUI based weight converter that accepts a kilogram input value and converts that value to grams, pounds, and ounces when the user clicks the Convert button." }, { "code": null, "e": 865, "s": 835, "text": "Below is the implementation. " }, { "code": null, "e": 873, "s": 865, "text": "Python3" }, { "code": "# Python program to create a simple GUI # weight converter using Tkinter from tkinter import * # Create a GUI windowwindow = Tk() # Function to convert weight# given in kg to grams, pounds# and ouncesdef from_kg(): # convert kg to gram gram = float(e2_value.get())*1000 # convert kg to pound pound = float(e2_value.get())*2.20462 # convert kg to ounce ounce = float(e2_value.get())*35.274 # Enters the converted weight to # the text widget t1.delete(\"1.0\", END) t1.insert(END,gram) t2.delete(\"1.0\", END) t2.insert(END,pound) t3.delete(\"1.0\", END) t3.insert(END,ounce) # Create the Label widgetse1 = Label(window, text = \"Enter the weight in Kg\")e2_value = StringVar()e2 = Entry(window, textvariable = e2_value)e3 = Label(window, text = 'Gram')e4 = Label(window, text = 'Pounds')e5 = Label(window, text = 'Ounce') # Create the Text Widgetst1 = Text(window, height = 1, width = 20)t2 = Text(window, height = 1, width = 20)t3 = Text(window, height = 1, width = 20) # Create the Button Widgetb1 = Button(window, text = \"Convert\", command = from_kg) # grid method is used for placing# the widgets at respective positions# in table like structuree1.grid(row = 0, column = 0)e2.grid(row = 0, column = 1)e3.grid(row = 1, column = 0)e4.grid(row = 1, column = 1)e5.grid(row = 1, column = 2)t1.grid(row = 2, column = 0)t2.grid(row = 2, column = 1)t3.grid(row = 2, column = 2)b1.grid(row = 0, column = 2) # Start the GUIwindow.mainloop()", "e": 2375, "s": 873, "text": null }, { "code": null, "e": 2383, "s": 2375, "text": "Output:" }, { "code": null, "e": 2392, "s": 2383, "text": "abhigoya" }, { "code": null, "e": 2417, "s": 2392, "text": "Python Tkinter-exercises" }, { "code": null, "e": 2432, "s": 2417, "text": "Python-tkinter" }, { "code": null, "e": 2439, "s": 2432, "text": "Python" } ]
Python – Create Dictionary Of Tuples
10 Oct, 2021 In this article, we will discuss how to create a dictionary of tuples in Python. Here we will pass keys as tuples inside a dictionary Syntax: {(tuple1):value,(tuple2):value,.........,(tuple3):value} Here tuple is a collection of elements that work as a key for some value Example: Python program to create a dictionary of tuples with a tuple as keys Python3 # tuple of favourite food as key# value is name of studentdata = {("chapathi", "roti"): 'Bobby', ("Paraota", "Idly", "Dosa"): 'ojaswi'} # displaydata Output: {('Paraota', 'Idly', 'Dosa'): 'ojaswi', ('chapathi', 'roti'): 'Bobby'} Here we will pass values as tuples inside a dictionary Syntax: {key:(tuple),key :(tuple2).........,key:(tuple)} Here tuple is a collection of elements that represent some value for some key. Example: Python program to create dictionary of tuples with tuple as values Python3 # tuple of favourite food as value# key is name of studentdata = {'Bobby': ("chapathi", "roti"), 'ojaswi': ("Paraota", "Idly", "Dosa")} # displaydata Output: {'Bobby': ('chapathi', 'roti'), 'ojaswi': ('Paraota', 'Idly', 'Dosa')} Here we will create a dictionary from nested tuples and for that we need to pass two values in each tuple one will represent key and the other its corresponding value in the dictionary. Syntax: dict((value, key) for key,value in nested_tuple) Example: Create a dictionary from tuples Python3 # one value is age of student# second value is student namedata = ((24, "bobby"), (21, "ojsawi")) # convert into dictionaryfinal = dict((value, key) for key, value in data) # displayprint(final) Output: {'bobby': 24, 'ojsawi': 21} Picked 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": "\n10 Oct, 2021" }, { "code": null, "e": 109, "s": 28, "text": "In this article, we will discuss how to create a dictionary of tuples in Python." }, { "code": null, "e": 162, "s": 109, "text": "Here we will pass keys as tuples inside a dictionary" }, { "code": null, "e": 170, "s": 162, "text": "Syntax:" }, { "code": null, "e": 227, "s": 170, "text": "{(tuple1):value,(tuple2):value,.........,(tuple3):value}" }, { "code": null, "e": 300, "s": 227, "text": "Here tuple is a collection of elements that work as a key for some value" }, { "code": null, "e": 378, "s": 300, "text": "Example: Python program to create a dictionary of tuples with a tuple as keys" }, { "code": null, "e": 386, "s": 378, "text": "Python3" }, { "code": "# tuple of favourite food as key# value is name of studentdata = {(\"chapathi\", \"roti\"): 'Bobby', (\"Paraota\", \"Idly\", \"Dosa\"): 'ojaswi'} # displaydata", "e": 545, "s": 386, "text": null }, { "code": null, "e": 553, "s": 545, "text": "Output:" }, { "code": null, "e": 624, "s": 553, "text": "{('Paraota', 'Idly', 'Dosa'): 'ojaswi', ('chapathi', 'roti'): 'Bobby'}" }, { "code": null, "e": 679, "s": 624, "text": "Here we will pass values as tuples inside a dictionary" }, { "code": null, "e": 687, "s": 679, "text": "Syntax:" }, { "code": null, "e": 736, "s": 687, "text": "{key:(tuple),key :(tuple2).........,key:(tuple)}" }, { "code": null, "e": 815, "s": 736, "text": "Here tuple is a collection of elements that represent some value for some key." }, { "code": null, "e": 891, "s": 815, "text": "Example: Python program to create dictionary of tuples with tuple as values" }, { "code": null, "e": 899, "s": 891, "text": "Python3" }, { "code": "# tuple of favourite food as value# key is name of studentdata = {'Bobby': (\"chapathi\", \"roti\"), 'ojaswi': (\"Paraota\", \"Idly\", \"Dosa\")} # displaydata", "e": 1058, "s": 899, "text": null }, { "code": null, "e": 1066, "s": 1058, "text": "Output:" }, { "code": null, "e": 1137, "s": 1066, "text": "{'Bobby': ('chapathi', 'roti'), 'ojaswi': ('Paraota', 'Idly', 'Dosa')}" }, { "code": null, "e": 1323, "s": 1137, "text": "Here we will create a dictionary from nested tuples and for that we need to pass two values in each tuple one will represent key and the other its corresponding value in the dictionary." }, { "code": null, "e": 1331, "s": 1323, "text": "Syntax:" }, { "code": null, "e": 1380, "s": 1331, "text": "dict((value, key) for key,value in nested_tuple)" }, { "code": null, "e": 1421, "s": 1380, "text": "Example: Create a dictionary from tuples" }, { "code": null, "e": 1429, "s": 1421, "text": "Python3" }, { "code": "# one value is age of student# second value is student namedata = ((24, \"bobby\"), (21, \"ojsawi\")) # convert into dictionaryfinal = dict((value, key) for key, value in data) # displayprint(final)", "e": 1626, "s": 1429, "text": null }, { "code": null, "e": 1634, "s": 1626, "text": "Output:" }, { "code": null, "e": 1662, "s": 1634, "text": "{'bobby': 24, 'ojsawi': 21}" }, { "code": null, "e": 1669, "s": 1662, "text": "Picked" }, { "code": null, "e": 1696, "s": 1669, "text": "Python dictionary-programs" }, { "code": null, "e": 1703, "s": 1696, "text": "Python" }, { "code": null, "e": 1719, "s": 1703, "text": "Python Programs" } ]
Every Function You Can (Should) Use In Pandas for Time Series Data Manipulation | Towards Data Science
Recently, the Optiver Realized Volatility Prediction competition has been launched on Kaggle. As the name suggests, it is a time series forecasting challenge. I wanted to participate, but it turns out my knowledge in time series couldn’t even begin to suffice to participate in a competition of such a magnitude. So, I accepted this as the ‘kick in the pants’ I needed to start paying serious attention to this large sphere of ML. As the first step, I wanted to learn and teach every single Pandas function you can use to manipulate time-series data. These functions are the basic requirements for dealing with any time series data you encounter in the wild. I have got rather cool and interesting articles planned on this topic, and today, you will be reading the first taste of what is to come. Enjoy! The notebook of this article can be read here on Kaggle. Basic data and time functionsMissing data imputation/interpolation in time seriesBasic time series calculations and metricsResampling — upsample and downsampleComparing the growth of multiple time seriesWindow functionsSummary Basic data and time functions Missing data imputation/interpolation in time series Basic time series calculations and metrics Resampling — upsample and downsample Comparing the growth of multiple time series Window functions Summary When using the pd.read_csv function to import time series, there are 2 arguments you should always use - parse_dates and index_col: The datasets have been anonymized due to publication policies. The real versions of the datasets are preserved in the notebook if you are interested. Note that this anonymity won’t hinder your experience. parse_dates converts date-like strings to DateTime objects and index_col sets the passed column as the index. This operation is the basis for all time-series manipulation you will do with Pandas. When you don’t know which column contains dates upon importing, you can perform the date conversion using pd.to_datetime function afterward: Now, inspect the datetime format string: >>> data2.head() It is in the format “%Y-%m-%d” (full list of datetime format strings can be found here). Pass this to pd.to_datetime: Passing a format string to pd.to_datetime significantly speeds up the conversion for large datasets. Set errors to "coerce" to mark invalid dates as NaT (not a date, i.e. - missing). After conversion, set the DateTime column as index (a strict requirement for best time series analysis): >>> data2.set_index("date", inplace=True) The basic date data structure in Pandas is a timestamp: You can make even more granular timestamps using the right format or, better yet, using the datetime module: A full timestamp has useful attributes such as these: A DateTime column/index in pandas is represented as a series of TimeStamp objects. pd.date_range returns a special DateTimeIndex object that is a collection of TimeStamps with a custom frequency over a given range: After specifying the date range (from October 10, 2010, to the same date in 2020), we are telling pandas to generate TimeStamps on a monthly-basis with freq='M': >>> index[0]Timestamp('2010-10-31 00:00:00', freq='M') Another way to create date ranges is passing the start date and telling how many periods you want, and specifying the frequency: Since we set the frequency to years, date_range with 5 periods returns 5 years/timestamp objects. The list of frequency aliases that can be passed to freq is large, so I will only mention the most important ones here: It is also possible to pass custom frequencies such as “1h30min”, “5D”, “2W”, etc. Again, check out this link for the full info. Slicing time series data can be very intuitive if the index is a DateTimeIndex. You can use something called partial slicing: You can even go down to hours, minutes, or seconds levels if the DateTime is granular enough. Note that pandas slices dates in closed intervals. For example, using “2010”: “2013” returns rows for all 4 years — it does not exclude the end of the period like integer slicing. This date slicing logic applies to other operations like choosing a specific column after the slice: Missing data is ubiquitous no matter the type of the dataset. This section is all about imputing it in the context of time series. You may also hear it called interpolation of missing data in time series lingo. Besides the basic mean, median and mode imputation, some of the most common techniques include: Forward fillingBackward fillingIntermediate imputations with pd.interpolate Forward filling Backward filling Intermediate imputations with pd.interpolate We will also discuss model-based imputation such as KNN imputing. Moreover, we will explore visual methods of comparing the efficiency of the techniques and choose the one that best fits the underlying distribution. Let’s start with the basics. We will randomly select data points in the first anonymized dataset and convert them to NaN: We will also create a function that plots the original distribution before and after an imputation(s) is performed: We will start trying out techniques with SimpleImputer from Sklearn: Let’s plot the original feature_2 distribution against the 3 imputed features we just created: It is hard to say which lines most closely resembles the black line, but I will go with the green. Consider this small distribution: We will use both forward and backward filling and assign them back to the DataFrame as separate columns: It should be fairly obvious how these methods work once you examine the above output. Now, let’s perform these methods on the Airquality in India dataset: Even though very basic, forward and backward filling actually works pretty well on climate and stocks data since the differences between nearby data points are small. Pandas provides a whole suite of other statistical imputation techniques in pd.interpolate function. Its method parameter accepts the name of the technique as a string. The most popular ones are ‘linear’ and ‘nearest,’ but you can see the full list from the function’s documentation. Here, we will only discuss those two. Consider this small distribution: Once again, we apply the methods and assign their results back: Neat, huh? The linear method considers the distance between any two non-missing points as linearly spaced and finds a linear line that connects them (like np.linspace). 'Nearest' method should be understandable from its name and the above output. The last method we will see is the K-Nearest-Neighbors algorithm. I won’t detail how the algorithm works but only show how you can use it with Sklearn. If you want the details, I have a separate article here. The most important parameter of KNN is k - the number of neighbors. We will apply the technique to the first dataset with several values of k and find the best one the same way as we did in the previous sections: Pandas offers basic functions to calculate the most common time series calculations. These are called shifts, lags, and something called a percentage change. A common operation in time series is to move all data points one or more periods backward or forward to compare past and future values. You can do these operations using shift function of pandas. Let's see how to move the data points 1 and 2 periods into the future: Shifting forward enables you to compare the current data point to those recorded one or more periods before. You can also shift backward. This operation is also called “lagging”: Shifting backward enables us to see the difference between the current data point and the one that comes one or more periods later. A common operation after shifting or lagging is finding the difference and plotting it: Since this operation is so common, Pandas has the diff function that computes the differences based on the period: Another common metric that can be derived from time-series data is day-to-day percentage change: To calculate day-to-day percentage change, shift one period forward and divide the original distribution by the shifted one and subtract 1. The resulting values are given as proportions of what they were the day before. Since it is a common operation, Pandas implements it with the pct_change function: Often, you may want to increase or decrease the granularity of time series to generate new insights. These operations are called resampling or changing the frequency of time series, and we will discuss the Pandas functions related to them in this section. The second dataset does not have a fixed date frequency, i.e., the period difference between each date is not the same: data2.head() Let’s fix this by giving it a calendar day frequency (daily): data2.asfreq("D").head(7) We just made the frequency of the date more granular. As a result, new dates were added, leading to more missing values. You can now interpolate them using any of the techniques we discussed earlier. You can see the list of built-in frequency aliases from here. A more interesting scenario would be using custom frequencies: # 10 month frequencydata2.asfreq("10M", method="bfill").head(7) There is also a reindex function that operates similarly and supports additional missing value filling logic. We won't discuss it here as there are better options we will consider. In time series lingo, making the frequency of a DateTime less granular is called downsampling. The examples are changing the frequency from hourly to daily, from daily to weekly, etc. We saw how to downsample with asfreq. A more powerful alternative is resample which behaves like pd.groupby. Just like groupby groups the data based on categorical values, resample groups the data by date frequencies. Let’s downsample the first dataset by month-end frequency: Unlike asfreq, using resample only returns the data in the resampled state. To see each group, we need to use some type of function, similar to how we use groupby. Since downsampling decreases the number of data points, we need an aggregation function like mean, median, or mode: data1.resample("M").mean().tail() There are also functions that return the first or last record of a group: It is also possible to use multiple aggregating functions using agg: The opposite of downsampling is making the DateTime more granular. This is called upsampling and includes operations like changing the frequency from daily to hourly, hourly to seconds, etc. When upsampling, you introduce new dates leading to more missing values. This means you need to use some type of imputation: Resampling isn’t going to give much if you don’t plot its results. In most cases, you will see new trends and patterns when you downsample. This is because downsampling reduces the granularity, thus eliminating noise: Plotting the upsampled distribution is only going to introduce more noise, so we won’t do it here. It is common to compare two or more numeric values that change over time. For example, we might want to see the growth rate of feature 1 and 2 in the first dataset. But here is the problem: The second distribution have much higher values. Plotting them together would probably squish feature_1 to a flat line. In other words, the two distributions have different scales. To fix this, statisticians use normalization. The most common variation is choosing the first recorded value and dividing the rest of the samples by that amount. This shows how each record changes compared to the first. Here is an example: Each row in the above output now shows the percentage growth compared to the first row. Now, let’s plot them to compare the growth rate: Both features achieved over 300% growth from 2011 to 2017. You can even plot time series from other datasets: As you can see, features in dataset 1 have much higher growth than another feature in the second dataset. There is another type of function that helps you analyze time-series data in novel ways. These are called window functions, and they help you aggregate over a custom number of rows called ‘windows.’ For example, I can create a 30-day window over my Medium subscribers data to see the total number of subscribers for the past 30 days on any given day. Or a restaurant owner might create a weekly window to see average sales of the past week. Examples are endless as you can create a window of any size over your data. Let’s explore these in more detail. Rolling window functions will have the same length. As they slide through the data, their coverage (number of rows don’t change). Here is an example window of 5 periods sliding through the data: Here is how we create rolling windows in pandas: >>> data1.rolling(window=5)Rolling [window=5,center=False,axis=0] Just like resample, it is in a read-only state - to use each window, we should chain some type of function. For example, let's create a cumulative sum for every past 5 periods: Obviously, the first 4 rows will be NaNs. Any other row will contain the sum of the previous 4 rows and the current one. Pay attention to the window argument. If you pass an integer, the window size will be determined by that number of rows. If you pass a frequency alias such as months, years, 5 hours, or 7 weeks, the window size will be whatever number of rows that includes the single unit of the passed frequency. In other words, a 5-period window might have a different size than a 5-day frequency window. As an example, let’s plot 90 and 360-day moving averages for feature 2 and plot them: Just like groupby and resample, you can calculate multiple metrics with the agg function for each window. Another type of window function deals with expanding windows. Each new window will contain all the records up to the current date: Expanding windows are useful for calculating ‘running’ metrics-for example, running sum, mean, min and max, running rate of return, etc. Below, you will see how to calculate the cumulative sum. The cumulative sum is actually an expanding window function with a window size of 1: expanding function has a min_periods parameter that determines the initial window size. Now, let’s see how to plot the running min and max: I think congratulations are in order! Now, you know every single Pandas function you can use to manipulate time-series data. It has been an excruciatingly long post, but it was definitely worth it since now, you can tackle any time series data thrown at you. This post was mainly focused on data manipulation. The next posts in the series will be about more in-depth time series analyses, similar posts on every single plot you can create on time series, and dedicated articles on forecasting. Stay tuned! Matplotlib vs. Plotly: Let’s Decide Once and for All 6 Things I Do to Consistently Improve My Machine Learning Models 5 Super Productive Things To Do While Training Machine Learning Models
[ { "code": null, "e": 330, "s": 171, "text": "Recently, the Optiver Realized Volatility Prediction competition has been launched on Kaggle. As the name suggests, it is a time series forecasting challenge." }, { "code": null, "e": 602, "s": 330, "text": "I wanted to participate, but it turns out my knowledge in time series couldn’t even begin to suffice to participate in a competition of such a magnitude. So, I accepted this as the ‘kick in the pants’ I needed to start paying serious attention to this large sphere of ML." }, { "code": null, "e": 830, "s": 602, "text": "As the first step, I wanted to learn and teach every single Pandas function you can use to manipulate time-series data. These functions are the basic requirements for dealing with any time series data you encounter in the wild." }, { "code": null, "e": 975, "s": 830, "text": "I have got rather cool and interesting articles planned on this topic, and today, you will be reading the first taste of what is to come. Enjoy!" }, { "code": null, "e": 1032, "s": 975, "text": "The notebook of this article can be read here on Kaggle." }, { "code": null, "e": 1259, "s": 1032, "text": "Basic data and time functionsMissing data imputation/interpolation in time seriesBasic time series calculations and metricsResampling — upsample and downsampleComparing the growth of multiple time seriesWindow functionsSummary" }, { "code": null, "e": 1289, "s": 1259, "text": "Basic data and time functions" }, { "code": null, "e": 1342, "s": 1289, "text": "Missing data imputation/interpolation in time series" }, { "code": null, "e": 1385, "s": 1342, "text": "Basic time series calculations and metrics" }, { "code": null, "e": 1422, "s": 1385, "text": "Resampling — upsample and downsample" }, { "code": null, "e": 1467, "s": 1422, "text": "Comparing the growth of multiple time series" }, { "code": null, "e": 1484, "s": 1467, "text": "Window functions" }, { "code": null, "e": 1492, "s": 1484, "text": "Summary" }, { "code": null, "e": 1624, "s": 1492, "text": "When using the pd.read_csv function to import time series, there are 2 arguments you should always use - parse_dates and index_col:" }, { "code": null, "e": 1829, "s": 1624, "text": "The datasets have been anonymized due to publication policies. The real versions of the datasets are preserved in the notebook if you are interested. Note that this anonymity won’t hinder your experience." }, { "code": null, "e": 2025, "s": 1829, "text": "parse_dates converts date-like strings to DateTime objects and index_col sets the passed column as the index. This operation is the basis for all time-series manipulation you will do with Pandas." }, { "code": null, "e": 2166, "s": 2025, "text": "When you don’t know which column contains dates upon importing, you can perform the date conversion using pd.to_datetime function afterward:" }, { "code": null, "e": 2207, "s": 2166, "text": "Now, inspect the datetime format string:" }, { "code": null, "e": 2224, "s": 2207, "text": ">>> data2.head()" }, { "code": null, "e": 2342, "s": 2224, "text": "It is in the format “%Y-%m-%d” (full list of datetime format strings can be found here). Pass this to pd.to_datetime:" }, { "code": null, "e": 2525, "s": 2342, "text": "Passing a format string to pd.to_datetime significantly speeds up the conversion for large datasets. Set errors to \"coerce\" to mark invalid dates as NaT (not a date, i.e. - missing)." }, { "code": null, "e": 2630, "s": 2525, "text": "After conversion, set the DateTime column as index (a strict requirement for best time series analysis):" }, { "code": null, "e": 2672, "s": 2630, "text": ">>> data2.set_index(\"date\", inplace=True)" }, { "code": null, "e": 2728, "s": 2672, "text": "The basic date data structure in Pandas is a timestamp:" }, { "code": null, "e": 2837, "s": 2728, "text": "You can make even more granular timestamps using the right format or, better yet, using the datetime module:" }, { "code": null, "e": 2891, "s": 2837, "text": "A full timestamp has useful attributes such as these:" }, { "code": null, "e": 2974, "s": 2891, "text": "A DateTime column/index in pandas is represented as a series of TimeStamp objects." }, { "code": null, "e": 3106, "s": 2974, "text": "pd.date_range returns a special DateTimeIndex object that is a collection of TimeStamps with a custom frequency over a given range:" }, { "code": null, "e": 3268, "s": 3106, "text": "After specifying the date range (from October 10, 2010, to the same date in 2020), we are telling pandas to generate TimeStamps on a monthly-basis with freq='M':" }, { "code": null, "e": 3323, "s": 3268, "text": ">>> index[0]Timestamp('2010-10-31 00:00:00', freq='M')" }, { "code": null, "e": 3452, "s": 3323, "text": "Another way to create date ranges is passing the start date and telling how many periods you want, and specifying the frequency:" }, { "code": null, "e": 3670, "s": 3452, "text": "Since we set the frequency to years, date_range with 5 periods returns 5 years/timestamp objects. The list of frequency aliases that can be passed to freq is large, so I will only mention the most important ones here:" }, { "code": null, "e": 3799, "s": 3670, "text": "It is also possible to pass custom frequencies such as “1h30min”, “5D”, “2W”, etc. Again, check out this link for the full info." }, { "code": null, "e": 3925, "s": 3799, "text": "Slicing time series data can be very intuitive if the index is a DateTimeIndex. You can use something called partial slicing:" }, { "code": null, "e": 4019, "s": 3925, "text": "You can even go down to hours, minutes, or seconds levels if the DateTime is granular enough." }, { "code": null, "e": 4199, "s": 4019, "text": "Note that pandas slices dates in closed intervals. For example, using “2010”: “2013” returns rows for all 4 years — it does not exclude the end of the period like integer slicing." }, { "code": null, "e": 4300, "s": 4199, "text": "This date slicing logic applies to other operations like choosing a specific column after the slice:" }, { "code": null, "e": 4431, "s": 4300, "text": "Missing data is ubiquitous no matter the type of the dataset. This section is all about imputing it in the context of time series." }, { "code": null, "e": 4511, "s": 4431, "text": "You may also hear it called interpolation of missing data in time series lingo." }, { "code": null, "e": 4607, "s": 4511, "text": "Besides the basic mean, median and mode imputation, some of the most common techniques include:" }, { "code": null, "e": 4683, "s": 4607, "text": "Forward fillingBackward fillingIntermediate imputations with pd.interpolate" }, { "code": null, "e": 4699, "s": 4683, "text": "Forward filling" }, { "code": null, "e": 4716, "s": 4699, "text": "Backward filling" }, { "code": null, "e": 4761, "s": 4716, "text": "Intermediate imputations with pd.interpolate" }, { "code": null, "e": 4977, "s": 4761, "text": "We will also discuss model-based imputation such as KNN imputing. Moreover, we will explore visual methods of comparing the efficiency of the techniques and choose the one that best fits the underlying distribution." }, { "code": null, "e": 5099, "s": 4977, "text": "Let’s start with the basics. We will randomly select data points in the first anonymized dataset and convert them to NaN:" }, { "code": null, "e": 5215, "s": 5099, "text": "We will also create a function that plots the original distribution before and after an imputation(s) is performed:" }, { "code": null, "e": 5284, "s": 5215, "text": "We will start trying out techniques with SimpleImputer from Sklearn:" }, { "code": null, "e": 5379, "s": 5284, "text": "Let’s plot the original feature_2 distribution against the 3 imputed features we just created:" }, { "code": null, "e": 5478, "s": 5379, "text": "It is hard to say which lines most closely resembles the black line, but I will go with the green." }, { "code": null, "e": 5512, "s": 5478, "text": "Consider this small distribution:" }, { "code": null, "e": 5617, "s": 5512, "text": "We will use both forward and backward filling and assign them back to the DataFrame as separate columns:" }, { "code": null, "e": 5703, "s": 5617, "text": "It should be fairly obvious how these methods work once you examine the above output." }, { "code": null, "e": 5772, "s": 5703, "text": "Now, let’s perform these methods on the Airquality in India dataset:" }, { "code": null, "e": 5939, "s": 5772, "text": "Even though very basic, forward and backward filling actually works pretty well on climate and stocks data since the differences between nearby data points are small." }, { "code": null, "e": 6108, "s": 5939, "text": "Pandas provides a whole suite of other statistical imputation techniques in pd.interpolate function. Its method parameter accepts the name of the technique as a string." }, { "code": null, "e": 6261, "s": 6108, "text": "The most popular ones are ‘linear’ and ‘nearest,’ but you can see the full list from the function’s documentation. Here, we will only discuss those two." }, { "code": null, "e": 6295, "s": 6261, "text": "Consider this small distribution:" }, { "code": null, "e": 6359, "s": 6295, "text": "Once again, we apply the methods and assign their results back:" }, { "code": null, "e": 6606, "s": 6359, "text": "Neat, huh? The linear method considers the distance between any two non-missing points as linearly spaced and finds a linear line that connects them (like np.linspace). 'Nearest' method should be understandable from its name and the above output." }, { "code": null, "e": 6815, "s": 6606, "text": "The last method we will see is the K-Nearest-Neighbors algorithm. I won’t detail how the algorithm works but only show how you can use it with Sklearn. If you want the details, I have a separate article here." }, { "code": null, "e": 7028, "s": 6815, "text": "The most important parameter of KNN is k - the number of neighbors. We will apply the technique to the first dataset with several values of k and find the best one the same way as we did in the previous sections:" }, { "code": null, "e": 7186, "s": 7028, "text": "Pandas offers basic functions to calculate the most common time series calculations. These are called shifts, lags, and something called a percentage change." }, { "code": null, "e": 7453, "s": 7186, "text": "A common operation in time series is to move all data points one or more periods backward or forward to compare past and future values. You can do these operations using shift function of pandas. Let's see how to move the data points 1 and 2 periods into the future:" }, { "code": null, "e": 7562, "s": 7453, "text": "Shifting forward enables you to compare the current data point to those recorded one or more periods before." }, { "code": null, "e": 7632, "s": 7562, "text": "You can also shift backward. This operation is also called “lagging”:" }, { "code": null, "e": 7764, "s": 7632, "text": "Shifting backward enables us to see the difference between the current data point and the one that comes one or more periods later." }, { "code": null, "e": 7852, "s": 7764, "text": "A common operation after shifting or lagging is finding the difference and plotting it:" }, { "code": null, "e": 7967, "s": 7852, "text": "Since this operation is so common, Pandas has the diff function that computes the differences based on the period:" }, { "code": null, "e": 8064, "s": 7967, "text": "Another common metric that can be derived from time-series data is day-to-day percentage change:" }, { "code": null, "e": 8284, "s": 8064, "text": "To calculate day-to-day percentage change, shift one period forward and divide the original distribution by the shifted one and subtract 1. The resulting values are given as proportions of what they were the day before." }, { "code": null, "e": 8367, "s": 8284, "text": "Since it is a common operation, Pandas implements it with the pct_change function:" }, { "code": null, "e": 8623, "s": 8367, "text": "Often, you may want to increase or decrease the granularity of time series to generate new insights. These operations are called resampling or changing the frequency of time series, and we will discuss the Pandas functions related to them in this section." }, { "code": null, "e": 8743, "s": 8623, "text": "The second dataset does not have a fixed date frequency, i.e., the period difference between each date is not the same:" }, { "code": null, "e": 8756, "s": 8743, "text": "data2.head()" }, { "code": null, "e": 8818, "s": 8756, "text": "Let’s fix this by giving it a calendar day frequency (daily):" }, { "code": null, "e": 8844, "s": 8818, "text": "data2.asfreq(\"D\").head(7)" }, { "code": null, "e": 9044, "s": 8844, "text": "We just made the frequency of the date more granular. As a result, new dates were added, leading to more missing values. You can now interpolate them using any of the techniques we discussed earlier." }, { "code": null, "e": 9169, "s": 9044, "text": "You can see the list of built-in frequency aliases from here. A more interesting scenario would be using custom frequencies:" }, { "code": null, "e": 9233, "s": 9169, "text": "# 10 month frequencydata2.asfreq(\"10M\", method=\"bfill\").head(7)" }, { "code": null, "e": 9414, "s": 9233, "text": "There is also a reindex function that operates similarly and supports additional missing value filling logic. We won't discuss it here as there are better options we will consider." }, { "code": null, "e": 9598, "s": 9414, "text": "In time series lingo, making the frequency of a DateTime less granular is called downsampling. The examples are changing the frequency from hourly to daily, from daily to weekly, etc." }, { "code": null, "e": 9816, "s": 9598, "text": "We saw how to downsample with asfreq. A more powerful alternative is resample which behaves like pd.groupby. Just like groupby groups the data based on categorical values, resample groups the data by date frequencies." }, { "code": null, "e": 9875, "s": 9816, "text": "Let’s downsample the first dataset by month-end frequency:" }, { "code": null, "e": 10039, "s": 9875, "text": "Unlike asfreq, using resample only returns the data in the resampled state. To see each group, we need to use some type of function, similar to how we use groupby." }, { "code": null, "e": 10155, "s": 10039, "text": "Since downsampling decreases the number of data points, we need an aggregation function like mean, median, or mode:" }, { "code": null, "e": 10189, "s": 10155, "text": "data1.resample(\"M\").mean().tail()" }, { "code": null, "e": 10263, "s": 10189, "text": "There are also functions that return the first or last record of a group:" }, { "code": null, "e": 10332, "s": 10263, "text": "It is also possible to use multiple aggregating functions using agg:" }, { "code": null, "e": 10523, "s": 10332, "text": "The opposite of downsampling is making the DateTime more granular. This is called upsampling and includes operations like changing the frequency from daily to hourly, hourly to seconds, etc." }, { "code": null, "e": 10648, "s": 10523, "text": "When upsampling, you introduce new dates leading to more missing values. This means you need to use some type of imputation:" }, { "code": null, "e": 10715, "s": 10648, "text": "Resampling isn’t going to give much if you don’t plot its results." }, { "code": null, "e": 10866, "s": 10715, "text": "In most cases, you will see new trends and patterns when you downsample. This is because downsampling reduces the granularity, thus eliminating noise:" }, { "code": null, "e": 10965, "s": 10866, "text": "Plotting the upsampled distribution is only going to introduce more noise, so we won’t do it here." }, { "code": null, "e": 11155, "s": 10965, "text": "It is common to compare two or more numeric values that change over time. For example, we might want to see the growth rate of feature 1 and 2 in the first dataset. But here is the problem:" }, { "code": null, "e": 11336, "s": 11155, "text": "The second distribution have much higher values. Plotting them together would probably squish feature_1 to a flat line. In other words, the two distributions have different scales." }, { "code": null, "e": 11556, "s": 11336, "text": "To fix this, statisticians use normalization. The most common variation is choosing the first recorded value and dividing the rest of the samples by that amount. This shows how each record changes compared to the first." }, { "code": null, "e": 11576, "s": 11556, "text": "Here is an example:" }, { "code": null, "e": 11664, "s": 11576, "text": "Each row in the above output now shows the percentage growth compared to the first row." }, { "code": null, "e": 11713, "s": 11664, "text": "Now, let’s plot them to compare the growth rate:" }, { "code": null, "e": 11823, "s": 11713, "text": "Both features achieved over 300% growth from 2011 to 2017. You can even plot time series from other datasets:" }, { "code": null, "e": 11929, "s": 11823, "text": "As you can see, features in dataset 1 have much higher growth than another feature in the second dataset." }, { "code": null, "e": 12128, "s": 11929, "text": "There is another type of function that helps you analyze time-series data in novel ways. These are called window functions, and they help you aggregate over a custom number of rows called ‘windows.’" }, { "code": null, "e": 12446, "s": 12128, "text": "For example, I can create a 30-day window over my Medium subscribers data to see the total number of subscribers for the past 30 days on any given day. Or a restaurant owner might create a weekly window to see average sales of the past week. Examples are endless as you can create a window of any size over your data." }, { "code": null, "e": 12482, "s": 12446, "text": "Let’s explore these in more detail." }, { "code": null, "e": 12677, "s": 12482, "text": "Rolling window functions will have the same length. As they slide through the data, their coverage (number of rows don’t change). Here is an example window of 5 periods sliding through the data:" }, { "code": null, "e": 12726, "s": 12677, "text": "Here is how we create rolling windows in pandas:" }, { "code": null, "e": 12792, "s": 12726, "text": ">>> data1.rolling(window=5)Rolling [window=5,center=False,axis=0]" }, { "code": null, "e": 12969, "s": 12792, "text": "Just like resample, it is in a read-only state - to use each window, we should chain some type of function. For example, let's create a cumulative sum for every past 5 periods:" }, { "code": null, "e": 13090, "s": 12969, "text": "Obviously, the first 4 rows will be NaNs. Any other row will contain the sum of the previous 4 rows and the current one." }, { "code": null, "e": 13481, "s": 13090, "text": "Pay attention to the window argument. If you pass an integer, the window size will be determined by that number of rows. If you pass a frequency alias such as months, years, 5 hours, or 7 weeks, the window size will be whatever number of rows that includes the single unit of the passed frequency. In other words, a 5-period window might have a different size than a 5-day frequency window." }, { "code": null, "e": 13567, "s": 13481, "text": "As an example, let’s plot 90 and 360-day moving averages for feature 2 and plot them:" }, { "code": null, "e": 13673, "s": 13567, "text": "Just like groupby and resample, you can calculate multiple metrics with the agg function for each window." }, { "code": null, "e": 13804, "s": 13673, "text": "Another type of window function deals with expanding windows. Each new window will contain all the records up to the current date:" }, { "code": null, "e": 13941, "s": 13804, "text": "Expanding windows are useful for calculating ‘running’ metrics-for example, running sum, mean, min and max, running rate of return, etc." }, { "code": null, "e": 14083, "s": 13941, "text": "Below, you will see how to calculate the cumulative sum. The cumulative sum is actually an expanding window function with a window size of 1:" }, { "code": null, "e": 14171, "s": 14083, "text": "expanding function has a min_periods parameter that determines the initial window size." }, { "code": null, "e": 14223, "s": 14171, "text": "Now, let’s see how to plot the running min and max:" }, { "code": null, "e": 14261, "s": 14223, "text": "I think congratulations are in order!" }, { "code": null, "e": 14482, "s": 14261, "text": "Now, you know every single Pandas function you can use to manipulate time-series data. It has been an excruciatingly long post, but it was definitely worth it since now, you can tackle any time series data thrown at you." }, { "code": null, "e": 14729, "s": 14482, "text": "This post was mainly focused on data manipulation. The next posts in the series will be about more in-depth time series analyses, similar posts on every single plot you can create on time series, and dedicated articles on forecasting. Stay tuned!" }, { "code": null, "e": 14782, "s": 14729, "text": "Matplotlib vs. Plotly: Let’s Decide Once and for All" }, { "code": null, "e": 14847, "s": 14782, "text": "6 Things I Do to Consistently Improve My Machine Learning Models" } ]
Plot a black-and-white binary map in Matplotlib
To plot black-and-white binary map in matplotlib, we can create and add two subplots to the current figure using subplot() method, where nrows=1 and ncols=2. To display the data as a binary map, we can use greys colormap in imshow() method. Create data using numpy Add two sublots, nrows=1 and ncols=2. Consider index 1. To show colored image, use imshow() method. Add title to the colored map. Add a second subplot at index 2. To show the binary map, use show() method with Greys colormap. To adjust the padding between and around the subplots, use tight_layout() method. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True data = np.random.rand(4, 4) plt.subplot(121) plt.imshow(data) plt.title("Colored Image") plt.subplot(122) plt.imshow(data, cmap='Greys_r', interpolation='nearest') plt.title("Greys Image") plt.tight_layout() plt.show()
[ { "code": null, "e": 1303, "s": 1062, "text": "To plot black-and-white binary map in matplotlib, we can create and add two subplots to the current figure using subplot() method, where nrows=1 and ncols=2. To display the data as a binary map, we can use greys colormap in imshow() method." }, { "code": null, "e": 1327, "s": 1303, "text": "Create data using numpy" }, { "code": null, "e": 1383, "s": 1327, "text": "Add two sublots, nrows=1 and ncols=2. Consider index 1." }, { "code": null, "e": 1427, "s": 1383, "text": "To show colored image, use imshow() method." }, { "code": null, "e": 1457, "s": 1427, "text": "Add title to the colored map." }, { "code": null, "e": 1490, "s": 1457, "text": "Add a second subplot at index 2." }, { "code": null, "e": 1553, "s": 1490, "text": "To show the binary map, use show() method with Greys colormap." }, { "code": null, "e": 1635, "s": 1553, "text": "To adjust the padding between and around the subplots, use tight_layout() method." }, { "code": null, "e": 1677, "s": 1635, "text": "To display the figure, use show() method." }, { "code": null, "e": 2039, "s": 1677, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndata = np.random.rand(4, 4)\nplt.subplot(121)\nplt.imshow(data)\nplt.title(\"Colored Image\")\nplt.subplot(122)\nplt.imshow(data, cmap='Greys_r', interpolation='nearest')\nplt.title(\"Greys Image\")\nplt.tight_layout()\nplt.show()" } ]
SQLite - Views
A view is nothing more than a SQLite statement that is stored in the database with an associated name. It is actually a composition of a table in the form of a predefined SQLite query. A view can contain all rows of a table or selected rows from one or more tables. A view can be created from one or many tables which depends on the written SQLite query to create a view. Views which are kind of virtual tables, allow the users to − Structure data in a way that users or classes of users find natural or intuitive. Structure data in a way that users or classes of users find natural or intuitive. Restrict access to the data such that a user can only see limited data instead of a complete table. Restrict access to the data such that a user can only see limited data instead of a complete table. Summarize data from various tables, which can be used to generate reports. Summarize data from various tables, which can be used to generate reports. SQLite views are read-only and thus you may not be able to execute a DELETE, INSERT or UPDATE statement on a view. However, you can create a trigger on a view that fires on an attempt to DELETE, INSERT, or UPDATE a view and do what you need in the body of the trigger. SQLite views are created using the CREATE VIEW statement. SQLite views can be created from a single table, multiple tables, or another view. Following is the basic CREATE VIEW syntax. CREATE [TEMP | TEMPORARY] VIEW view_name AS SELECT column1, column2..... FROM table_name WHERE [condition]; You can include multiple tables in your SELECT statement in a similar way as you use them in a normal SQL SELECT query. If the optional TEMP or TEMPORARY keyword is present, the view will be created in the temp database. Consider COMPANY table with the following records − ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 Following is an example to create a view from COMPANY table. This view will be used to have only a few columns from COMPANY table. sqlite> CREATE VIEW COMPANY_VIEW AS SELECT ID, NAME, AGE FROM COMPANY; You can now query COMPANY_VIEW in a similar way as you query an actual table. Following is an example − sqlite> SELECT * FROM COMPANY_VIEW; This will produce the following result. ID NAME AGE ---------- ---------- ---------- 1 Paul 32 2 Allen 25 3 Teddy 23 4 Mark 25 5 David 27 6 Kim 22 7 James 24 To drop a view, simply use the DROP VIEW statement with the view_name. The basic DROP VIEW syntax is as follows − sqlite> DROP VIEW view_name; The following command will delete COMPANY_VIEW view, which we created in the last section. sqlite> DROP VIEW COMPANY_VIEW; 25 Lectures 4.5 hours Sandip Bhattacharya 17 Lectures 1 hours Laurence Svekis 5 Lectures 51 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2823, "s": 2638, "text": "A view is nothing more than a SQLite statement that is stored in the database with an associated name. It is actually a composition of a table in the form of a predefined SQLite query." }, { "code": null, "e": 3010, "s": 2823, "text": "A view can contain all rows of a table or selected rows from one or more tables. A view can be created from one or many tables which depends on the written SQLite query to create a view." }, { "code": null, "e": 3071, "s": 3010, "text": "Views which are kind of virtual tables, allow the users to −" }, { "code": null, "e": 3153, "s": 3071, "text": "Structure data in a way that users or classes of users find natural or intuitive." }, { "code": null, "e": 3235, "s": 3153, "text": "Structure data in a way that users or classes of users find natural or intuitive." }, { "code": null, "e": 3335, "s": 3235, "text": "Restrict access to the data such that a user can only see limited data instead of a complete table." }, { "code": null, "e": 3435, "s": 3335, "text": "Restrict access to the data such that a user can only see limited data instead of a complete table." }, { "code": null, "e": 3510, "s": 3435, "text": "Summarize data from various tables, which can be used to generate reports." }, { "code": null, "e": 3585, "s": 3510, "text": "Summarize data from various tables, which can be used to generate reports." }, { "code": null, "e": 3854, "s": 3585, "text": "SQLite views are read-only and thus you may not be able to execute a DELETE, INSERT or UPDATE statement on a view. However, you can create a trigger on a view that fires on an attempt to DELETE, INSERT, or UPDATE a view and do what you need in the body of the trigger." }, { "code": null, "e": 3995, "s": 3854, "text": "SQLite views are created using the CREATE VIEW statement. SQLite views can be created from a single table, multiple tables, or another view." }, { "code": null, "e": 4038, "s": 3995, "text": "Following is the basic CREATE VIEW syntax." }, { "code": null, "e": 4147, "s": 4038, "text": "CREATE [TEMP | TEMPORARY] VIEW view_name AS\nSELECT column1, column2.....\nFROM table_name\nWHERE [condition];\n" }, { "code": null, "e": 4368, "s": 4147, "text": "You can include multiple tables in your SELECT statement in a similar way as you use them in a normal SQL SELECT query. If the optional TEMP or TEMPORARY keyword is present, the view will be created in the temp database." }, { "code": null, "e": 4420, "s": 4368, "text": "Consider COMPANY table with the following records −" }, { "code": null, "e": 4926, "s": 4420, "text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0" }, { "code": null, "e": 5057, "s": 4926, "text": "Following is an example to create a view from COMPANY table. This view will be used to have only a few columns from COMPANY table." }, { "code": null, "e": 5129, "s": 5057, "text": "sqlite> CREATE VIEW COMPANY_VIEW AS\nSELECT ID, NAME, AGE\nFROM COMPANY;" }, { "code": null, "e": 5233, "s": 5129, "text": "You can now query COMPANY_VIEW in a similar way as you query an actual table. Following is an example −" }, { "code": null, "e": 5269, "s": 5233, "text": "sqlite> SELECT * FROM COMPANY_VIEW;" }, { "code": null, "e": 5309, "s": 5269, "text": "This will produce the following result." }, { "code": null, "e": 5562, "s": 5309, "text": "ID NAME AGE\n---------- ---------- ----------\n1 Paul 32\n2 Allen 25\n3 Teddy 23\n4 Mark 25\n5 David 27\n6 Kim 22\n7 James 24\n" }, { "code": null, "e": 5676, "s": 5562, "text": "To drop a view, simply use the DROP VIEW statement with the view_name. The basic DROP VIEW syntax is as follows −" }, { "code": null, "e": 5706, "s": 5676, "text": "sqlite> DROP VIEW view_name;\n" }, { "code": null, "e": 5797, "s": 5706, "text": "The following command will delete COMPANY_VIEW view, which we created in the last section." }, { "code": null, "e": 5829, "s": 5797, "text": "sqlite> DROP VIEW COMPANY_VIEW;" }, { "code": null, "e": 5864, "s": 5829, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5885, "s": 5864, "text": " Sandip Bhattacharya" }, { "code": null, "e": 5918, "s": 5885, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 5935, "s": 5918, "text": " Laurence Svekis" }, { "code": null, "e": 5966, "s": 5935, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 5979, "s": 5966, "text": " Vinay Kumar" }, { "code": null, "e": 5986, "s": 5979, "text": " Print" }, { "code": null, "e": 5997, "s": 5986, "text": " Add Notes" } ]
HTML5 Canvas - Styles and Colors
HTML5 canvas provides the following two important properties to apply colors to a shape − fillStyle This attribute represents the color or style to use inside the shapes. strokeStyle This attribute represents the color or style to use for the lines around shapes. By default, the stroke and fill color are set to black which is CSS color value #000000. Following is a simple example which makes use of the above-mentioned fillStyle attribute to create a nice pattern. <!DOCTYPE HTML> <html> <head> <style> #test { width: 100px; height:100px; margin: 0px auto; } </style> <script type = "text/javascript"> function drawShape() { // get the canvas element using the DOM var canvas = document.getElementById('mycanvas'); // Make sure we don't execute when canvas isn't supported if (canvas.getContext) { // use getContext to use the canvas for drawing var ctx = canvas.getContext('2d'); // Create a pattern for (var i = 0;i<7;i++) { for (var j = 0;j<7;j++) { ctx.fillStyle = 'rgb(' + Math.floor(255-20.5*i)+ ','+ Math.floor(255 - 42.5*j) + ',255)'; ctx.fillRect( j*25, i* 25, 55, 55 ); } } } else { alert('You need Safari or Firefox 1.5+ to see this demo.'); } } </script> </head> <body id = "test" onload = "drawShape();"> <canvas id = "mycanvas"></canvas> </body> </html> The above example would produce the following result − Following is a simple example which makes use of the above-mentioned fillStyle attribute to create another nice pattern. <!DOCTYPE HTML> <html> <head> <style> #test { width: 100px; height:100px; margin: 0px auto; } </style> <script type = "text/javascript"> function drawShape() { // get the canvas element using the DOM var canvas = document.getElementById('mycanvas'); // Make sure we don't execute when canvas isn't supported if (canvas.getContext) { // use getContext to use the canvas for drawing var ctx = canvas.getContext('2d'); // Create a pattern for (var i = 0;i<10;i++) { for (var j = 0;j<10;j++) { ctx.strokeStyle = 'rgb(255,'+ Math.floor(50-2.5*i)+','+ Math.floor(155 - 22.5 * j ) + ')'; ctx.beginPath(); ctx.arc(1.5+j*25, 1.5 + i*25,10,10,Math.PI*5.5, true); ctx.stroke(); } } } else { alert('You need Safari or Firefox 1.5+ to see this demo.'); } } </script> </head> <body id = "test" onload = "drawShape();"> <canvas id = "mycanvas"></canvas> </body> </html> The above example would produce the following result − 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2698, "s": 2608, "text": "HTML5 canvas provides the following two important properties to apply colors to a shape −" }, { "code": null, "e": 2708, "s": 2698, "text": "fillStyle" }, { "code": null, "e": 2779, "s": 2708, "text": "This attribute represents the color or style to use inside the shapes." }, { "code": null, "e": 2791, "s": 2779, "text": "strokeStyle" }, { "code": null, "e": 2872, "s": 2791, "text": "This attribute represents the color or style to use for the lines around shapes." }, { "code": null, "e": 2961, "s": 2872, "text": "By default, the stroke and fill color are set to black which is CSS color value #000000." }, { "code": null, "e": 3076, "s": 2961, "text": "Following is a simple example which makes use of the above-mentioned fillStyle attribute to create a nice pattern." }, { "code": null, "e": 4355, "s": 3076, "text": "<!DOCTYPE HTML>\n\n<html>\n <head>\n \n <style>\n #test {\n width: 100px;\n height:100px;\n margin: 0px auto;\n }\n </style>\n \n <script type = \"text/javascript\">\n function drawShape() {\n \n // get the canvas element using the DOM\n var canvas = document.getElementById('mycanvas');\n \n // Make sure we don't execute when canvas isn't supported\n if (canvas.getContext) {\n \n // use getContext to use the canvas for drawing\n var ctx = canvas.getContext('2d');\n \n // Create a pattern\n for (var i = 0;i<7;i++) {\n \n for (var j = 0;j<7;j++) { \n ctx.fillStyle = 'rgb(' + Math.floor(255-20.5*i)+ ','+ \n Math.floor(255 - 42.5*j) + ',255)';\n ctx.fillRect( j*25, i* 25, 55, 55 );\n }\n }\n } else {\n alert('You need Safari or Firefox 1.5+ to see this demo.');\n }\n }\n </script>\n </head>\n \n <body id = \"test\" onload = \"drawShape();\">\n <canvas id = \"mycanvas\"></canvas>\n </body>\n\n</html>" }, { "code": null, "e": 4410, "s": 4355, "text": "The above example would produce the following result −" }, { "code": null, "e": 4531, "s": 4410, "text": "Following is a simple example which makes use of the above-mentioned fillStyle attribute to create another nice pattern." }, { "code": null, "e": 5890, "s": 4531, "text": "<!DOCTYPE HTML>\n\n<html>\n <head>\n \n <style>\n #test {\n width: 100px;\n height:100px;\n margin: 0px auto;\n }\n </style>\n <script type = \"text/javascript\">\n function drawShape() {\n \n // get the canvas element using the DOM\n var canvas = document.getElementById('mycanvas');\n \n // Make sure we don't execute when canvas isn't supported\n if (canvas.getContext) {\n \n // use getContext to use the canvas for drawing\n var ctx = canvas.getContext('2d');\n \n // Create a pattern\n for (var i = 0;i<10;i++) {\n \n for (var j = 0;j<10;j++) {\n ctx.strokeStyle = 'rgb(255,'+ Math.floor(50-2.5*i)+','+ \n Math.floor(155 - 22.5 * j ) + ')';\n ctx.beginPath();\n ctx.arc(1.5+j*25, 1.5 + i*25,10,10,Math.PI*5.5, true);\n ctx.stroke();\n }\n }\n } else {\n alert('You need Safari or Firefox 1.5+ to see this demo.');\n }\n }\n </script>\n </head>\n \n <body id = \"test\" onload = \"drawShape();\">\n <canvas id = \"mycanvas\"></canvas>\n </body>\n \n</html>" }, { "code": null, "e": 5945, "s": 5890, "text": "The above example would produce the following result −" }, { "code": null, "e": 5978, "s": 5945, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 5992, "s": 5978, "text": " Anadi Sharma" }, { "code": null, "e": 6027, "s": 5992, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6041, "s": 6027, "text": " Anadi Sharma" }, { "code": null, "e": 6076, "s": 6041, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6093, "s": 6076, "text": " Frahaan Hussain" }, { "code": null, "e": 6128, "s": 6093, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6159, "s": 6128, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 6192, "s": 6159, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 6223, "s": 6192, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 6258, "s": 6223, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6289, "s": 6258, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 6296, "s": 6289, "text": " Print" }, { "code": null, "e": 6307, "s": 6296, "text": " Add Notes" } ]
JavaMail API - Core Classes
The JavaMail API consists of some interfaces and classes used to send, read, and delete e-mail messages. Though there are many packages in the JavaMail API, will cover the main two packages that are used in Java Mail API frequently: javax.mail and javax.mail.internet package. These packages contain all the JavaMail core classes. They are: Let us study each of these classes in detail and in the subsequent chapters we shall study examples using each of these. The Session class is the primary class of the JavaMail API and it is not subclassed. The Session object acts as the connection factory for the JavaMail API, which handles both configuration setting and authentication. Session object can be created in the following ways: By looking up the administered object stored in the JNDI service InitialContext ctx = new InitialContext(); Session session = (Session) ctx.lookup("usersMailSession"); usersMailSession is the JNDI name object used as the administered object for the Session object. usersMailSession can be created and configured with the required parameters as name/value pairs, including information such as the mail server hostname, the user account sending the mail, and the protocols supported by the Session object. By looking up the administered object stored in the JNDI service InitialContext ctx = new InitialContext(); Session session = (Session) ctx.lookup("usersMailSession"); usersMailSession is the JNDI name object used as the administered object for the Session object. usersMailSession can be created and configured with the required parameters as name/value pairs, including information such as the mail server hostname, the user account sending the mail, and the protocols supported by the Session object. Another method of creating the Session object is based on the programmatic approach in which you can use a java.util.Properties object to override some of the default information, such as the mail server name, username, password, and other information that can be shared across your entire application. Another method of creating the Session object is based on the programmatic approach in which you can use a java.util.Properties object to override some of the default information, such as the mail server name, username, password, and other information that can be shared across your entire application. The constructor for Session class is private. Hence the Session class provides two methods (listed below) which get the Session object. getDefaultInstance(): There are two methods to get the session object by using the getDefaultInstance() method. It returns the default session. public static Session getDefaultInstance(Properties props) public static Session getDefaultInstance(Properties props,Authenticator auth) getDefaultInstance(): There are two methods to get the session object by using the getDefaultInstance() method. It returns the default session. public static Session getDefaultInstance(Properties props) public static Session getDefaultInstance(Properties props,Authenticator auth) getInstance(): There are two methods to get the session object by using the getInstance() method. It returns the new session. public static Session getInstance(Properties props) public static Session getInstance(Properties props,Authenticator auth) getInstance(): There are two methods to get the session object by using the getInstance() method. It returns the new session. public static Session getInstance(Properties props) public static Session getInstance(Properties props,Authenticator auth) With Session object created we now move on to creating a message that will be sent. The message type will be javax.mail.Message. Message is an abstract class. Hence its subclass javax.mail.internet.MimeMessage class is mostly used. Message is an abstract class. Hence its subclass javax.mail.internet.MimeMessage class is mostly used. To create the message, you need to pass session object in MimeMessage class constructor. For example: MimeMessage message=new MimeMessage(session); To create the message, you need to pass session object in MimeMessage class constructor. For example: MimeMessage message=new MimeMessage(session); Once the message object is created we need to store information in it. Message class implements the javax.mail.Part interface while javax.mail.internet. MimeMessage implements javax.mail.internet.MimePart. You can either use message.setContent() or mimeMessage.setText() to store the content. Once the message object is created we need to store information in it. Message class implements the javax.mail.Part interface while javax.mail.internet. MimeMessage implements javax.mail.internet.MimePart. You can either use message.setContent() or mimeMessage.setText() to store the content. Commonly used methods of MimeMessage class are MethodDescription public void setFrom(Address address)used to set the from header field. public void addRecipients(Message.RecipientType type, String addresses) used to add the given address to the recipient type. public void setSubject(String subject)used to set the subject header field. public void setText(String textmessage) used to set the text as the message content using text/plain MIME type. Commonly used methods of MimeMessage class are Now that we have a Session and Message (with content stored in it) objects, we need to address the letter by using Address object. Address is an abstract class. Hence its subclass javax.mail.internet.InternetAddress class is mostly used. Address is an abstract class. Hence its subclass javax.mail.internet.InternetAddress class is mostly used. Address can be created by just passing email address: Address address = new InternetAddress("[email protected]"); Address can be created by just passing email address: Address address = new InternetAddress("[email protected]"); Another way of creating Address is by passing name alogwith the email address: Address address = new InternetAddress("[email protected]", Manisha); Another way of creating Address is by passing name alogwith the email address: Address address = new InternetAddress("[email protected]", Manisha); You can also set the To, From, CC, BCC fields as below message.setFrom(address) message.addRecipient(type, address) Three predefined address types are objects with one of these values: Message.RecipientType.TO Message.RecipientType.CC Message.RecipientType.BCC You can also set the To, From, CC, BCC fields as below message.setFrom(address) message.setFrom(address) message.addRecipient(type, address) message.addRecipient(type, address) Three predefined address types are objects with one of these values: Message.RecipientType.TO Message.RecipientType.CC Message.RecipientType.BCC Three predefined address types are objects with one of these values: Message.RecipientType.TO Message.RecipientType.TO Message.RecipientType.CC Message.RecipientType.CC Message.RecipientType.BCC Message.RecipientType.BCC The class Authenticator represents an object that knows how to obtain authentication for a network connection. Usually, it will do this by prompting the user for information. Authenticator is an abstract class. You create a subclass PasswordAuthentication, passing a username and password to its constructor. Authenticator is an abstract class. You create a subclass PasswordAuthentication, passing a username and password to its constructor. You must register the Authenticator with the Session when you create session object. You must register the Authenticator with the Session when you create session object. Following is an example of Authenticator use: Properties props = new Properties(); //Override props with any customized data PasswordAuthentication auth = new PasswordAuthentication("manisha", "pswrd") Session session = Session.getDefaultInstance(props, auth); Transport class is used as a message transport mechanism. This class normally uses the SMTP protocol to send a message. It is an abstract class. It is an abstract class. You can use the default version of the class by just calling the static send() method: Transport.send(message); You can use the default version of the class by just calling the static send() method: Transport.send(message); The other way to send message is by getting a specific instance from the session for your protocol, pass along the username and password (blank if unnecessary), send the message, and close the connection: message.saveChanges(); // implicit with send() //Get transport for session Transport transport = session.getTransport("smtp"); //Connect transport.connect(host, username, password); //repeat if necessary transport.sendMessage(message, message.getAllRecipients()); //Done, close the connection transport.close(); The other way to send message is by getting a specific instance from the session for your protocol, pass along the username and password (blank if unnecessary), send the message, and close the connection: message.saveChanges(); // implicit with send() //Get transport for session Transport transport = session.getTransport("smtp"); //Connect transport.connect(host, username, password); //repeat if necessary transport.sendMessage(message, message.getAllRecipients()); //Done, close the connection transport.close(); An abstract class that models a message store and its access protocol, for storing and retrieving messages. Subclasses provide actual implementations. Store extends the Service class, which provides many common methods for naming stores, connecting to stores, and listening to connection events. Clients gain access to a Message Store by obtaining a Store object that implements the database access protocol. Most message stores require the user to be authenticated before they allow access. The connect method performs that authentication. Store store = session.getStore("pop3"); store.connect(host, username, password); Folder is an abstract class that represents a folder for mail messages. Subclasses implement protocol specific Folders. Folders can contain subfolders as well as messages, thus providing a hierarchical structure. After connecting to the Store, you can then get a Folder, which must be opened before you can read messages from it. Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); Message message[] = folder.getMessages(); The getFolder(String name) method for a Folder object returns the named subfolder. Close the both the Store and Folder connection once reading mail is done. We can see the Store and Folder relation the image below: As we can see, for each user account, the server has a store which is the storage of user’s messages. The store is divided into folders, and the “inbox” folder is the primarily folder which contains e-mail messages. A folder can contain both messages and sub-folders. Print Add Notes Bookmark this page
[ { "code": null, "e": 2412, "s": 2071, "text": "The JavaMail API consists of some interfaces and classes used to send, read, and delete e-mail messages. Though there are many packages in the JavaMail API, will cover the main two packages that are used in Java Mail API frequently: javax.mail and javax.mail.internet package. These packages contain all the JavaMail core classes. They are:" }, { "code": null, "e": 2533, "s": 2412, "text": "Let us study each of these classes in detail and in the subsequent chapters we shall study examples using each of these." }, { "code": null, "e": 2752, "s": 2533, "text": "The Session class is the primary class of the JavaMail API and it is not subclassed. The Session object acts as the connection factory for the JavaMail API, which handles both configuration setting and authentication. " }, { "code": null, "e": 2805, "s": 2752, "text": "Session object can be created in the following ways:" }, { "code": null, "e": 3311, "s": 2805, "text": "By looking up the administered object stored in the JNDI service\nInitialContext ctx = new InitialContext();\nSession session = (Session) ctx.lookup(\"usersMailSession\");\nusersMailSession is the JNDI name object used as the administered object for the Session object. usersMailSession can be created and configured with the required parameters as name/value pairs, including information such as the mail server hostname, the user account sending the mail, and the protocols supported by the Session object. \n" }, { "code": null, "e": 3376, "s": 3311, "text": "By looking up the administered object stored in the JNDI service" }, { "code": null, "e": 3479, "s": 3376, "text": "InitialContext ctx = new InitialContext();\nSession session = (Session) ctx.lookup(\"usersMailSession\");" }, { "code": null, "e": 3816, "s": 3479, "text": "usersMailSession is the JNDI name object used as the administered object for the Session object. usersMailSession can be created and configured with the required parameters as name/value pairs, including information such as the mail server hostname, the user account sending the mail, and the protocols supported by the Session object. " }, { "code": null, "e": 4120, "s": 3816, "text": "Another method of creating the Session object is based on the programmatic approach in which you can use a java.util.Properties object to override some of the default information, such as the mail server name, username, password, and other information that can be shared across your entire application. " }, { "code": null, "e": 4424, "s": 4120, "text": "Another method of creating the Session object is based on the programmatic approach in which you can use a java.util.Properties object to override some of the default information, such as the mail server name, username, password, and other information that can be shared across your entire application. " }, { "code": null, "e": 4560, "s": 4424, "text": "The constructor for Session class is private. Hence the Session class provides two methods (listed below) which get the Session object." }, { "code": null, "e": 4842, "s": 4560, "text": "getDefaultInstance(): There are two methods to get the session object by using the getDefaultInstance() method. It returns the default session.\npublic static Session getDefaultInstance(Properties props)\npublic static Session getDefaultInstance(Properties props,Authenticator auth)\n" }, { "code": null, "e": 4986, "s": 4842, "text": "getDefaultInstance(): There are two methods to get the session object by using the getDefaultInstance() method. It returns the default session." }, { "code": null, "e": 5123, "s": 4986, "text": "public static Session getDefaultInstance(Properties props)\npublic static Session getDefaultInstance(Properties props,Authenticator auth)" }, { "code": null, "e": 5373, "s": 5123, "text": "getInstance(): There are two methods to get the session object by using the getInstance() method. It returns the new session.\npublic static Session getInstance(Properties props)\npublic static Session getInstance(Properties props,Authenticator auth)\n" }, { "code": null, "e": 5499, "s": 5373, "text": "getInstance(): There are two methods to get the session object by using the getInstance() method. It returns the new session." }, { "code": null, "e": 5622, "s": 5499, "text": "public static Session getInstance(Properties props)\npublic static Session getInstance(Properties props,Authenticator auth)" }, { "code": null, "e": 5751, "s": 5622, "text": "With Session object created we now move on to creating a message that will be sent. The message type will be javax.mail.Message." }, { "code": null, "e": 5854, "s": 5751, "text": "Message is an abstract class. Hence its subclass javax.mail.internet.MimeMessage class is mostly used." }, { "code": null, "e": 5957, "s": 5854, "text": "Message is an abstract class. Hence its subclass javax.mail.internet.MimeMessage class is mostly used." }, { "code": null, "e": 6106, "s": 5957, "text": "To create the message, you need to pass session object in MimeMessage class constructor. For example:\nMimeMessage message=new MimeMessage(session);\n" }, { "code": null, "e": 6208, "s": 6106, "text": "To create the message, you need to pass session object in MimeMessage class constructor. For example:" }, { "code": null, "e": 6254, "s": 6208, "text": "MimeMessage message=new MimeMessage(session);" }, { "code": null, "e": 6548, "s": 6254, "text": "Once the message object is created we need to store information in it. Message class implements the javax.mail.Part interface while javax.mail.internet. MimeMessage implements javax.mail.internet.MimePart. You can either use message.setContent() or mimeMessage.setText() to store the content.\n" }, { "code": null, "e": 6842, "s": 6548, "text": "Once the message object is created we need to store information in it. Message class implements the javax.mail.Part interface while javax.mail.internet. MimeMessage implements javax.mail.internet.MimePart. You can either use message.setContent() or mimeMessage.setText() to store the content.\n" }, { "code": null, "e": 7294, "s": 6842, "text": "Commonly used methods of MimeMessage class are\n\nMethodDescription\npublic void setFrom(Address address)used to set the from header field.\npublic void addRecipients(Message.RecipientType type, String addresses) used to add the given address to the recipient type.\npublic void setSubject(String subject)used to set the subject header field.\npublic void setText(String textmessage) used to set the text as the message content using text/plain MIME type.\n\n" }, { "code": null, "e": 7341, "s": 7294, "text": "Commonly used methods of MimeMessage class are" }, { "code": null, "e": 7473, "s": 7341, "text": "Now that we have a Session and Message (with content stored in it) objects, we need to address the letter by using Address object. " }, { "code": null, "e": 7581, "s": 7473, "text": "Address is an abstract class. Hence its subclass javax.mail.internet.InternetAddress class is mostly used." }, { "code": null, "e": 7689, "s": 7581, "text": "Address is an abstract class. Hence its subclass javax.mail.internet.InternetAddress class is mostly used." }, { "code": null, "e": 7805, "s": 7689, "text": "Address can be created by just passing email address:\nAddress address = new InternetAddress(\"[email protected]\"); \n" }, { "code": null, "e": 7859, "s": 7805, "text": "Address can be created by just passing email address:" }, { "code": null, "e": 7920, "s": 7859, "text": "Address address = new InternetAddress(\"[email protected]\"); " }, { "code": null, "e": 8070, "s": 7920, "text": "Another way of creating Address is by passing name alogwith the email address:\nAddress address = new InternetAddress(\"[email protected]\", Manisha); \n" }, { "code": null, "e": 8149, "s": 8070, "text": "Another way of creating Address is by passing name alogwith the email address:" }, { "code": null, "e": 8219, "s": 8149, "text": "Address address = new InternetAddress(\"[email protected]\", Manisha); " }, { "code": null, "e": 8486, "s": 8219, "text": "You can also set the To, From, CC, BCC fields as below\n\nmessage.setFrom(address)\nmessage.addRecipient(type, address)\nThree predefined address types are objects with one of these values:\n\nMessage.RecipientType.TO\nMessage.RecipientType.CC\nMessage.RecipientType.BCC\n\n\n\n" }, { "code": null, "e": 8541, "s": 8486, "text": "You can also set the To, From, CC, BCC fields as below" }, { "code": null, "e": 8566, "s": 8541, "text": "message.setFrom(address)" }, { "code": null, "e": 8591, "s": 8566, "text": "message.setFrom(address)" }, { "code": null, "e": 8627, "s": 8591, "text": "message.addRecipient(type, address)" }, { "code": null, "e": 8663, "s": 8627, "text": "message.addRecipient(type, address)" }, { "code": null, "e": 8811, "s": 8663, "text": "Three predefined address types are objects with one of these values:\n\nMessage.RecipientType.TO\nMessage.RecipientType.CC\nMessage.RecipientType.BCC\n\n" }, { "code": null, "e": 8880, "s": 8811, "text": "Three predefined address types are objects with one of these values:" }, { "code": null, "e": 8905, "s": 8880, "text": "Message.RecipientType.TO" }, { "code": null, "e": 8930, "s": 8905, "text": "Message.RecipientType.TO" }, { "code": null, "e": 8955, "s": 8930, "text": "Message.RecipientType.CC" }, { "code": null, "e": 8980, "s": 8955, "text": "Message.RecipientType.CC" }, { "code": null, "e": 9006, "s": 8980, "text": "Message.RecipientType.BCC" }, { "code": null, "e": 9032, "s": 9006, "text": "Message.RecipientType.BCC" }, { "code": null, "e": 9207, "s": 9032, "text": "The class Authenticator represents an object that knows how to obtain authentication for a network connection. Usually, it will do this by prompting the user for information." }, { "code": null, "e": 9342, "s": 9207, "text": "Authenticator is an abstract class. You create a subclass PasswordAuthentication, passing a username and password to its constructor. " }, { "code": null, "e": 9477, "s": 9342, "text": "Authenticator is an abstract class. You create a subclass PasswordAuthentication, passing a username and password to its constructor. " }, { "code": null, "e": 9562, "s": 9477, "text": "You must register the Authenticator with the Session when you create session object." }, { "code": null, "e": 9647, "s": 9562, "text": "You must register the Authenticator with the Session when you create session object." }, { "code": null, "e": 9693, "s": 9647, "text": "Following is an example of Authenticator use:" }, { "code": null, "e": 9908, "s": 9693, "text": "Properties props = new Properties();\n//Override props with any customized data\nPasswordAuthentication auth = new PasswordAuthentication(\"manisha\", \"pswrd\")\nSession session = Session.getDefaultInstance(props, auth);" }, { "code": null, "e": 10029, "s": 9908, "text": "Transport class is used as a message transport mechanism. This class normally uses the SMTP protocol to send a message. " }, { "code": null, "e": 10054, "s": 10029, "text": "It is an abstract class." }, { "code": null, "e": 10079, "s": 10054, "text": "It is an abstract class." }, { "code": null, "e": 10193, "s": 10079, "text": "You can use the default version of the class by just calling the static send() method: \nTransport.send(message);\n" }, { "code": null, "e": 10281, "s": 10193, "text": "You can use the default version of the class by just calling the static send() method: " }, { "code": null, "e": 10306, "s": 10281, "text": "Transport.send(message);" }, { "code": null, "e": 10825, "s": 10306, "text": "The other way to send message is by getting a specific instance from the session for your protocol, pass along the username and password (blank if unnecessary), send the message, and close the connection: \nmessage.saveChanges(); // implicit with send()\n//Get transport for session\nTransport transport = session.getTransport(\"smtp\");\n//Connect\ntransport.connect(host, username, password);\n//repeat if necessary\ntransport.sendMessage(message, message.getAllRecipients());\n//Done, close the connection\ntransport.close();\n" }, { "code": null, "e": 11031, "s": 10825, "text": "The other way to send message is by getting a specific instance from the session for your protocol, pass along the username and password (blank if unnecessary), send the message, and close the connection: " }, { "code": null, "e": 11343, "s": 11031, "text": "message.saveChanges(); // implicit with send()\n//Get transport for session\nTransport transport = session.getTransport(\"smtp\");\n//Connect\ntransport.connect(host, username, password);\n//repeat if necessary\ntransport.sendMessage(message, message.getAllRecipients());\n//Done, close the connection\ntransport.close();" }, { "code": null, "e": 11639, "s": 11343, "text": "An abstract class that models a message store and its access protocol, for storing and retrieving messages. Subclasses provide actual implementations. Store extends the Service class, which provides many common methods for naming stores, connecting to stores, and listening to connection events." }, { "code": null, "e": 11884, "s": 11639, "text": "Clients gain access to a Message Store by obtaining a Store object that implements the database access protocol. Most message stores require the user to be authenticated before they allow access. The connect method performs that authentication." }, { "code": null, "e": 11965, "s": 11884, "text": "Store store = session.getStore(\"pop3\");\nstore.connect(host, username, password);" }, { "code": null, "e": 12178, "s": 11965, "text": "Folder is an abstract class that represents a folder for mail messages. Subclasses implement protocol specific Folders. Folders can contain subfolders as well as messages, thus providing a hierarchical structure." }, { "code": null, "e": 12295, "s": 12178, "text": "After connecting to the Store, you can then get a Folder, which must be opened before you can read messages from it." }, { "code": null, "e": 12410, "s": 12295, "text": "Folder folder = store.getFolder(\"INBOX\");\nfolder.open(Folder.READ_ONLY);\nMessage message[] = folder.getMessages();" }, { "code": null, "e": 12567, "s": 12410, "text": "The getFolder(String name) method for a Folder object returns the named subfolder. Close the both the Store and Folder connection once reading mail is done." }, { "code": null, "e": 12625, "s": 12567, "text": "We can see the Store and Folder relation the image below:" }, { "code": null, "e": 12893, "s": 12625, "text": "As we can see, for each user account, the server has a store which is the storage of user’s messages. The store is divided into folders, and the “inbox” folder is the primarily folder which contains e-mail messages. A folder can contain both messages and sub-folders." }, { "code": null, "e": 12900, "s": 12893, "text": " Print" }, { "code": null, "e": 12911, "s": 12900, "text": " Add Notes" } ]
JavaMail API - Bounced Messages
A message can be bounced for several reasons. This problem is discussed in depth at rfc1211. Only a server can determine the existence of a particular mailbox or user name. When the server detects an error, it will return a message indicating the reason for the failure to the sender of the original message. There are many Internet standards covering Delivery Status Notifications but a large number of servers don't support these new standards, instead using ad hoc techniques for returning such failure messages. Hence it get very difficult to correlate the bounced message with the original message that caused the problem. JavaMail includes support for parsing Delivery Status Notifications. There are a number of techniques and heuristics for dealing with this problem. One of the techniques being Variable Envelope Return Paths. You can set the return path in the enveloper as shown in the example below. This is the address where bounce mails are sent to. You may want to set this to a generic address, different than the From: header, so you can process remote bounces. This done by setting mail.smtp.from property in JavaMail. Create a java class file SendEmail, the contents of which are as follows: import java.util.Properties; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendEmail { public static void main(String[] args) throws Exception { String smtpServer = "smtp.gmail.com"; int port = 587; final String userid = "youraddress";//change accordingly final String password = "*****";//change accordingly String contentType = "text/html"; String subject = "test: bounce an email to a different address " + "from the sender"; String from = "[email protected]"; String to = "[email protected]";//some invalid address String bounceAddr = "[email protected]";//change accordingly String body = "Test: get message to bounce to a separate email address"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", smtpServer); props.put("mail.smtp.port", "587"); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.from", bounceAddr); Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userid, password); } }); MimeMessage message = new MimeMessage(mailSession); message.addFrom(InternetAddress.parse(from)); message.setRecipients(Message.RecipientType.TO, to); message.setSubject(subject); message.setContent(body, contentType); Transport transport = mailSession.getTransport(); try { System.out.println("Sending ...."); transport.connect(smtpServer, port, userid, password); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); System.out.println("Sending done ..."); } catch (Exception e) { System.err.println("Error Sending: "); e.printStackTrace(); } transport.close(); }// end function main() } Here we can see that the property mail.smtp.from is set different from the from address. Now that our class is ready, let us compile the above class. I've saved the class SendEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmail.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmail You should see the following message on the command console: Sending .... Sending done ... Print Add Notes Bookmark this page
[ { "code": null, "e": 2380, "s": 2071, "text": "A message can be bounced for several reasons. This problem is discussed in depth at rfc1211. Only a server can determine the existence of a particular mailbox or user name. When the server detects an error, it will return a message indicating the reason for the failure to the sender of the original message." }, { "code": null, "e": 2699, "s": 2380, "text": "There are many Internet standards covering Delivery Status Notifications but a large number of servers don't support these new standards, instead using ad hoc techniques for returning such failure messages. Hence it get very difficult to correlate the bounced message with the original message that caused the problem." }, { "code": null, "e": 3210, "s": 2699, "text": "JavaMail includes support for parsing Delivery Status Notifications. There are a number of techniques and heuristics for dealing with this problem. One of the techniques being Variable Envelope Return Paths. You can set the return path in the enveloper as shown in the example below. This is the address where bounce mails are sent to. You may want to set this to a generic address, different than the From: header, so you can process remote bounces. This done by setting mail.smtp.from property in JavaMail. " }, { "code": null, "e": 3284, "s": 3210, "text": "Create a java class file SendEmail, the contents of which are as follows:" }, { "code": null, "e": 5539, "s": 3284, "text": "import java.util.Properties;\n\nimport javax.mail.Message;\nimport javax.mail.PasswordAuthentication;\nimport javax.mail.Session;\nimport javax.mail.Transport;\nimport javax.mail.internet.InternetAddress;\nimport javax.mail.internet.MimeMessage;\n\npublic class SendEmail {\n public static void main(String[] args) throws Exception {\n String smtpServer = \"smtp.gmail.com\";\n int port = 587;\n final String userid = \"youraddress\";//change accordingly\n final String password = \"*****\";//change accordingly\n String contentType = \"text/html\";\n String subject = \"test: bounce an email to a different address \" +\n\t\t\t\t\"from the sender\";\n String from = \"[email protected]\";\n String to = \"[email protected]\";//some invalid address\n String bounceAddr = \"[email protected]\";//change accordingly\n String body = \"Test: get message to bounce to a separate email address\";\n\n Properties props = new Properties();\n\n props.put(\"mail.smtp.auth\", \"true\");\n props.put(\"mail.smtp.starttls.enable\", \"true\");\n props.put(\"mail.smtp.host\", smtpServer);\n props.put(\"mail.smtp.port\", \"587\");\n props.put(\"mail.transport.protocol\", \"smtp\");\n props.put(\"mail.smtp.from\", bounceAddr);\n\n Session mailSession = Session.getInstance(props,\n new javax.mail.Authenticator() {\n protected PasswordAuthentication getPasswordAuthentication() {\n return new PasswordAuthentication(userid, password);\n }\n });\n\n MimeMessage message = new MimeMessage(mailSession);\n message.addFrom(InternetAddress.parse(from));\n message.setRecipients(Message.RecipientType.TO, to);\n message.setSubject(subject);\n message.setContent(body, contentType);\n\n Transport transport = mailSession.getTransport();\n try {\n System.out.println(\"Sending ....\");\n transport.connect(smtpServer, port, userid, password);\n transport.sendMessage(message,\n message.getRecipients(Message.RecipientType.TO));\n System.out.println(\"Sending done ...\");\n } catch (Exception e) {\n System.err.println(\"Error Sending: \");\n e.printStackTrace();\n\n }\n transport.close();\n }// end function main()\n}" }, { "code": null, "e": 5628, "s": 5539, "text": "Here we can see that the property mail.smtp.from is set different from the from address." }, { "code": null, "e": 5973, "s": 5628, "text": "Now that our class is ready, let us compile the above class. I've saved the class SendEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt:" }, { "code": null, "e": 6057, "s": 5973, "text": "javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmail.java" }, { "code": null, "e": 6123, "s": 6057, "text": "Now that the class is compiled, execute the below command to run:" }, { "code": null, "e": 6201, "s": 6123, "text": "java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmail" }, { "code": null, "e": 6262, "s": 6201, "text": "You should see the following message on the command console:" }, { "code": null, "e": 6292, "s": 6262, "text": "Sending ....\nSending done ..." }, { "code": null, "e": 6299, "s": 6292, "text": " Print" }, { "code": null, "e": 6310, "s": 6299, "text": " Add Notes" } ]
Algorithms | Sorting | Question 23 - GeeksforGeeks
19 Nov, 2018 Suppose we are sorting an array of eight integers using quicksort, and we have just finished the first partitioning with the array looking like this: 2 5 1 7 9 12 11 10 Which statement is correct?(A) The pivot could be either the 7 or the 9.(B) The pivot could be the 7, but it is not the 9(C) The pivot is not the 7, but it could be the 9(D) Neither the 7 nor the 9 is the pivot.Answer: (A)Explanation: 7 and 9 both are at their correct positions (as in a sorted array). Also, all elements on left of 7 and 9 are smaller than 7 and 9 respectively and on right are greater than 7 and 9 respectively.Quiz of this Question Algorithms-Sorting-Quiz Sorting Quiz Algorithms Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Algorithms | Dynamic Programming | Question 2 Algorithms | Dynamic Programming | Question 3 Algorithms Quiz | Dynamic Programming | Question 8 Algorithms | Bit Algorithms | Question 3 Algorithms | Bit Algorithms | Question 2 Algorithms | Bit Algorithms | Question 1 Data Structures and Algorithms | Set 38 Algorithms | Divide and Conquer | Question 2 Algorithms | Divide and Conquer | Question 4 Algorithms | Dynamic Programming | Question 7
[ { "code": null, "e": 24130, "s": 24102, "text": "\n19 Nov, 2018" }, { "code": null, "e": 24280, "s": 24130, "text": "Suppose we are sorting an array of eight integers using quicksort, and we have just finished the first partitioning with the array looking like this:" }, { "code": null, "e": 24307, "s": 24280, "text": "2 5 1 7 9 12 11 10 " }, { "code": null, "e": 24759, "s": 24307, "text": "Which statement is correct?(A) The pivot could be either the 7 or the 9.(B) The pivot could be the 7, but it is not the 9(C) The pivot is not the 7, but it could be the 9(D) Neither the 7 nor the 9 is the pivot.Answer: (A)Explanation: 7 and 9 both are at their correct positions (as in a sorted array). Also, all elements on left of 7 and 9 are smaller than 7 and 9 respectively and on right are greater than 7 and 9 respectively.Quiz of this Question" }, { "code": null, "e": 24783, "s": 24759, "text": "Algorithms-Sorting-Quiz" }, { "code": null, "e": 24796, "s": 24783, "text": "Sorting Quiz" }, { "code": null, "e": 24812, "s": 24796, "text": "Algorithms Quiz" }, { "code": null, "e": 24910, "s": 24812, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24919, "s": 24910, "text": "Comments" }, { "code": null, "e": 24932, "s": 24919, "text": "Old Comments" }, { "code": null, "e": 24978, "s": 24932, "text": "Algorithms | Dynamic Programming | Question 2" }, { "code": null, "e": 25024, "s": 24978, "text": "Algorithms | Dynamic Programming | Question 3" }, { "code": null, "e": 25075, "s": 25024, "text": "Algorithms Quiz | Dynamic Programming | Question 8" }, { "code": null, "e": 25116, "s": 25075, "text": "Algorithms | Bit Algorithms | Question 3" }, { "code": null, "e": 25157, "s": 25116, "text": "Algorithms | Bit Algorithms | Question 2" }, { "code": null, "e": 25198, "s": 25157, "text": "Algorithms | Bit Algorithms | Question 1" }, { "code": null, "e": 25238, "s": 25198, "text": "Data Structures and Algorithms | Set 38" }, { "code": null, "e": 25283, "s": 25238, "text": "Algorithms | Divide and Conquer | Question 2" }, { "code": null, "e": 25328, "s": 25283, "text": "Algorithms | Divide and Conquer | Question 4" } ]
Nuclei - Fast and Customizable Vulnerability Scanner - GeeksforGeeks
28 Jul, 2021 Nuclei is a Fast and Customizable Vulnerability Scanner. Nuclei tool is Golang Language-based tool used to send requests across multiple targets based on nuclei templates leading to zero false positive or irrelevant results and provides fast scanning on various hosts. Nuclei have built-in support to automatically update the templates to their newer version with more data. Nuclei-templates projects provide a regular Updates list to ready-to-use templates regularly. Nuclei offer to scan for various protocols, including DNS, HTTP, TCP, and many more. All kinds of security checks can be performed using nuclei templates. Note: As Nuclei is a Golang language-based tool, so you need to have a Golang environment on your system. Step 1: If you have downloaded Golang in your system, verify the installation by checking the version of Golang, use the following command. go version Step 2: Get the Nuclei repository or clone the Nuclei tool from Github, use the following command. sudo GO111MODULE=on go get -v github.com/projectdiscovery/nuclei/v2/cmd/nuclei Step 3: Copy the Nuclei tool in the bin directory so we can easily use the tool without running the tool manually by golang, use the following command. sudo cp /root/go/bin/nuclei /usr/local/go/bin/ Step 4: Update the Nuclei templates, use the following command. sudo nuclei -update-templates Step 5: Check the help menu page to get a better understanding of the Nuclei tool, use the following command. nuclei -h Example 1: Running single template nuclei -u http://testphp.vulnweb.com/ -t technologies/ngix-version.yaml Example 2: Running multiple templates with speed. nuclei -u http://example.com -t cves/ -t exposures/ Example 3: Scanning for CVEs on a given list of URLs. nuclei -l target_urls.txt -t cves/ Example 4: Excluding single template. nuclei -u https://evil.com -t cves/ - evclude-templates cves/2020/ Example 5: Excluding single template. nuclei -u http://example.com -exclude-templates exposed-panels/ -exclude-templates technologies/ Example 6: Excluding templates with a single tag. nuclei -u https://facebook.com -t cves/ -etags xss Example 7: Excluding templates with multiple tags. nuclei -u geeksforgeeks.org -t cves/ -etags sqli.rce Example 8: Running blocked templates. nuclei -l target_urls.txt -include-tags iot,misc,fuzz Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n28 Jul, 2021" }, { "code": null, "e": 26275, "s": 25651, "text": "Nuclei is a Fast and Customizable Vulnerability Scanner. Nuclei tool is Golang Language-based tool used to send requests across multiple targets based on nuclei templates leading to zero false positive or irrelevant results and provides fast scanning on various hosts. Nuclei have built-in support to automatically update the templates to their newer version with more data. Nuclei-templates projects provide a regular Updates list to ready-to-use templates regularly. Nuclei offer to scan for various protocols, including DNS, HTTP, TCP, and many more. All kinds of security checks can be performed using nuclei templates." }, { "code": null, "e": 26381, "s": 26275, "text": "Note: As Nuclei is a Golang language-based tool, so you need to have a Golang environment on your system." }, { "code": null, "e": 26521, "s": 26381, "text": "Step 1: If you have downloaded Golang in your system, verify the installation by checking the version of Golang, use the following command." }, { "code": null, "e": 26532, "s": 26521, "text": "go version" }, { "code": null, "e": 26631, "s": 26532, "text": "Step 2: Get the Nuclei repository or clone the Nuclei tool from Github, use the following command." }, { "code": null, "e": 26710, "s": 26631, "text": "sudo GO111MODULE=on go get -v github.com/projectdiscovery/nuclei/v2/cmd/nuclei" }, { "code": null, "e": 26862, "s": 26710, "text": "Step 3: Copy the Nuclei tool in the bin directory so we can easily use the tool without running the tool manually by golang, use the following command." }, { "code": null, "e": 26909, "s": 26862, "text": "sudo cp /root/go/bin/nuclei /usr/local/go/bin/" }, { "code": null, "e": 26973, "s": 26909, "text": "Step 4: Update the Nuclei templates, use the following command." }, { "code": null, "e": 27003, "s": 26973, "text": "sudo nuclei -update-templates" }, { "code": null, "e": 27113, "s": 27003, "text": "Step 5: Check the help menu page to get a better understanding of the Nuclei tool, use the following command." }, { "code": null, "e": 27123, "s": 27113, "text": "nuclei -h" }, { "code": null, "e": 27158, "s": 27123, "text": "Example 1: Running single template" }, { "code": null, "e": 27230, "s": 27158, "text": "nuclei -u http://testphp.vulnweb.com/ -t technologies/ngix-version.yaml" }, { "code": null, "e": 27280, "s": 27230, "text": "Example 2: Running multiple templates with speed." }, { "code": null, "e": 27332, "s": 27280, "text": "nuclei -u http://example.com -t cves/ -t exposures/" }, { "code": null, "e": 27386, "s": 27332, "text": "Example 3: Scanning for CVEs on a given list of URLs." }, { "code": null, "e": 27421, "s": 27386, "text": "nuclei -l target_urls.txt -t cves/" }, { "code": null, "e": 27459, "s": 27421, "text": "Example 4: Excluding single template." }, { "code": null, "e": 27526, "s": 27459, "text": "nuclei -u https://evil.com -t cves/ - evclude-templates cves/2020/" }, { "code": null, "e": 27564, "s": 27526, "text": "Example 5: Excluding single template." }, { "code": null, "e": 27661, "s": 27564, "text": "nuclei -u http://example.com -exclude-templates exposed-panels/ -exclude-templates technologies/" }, { "code": null, "e": 27711, "s": 27661, "text": "Example 6: Excluding templates with a single tag." }, { "code": null, "e": 27762, "s": 27711, "text": "nuclei -u https://facebook.com -t cves/ -etags xss" }, { "code": null, "e": 27813, "s": 27762, "text": "Example 7: Excluding templates with multiple tags." }, { "code": null, "e": 27866, "s": 27813, "text": "nuclei -u geeksforgeeks.org -t cves/ -etags sqli.rce" }, { "code": null, "e": 27904, "s": 27866, "text": "Example 8: Running blocked templates." }, { "code": null, "e": 27958, "s": 27904, "text": "nuclei -l target_urls.txt -include-tags iot,misc,fuzz" }, { "code": null, "e": 27969, "s": 27958, "text": "Kali-Linux" }, { "code": null, "e": 27981, "s": 27969, "text": "Linux-Tools" }, { "code": null, "e": 27992, "s": 27981, "text": "Linux-Unix" }, { "code": null, "e": 28090, "s": 27992, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28125, "s": 28090, "text": "scp command in Linux with Examples" }, { "code": null, "e": 28159, "s": 28125, "text": "mv command in Linux with examples" }, { "code": null, "e": 28185, "s": 28159, "text": "Docker - COPY Instruction" }, { "code": null, "e": 28214, "s": 28185, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 28251, "s": 28214, "text": "chown command in Linux with Examples" }, { "code": null, "e": 28288, "s": 28251, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 28330, "s": 28288, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 28356, "s": 28330, "text": "Thread functions in C/C++" }, { "code": null, "e": 28392, "s": 28356, "text": "uniq Command in LINUX with examples" } ]
10's Complement of a decimal number - GeeksforGeeks
07 Jul, 2021 Given a decimal number N. The task is to find 10’s complement of the number N.Example: Input : 25 Output : 10's complement is : 75 Input : 456 Output : 10's complement is : 544 10’s complement of a decimal number can be found by adding 1 to the 9’s complement of that decimal number. It is just like 2s complement in binary number representation.Mathematically, 10’s complement = 9’s complement + 1 For example, let us take a decimal number 456, 9’s complement of this number will be 999-456 which will be 543. Now 10s complement will be 543+1=544.Therefore, 10’s complement = 10len – num Where, len = total number of digits in num. Below is the program to find 10’s complement of a given number: C++ Java Python3 C# PHP Javascript // C++ program to find 10's complement #include<iostream>#include<cmath> using namespace std; // Function to find 10's complementint complement(int num){ int i,len=0,temp,comp; // Calculating total digits // in num temp = num; while(1) { len++; num=num/10; if(abs(num)==0) break; } // restore num num = temp; // calculate 10's complement comp = pow(10,len) - num; return comp;} // Driver codeint main(){ cout<<complement(25)<<endl; cout<<complement(456); return 0;} // Java program to find 10's complementimport java.io.*; class GFG{// Function to find 10's complementstatic int complement(int num){ int i, len = 0, temp, comp; // Calculating total // digits in num temp = num; while(true) { len++; num = num / 10; if(Math.abs(num) == 0) break; } // restore num num = temp; // calculate 10's complement comp = (int)Math.pow(10,len) - num; return comp;} // Driver codepublic static void main (String[] args){ System.out.println(complement(25)); System.out.println(complement(456));}} // This code is contributed// by chandan_jnu. # Python3 program to find# 10's complementimport math # Function to find 10's complementdef complement(num): i = 0; len = 0; comp = 0; # Calculating total # digits in num temp = num; while(1): len += 1; num = int(num / 10); if(abs(num) == 0): break; # restore num num = temp; # calculate 10's complement comp = math.pow(10, len) - num; return int(comp); # Driver codeprint(complement(25));print(complement(456)); # This code is contributed by mits // C# program to find// 10's complementusing System; class GFG{// Function to find 10's complementstatic int complement(int num){ int len = 0, temp, comp; // Calculating total // digits in num temp = num; while(true) { len++; num = num / 10; if(Math.Abs(num) == 0) break; } // restore num num = temp; // calculate 10's complement comp = (int)Math.Pow(10, len) - num; return comp;} // Driver codepublic static void Main (){ Console.WriteLine(complement(25)); Console.WriteLine(complement(456));}} // This code is contributed// by chandan_jnu. <?php// PHP program to find 10's complement // Function to find 10's complementfunction complement($num){ $i; $len = 0; $comp; // Calculating total // digits in num $temp = $num; while(1) { $len++; $num = (int)($num / 10); if(abs($num) == 0) break; } // restore num $num = $temp; // calculate 10's complement $comp = pow(10, $len) - $num; return $comp;} // Driver codeecho complement(25) . "\n";echo complement(456); // This code is contributed by mits?> <script>// javascript program to find 10's complement // Function to find 10's complement function complement(num) { var i, len = 0, temp, comp; // Calculating total // digits in num temp = num; while (true) { len++; num = parseInt(num / 10); if (Math.abs(num) == 0) break; } // restore num num = temp; // calculate 10's complement comp = parseInt( Math.pow(10, len) - num); return comp; } // Driver code document.write(complement(25)+"<br/>"); document.write(complement(456)); // This code contributed by umadevi9616</script> 75 544 Chandan_Kumar Mithun Kumar umadevi9616 ruhelaa48 complement math Numbers school-programming Mathematical Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Sieve of Eratosthenes Program to find GCD or HCF of two numbers Program for factorial of a number Print all possible combinations of r elements in a given array of size n Program for Decimal to Binary Conversion The Knight's tour problem | Backtracking-1 Find minimum number of coins that make a given value
[ { "code": null, "e": 26173, "s": 26145, "text": "\n07 Jul, 2021" }, { "code": null, "e": 26262, "s": 26173, "text": "Given a decimal number N. The task is to find 10’s complement of the number N.Example: " }, { "code": null, "e": 26353, "s": 26262, "text": "Input : 25\nOutput : 10's complement is : 75\n\nInput : 456\nOutput : 10's complement is : 544" }, { "code": null, "e": 26542, "s": 26355, "text": "10’s complement of a decimal number can be found by adding 1 to the 9’s complement of that decimal number. It is just like 2s complement in binary number representation.Mathematically, " }, { "code": null, "e": 26581, "s": 26542, "text": "10’s complement = 9’s complement + 1 " }, { "code": null, "e": 26743, "s": 26581, "text": "For example, let us take a decimal number 456, 9’s complement of this number will be 999-456 which will be 543. Now 10s complement will be 543+1=544.Therefore, " }, { "code": null, "e": 26775, "s": 26743, "text": "10’s complement = 10len – num " }, { "code": null, "e": 26819, "s": 26775, "text": "Where, len = total number of digits in num." }, { "code": null, "e": 26887, "s": 26821, "text": "Below is the program to find 10’s complement of a given number: " }, { "code": null, "e": 26891, "s": 26887, "text": "C++" }, { "code": null, "e": 26896, "s": 26891, "text": "Java" }, { "code": null, "e": 26904, "s": 26896, "text": "Python3" }, { "code": null, "e": 26907, "s": 26904, "text": "C#" }, { "code": null, "e": 26911, "s": 26907, "text": "PHP" }, { "code": null, "e": 26922, "s": 26911, "text": "Javascript" }, { "code": "// C++ program to find 10's complement #include<iostream>#include<cmath> using namespace std; // Function to find 10's complementint complement(int num){ int i,len=0,temp,comp; // Calculating total digits // in num temp = num; while(1) { len++; num=num/10; if(abs(num)==0) break; } // restore num num = temp; // calculate 10's complement comp = pow(10,len) - num; return comp;} // Driver codeint main(){ cout<<complement(25)<<endl; cout<<complement(456); return 0;}", "e": 27502, "s": 26922, "text": null }, { "code": "// Java program to find 10's complementimport java.io.*; class GFG{// Function to find 10's complementstatic int complement(int num){ int i, len = 0, temp, comp; // Calculating total // digits in num temp = num; while(true) { len++; num = num / 10; if(Math.abs(num) == 0) break; } // restore num num = temp; // calculate 10's complement comp = (int)Math.pow(10,len) - num; return comp;} // Driver codepublic static void main (String[] args){ System.out.println(complement(25)); System.out.println(complement(456));}} // This code is contributed// by chandan_jnu.", "e": 28164, "s": 27502, "text": null }, { "code": "# Python3 program to find# 10's complementimport math # Function to find 10's complementdef complement(num): i = 0; len = 0; comp = 0; # Calculating total # digits in num temp = num; while(1): len += 1; num = int(num / 10); if(abs(num) == 0): break; # restore num num = temp; # calculate 10's complement comp = math.pow(10, len) - num; return int(comp); # Driver codeprint(complement(25));print(complement(456)); # This code is contributed by mits", "e": 28700, "s": 28164, "text": null }, { "code": "// C# program to find// 10's complementusing System; class GFG{// Function to find 10's complementstatic int complement(int num){ int len = 0, temp, comp; // Calculating total // digits in num temp = num; while(true) { len++; num = num / 10; if(Math.Abs(num) == 0) break; } // restore num num = temp; // calculate 10's complement comp = (int)Math.Pow(10, len) - num; return comp;} // Driver codepublic static void Main (){ Console.WriteLine(complement(25)); Console.WriteLine(complement(456));}} // This code is contributed// by chandan_jnu.", "e": 29341, "s": 28700, "text": null }, { "code": "<?php// PHP program to find 10's complement // Function to find 10's complementfunction complement($num){ $i; $len = 0; $comp; // Calculating total // digits in num $temp = $num; while(1) { $len++; $num = (int)($num / 10); if(abs($num) == 0) break; } // restore num $num = $temp; // calculate 10's complement $comp = pow(10, $len) - $num; return $comp;} // Driver codeecho complement(25) . \"\\n\";echo complement(456); // This code is contributed by mits?>", "e": 29890, "s": 29341, "text": null }, { "code": "<script>// javascript program to find 10's complement // Function to find 10's complement function complement(num) { var i, len = 0, temp, comp; // Calculating total // digits in num temp = num; while (true) { len++; num = parseInt(num / 10); if (Math.abs(num) == 0) break; } // restore num num = temp; // calculate 10's complement comp = parseInt( Math.pow(10, len) - num); return comp; } // Driver code document.write(complement(25)+\"<br/>\"); document.write(complement(456)); // This code contributed by umadevi9616</script>", "e": 30579, "s": 29890, "text": null }, { "code": null, "e": 30586, "s": 30579, "text": "75\n544" }, { "code": null, "e": 30602, "s": 30588, "text": "Chandan_Kumar" }, { "code": null, "e": 30615, "s": 30602, "text": "Mithun Kumar" }, { "code": null, "e": 30627, "s": 30615, "text": "umadevi9616" }, { "code": null, "e": 30637, "s": 30627, "text": "ruhelaa48" }, { "code": null, "e": 30648, "s": 30637, "text": "complement" }, { "code": null, "e": 30653, "s": 30648, "text": "math" }, { "code": null, "e": 30661, "s": 30653, "text": "Numbers" }, { "code": null, "e": 30680, "s": 30661, "text": "school-programming" }, { "code": null, "e": 30693, "s": 30680, "text": "Mathematical" }, { "code": null, "e": 30706, "s": 30693, "text": "Mathematical" }, { "code": null, "e": 30714, "s": 30706, "text": "Numbers" }, { "code": null, "e": 30812, "s": 30714, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30836, "s": 30812, "text": "Merge two sorted arrays" }, { "code": null, "e": 30879, "s": 30836, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30893, "s": 30879, "text": "Prime Numbers" }, { "code": null, "e": 30915, "s": 30893, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 30957, "s": 30915, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 30991, "s": 30957, "text": "Program for factorial of a number" }, { "code": null, "e": 31064, "s": 30991, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 31105, "s": 31064, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 31148, "s": 31105, "text": "The Knight's tour problem | Backtracking-1" } ]
Find the number of pairs such that their gcd is equals to 1 - GeeksforGeeks
18 Mar, 2022 Given an array a of size N. The task is to find the number of pairs such that gcd(a[i], a[j]) is equal to 1, where 1 ≤ i < j ≤ N. Examples: Input : a[] = {1, 2, 4, 6} Output : 3 {1, 2}, {1, 4}, {1, 6} are such pairs Input : a[] = {1, 2, 3, 4, 5, 6} Output : 11 Approach : The answer is to sum of μ(X) * C(D(X), 2) overall integer X. Where, μ(X) is Mobius function, C(N, K) is the selection of K things from N and D(X) is the number of integers in the given sequence that are divisible by X.The correctness of the solution follows from the fact that we can do an inclusion-exclusion principle solution and to show that it is, in fact, equal to our answer. That means that we will add to the answer the number of pairs that are divisible by some intermediate (in the IEP) product D if D is formed by multiplication of even number of prime numbers and subtract this number of pairs otherwise. So, we get: 1 for addition, because that is Möbius function for square-free numbers with even number of prime divisors. -1 for subtraction, that is Mobius function for square-free numbers with an odd number of prime divisors. 0 for square-free numbers. By the definition, they can’t occur in our IEP solution. Below is the implementation of the above approach : C++ Java Python3 C# Javascript // CPP program to find the number of pairs// such that gcd equals to 1#include <bits/stdc++.h>using namespace std; #define N 100050 int lpf[N], mobius[N]; // Function to calculate least// prime factor of each numbervoid least_prime_factor(){ for (int i = 2; i < N; i++) // If it is a prime number if (!lpf[i]) for (int j = i; j < N; j += i) // For all multiples which are not // visited yet. if (!lpf[j]) lpf[j] = i;} // Function to find the value of Mobius function// for all the numbers from 1 to nvoid Mobius(){ for (int i = 1; i < N; i++) { // If number is one if (i == 1) mobius[i] = 1; else { // If number has a squared prime factor if (lpf[i / lpf[i]] == lpf[i]) mobius[i] = 0; // Multiply -1 with the previous number else mobius[i] = -1 * mobius[i / lpf[i]]; } }} // Function to find the number of pairs// such that gcd equals to 1int gcd_pairs(int a[], int n){ // To store maximum number int maxi = 0; // To store frequency of each number int fre[N] = { 0 }; // Find frequency and maximum number for (int i = 0; i < n; i++) { fre[a[i]]++; maxi = max(a[i], maxi); } least_prime_factor(); Mobius(); // To store number of pairs with gcd equals to 1 int ans = 0; // Traverse through the all possible elements for (int i = 1; i <= maxi; i++) { if (!mobius[i]) continue; int temp = 0; for (int j = i; j <= maxi; j += i) temp += fre[j]; ans += temp * (temp - 1) / 2 * mobius[i]; } // Return the number of pairs return ans;} // Driver codeint main(){ int a[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(a) / sizeof(a[0]); // Function call cout << gcd_pairs(a, n); return 0;} // Java program to find the number of pairs// such that gcd equals to 1class GFG{ static int N = 100050; static int []lpf = new int[N];static int []mobius = new int[N]; // Function to calculate least// prime factor of each numberstatic void least_prime_factor(){ for (int i = 2; i < N; i++) // If it is a prime number if (lpf[i] == 0) for (int j = i; j < N; j += i) // For all multiples which are not // visited yet. if (lpf[j] == 0) lpf[j] = i;} // Function to find the value of Mobius function// for all the numbers from 1 to nstatic void Mobius(){ for (int i = 1; i < N; i++) { // If number is one if (i == 1) mobius[i] = 1; else { // If number has a squared prime factor if (lpf[i / lpf[i]] == lpf[i]) mobius[i] = 0; // Multiply -1 with the previous number else mobius[i] = -1 * mobius[i / lpf[i]]; } }} // Function to find the number of pairs// such that gcd equals to 1static int gcd_pairs(int a[], int n){ // To store maximum number int maxi = 0; // To store frequency of each number int []fre = new int[N]; // Find frequency and maximum number for (int i = 0; i < n; i++) { fre[a[i]]++; maxi = Math.max(a[i], maxi); } least_prime_factor(); Mobius(); // To store number of pairs with gcd equals to 1 int ans = 0; // Traverse through the all possible elements for (int i = 1; i <= maxi; i++) { if (mobius[i] == 0) continue; int temp = 0; for (int j = i; j <= maxi; j += i) temp += fre[j]; ans += temp * (temp - 1) / 2 * mobius[i]; } // Return the number of pairs return ans;} // Driver codepublic static void main (String[] args){ int a[] = { 1, 2, 3, 4, 5, 6 }; int n = a.length; // Function call System.out.print(gcd_pairs(a, n));}} // This code is contributed by PrinciRaj1992 # Python3 program to find the number of pairs# such that gcd equals to 1N = 100050 lpf = [0 for i in range(N)]mobius = [0 for i in range(N)] # Function to calculate least# prime factor of each numberdef least_prime_factor(): for i in range(2, N): # If it is a prime number if (lpf[i] == 0): for j in range(i, N, i): # For all multiples which are not # visited yet. if (lpf[j] == 0): lpf[j] = i # Function to find the value of Mobius function# for all the numbers from 1 to ndef Mobius(): for i in range(1, N): # If number is one if (i == 1): mobius[i] = 1 else: # If number has a squared prime factor if (lpf[ (i // lpf[i]) ] == lpf[i]): mobius[i] = 0 # Multiply -1 with the previous number else: mobius[i] = -1 * mobius[i // lpf[i]] # Function to find the number of pairs# such that gcd equals to 1def gcd_pairs(a, n): # To store maximum number maxi = 0 # To store frequency of each number fre = [0 for i in range(N)] # Find frequency and maximum number for i in range(n): fre[a[i]] += 1 maxi = max(a[i], maxi) least_prime_factor() Mobius() # To store number of pairs with gcd equals to 1 ans = 0 # Traverse through the all possible elements for i in range(1, maxi + 1): if (mobius[i] == 0): continue temp = 0 for j in range(i, maxi + 1, i): temp += fre[j] ans += temp * (temp - 1) // 2 * mobius[i] # Return the number of pairs return ans # Driver codea = [1, 2, 3, 4, 5, 6] n = len(a) # Function callprint(gcd_pairs(a, n)) # This code is contributed by Mohit Kumar // C# program to find the number of pairs// such that gcd equals to 1using System; class GFG{static int N = 100050; static int []lpf = new int[N];static int []mobius = new int[N]; // Function to calculate least// prime factor of each numberstatic void least_prime_factor(){ for (int i = 2; i < N; i++) // If it is a prime number if (lpf[i] == 0) for (int j = i; j < N; j += i) // For all multiples which are not // visited yet. if (lpf[j] == 0) lpf[j] = i;} // Function to find the value of Mobius function// for all the numbers from 1 to nstatic void Mobius(){ for (int i = 1; i < N; i++) { // If number is one if (i == 1) mobius[i] = 1; else { // If number has a squared prime factor if (lpf[i / lpf[i]] == lpf[i]) mobius[i] = 0; // Multiply -1 with the previous number else mobius[i] = -1 * mobius[i / lpf[i]]; } }} // Function to find the number of pairs// such that gcd equals to 1static int gcd_pairs(int []a, int n){ // To store maximum number int maxi = 0; // To store frequency of each number int []fre = new int[N]; // Find frequency and maximum number for (int i = 0; i < n; i++) { fre[a[i]]++; maxi = Math.Max(a[i], maxi); } least_prime_factor(); Mobius(); // To store number of pairs with gcd equals to 1 int ans = 0; // Traverse through the all possible elements for (int i = 1; i <= maxi; i++) { if (mobius[i] == 0) continue; int temp = 0; for (int j = i; j <= maxi; j += i) temp += fre[j]; ans += temp * (temp - 1) / 2 * mobius[i]; } // Return the number of pairs return ans;} // Driver codepublic static void Main (String[] args){ int []a = { 1, 2, 3, 4, 5, 6 }; int n = a.Length; // Function call Console.Write(gcd_pairs(a, n));}} // This code is contributed by Rajput-Ji <script> // Javascript program to find the number of pairs// such that gcd equals to 1 var N = 100050; var lpf = Array(N).fill(0); var mobius = Array(N).fill(0); // Function to calculate least // prime factor of each number function least_prime_factor() { for (i = 2; i < N; i++) // If it is a prime number if (lpf[i] == 0) for (j = i; j < N; j += i) // For all multiples which are not // visited yet. if (lpf[j] == 0) lpf[j] = i; } // Function to find the value of Mobius function // for all the numbers from 1 to n function Mobius() { for (i = 1; i < N; i++) { // If number is one if (i == 1) mobius[i] = 1; else { // If number has a squared prime factor if (lpf[i / lpf[i]] == lpf[i]) mobius[i] = 0; // Multiply -1 with the previous number else mobius[i] = -1 * mobius[i / lpf[i]]; } } } // Function to find the number of pairs // such that gcd equals to 1 function gcd_pairs(a , n) { // To store maximum number var maxi = 0; // To store frequency of each number var fre = Array(n+1).fill(0); // Find frequency and maximum number for (i = 0; i < n; i++) { fre[a[i]]++; maxi = Math.max(a[i], maxi); } least_prime_factor(); Mobius(); // To store number of pairs with gcd equals to 1 var ans = 0; // Traverse through the all possible elements for (i = 1; i <= maxi; i++) { if (mobius[i] == 0) continue; var temp = 0; for (j = i; j <= maxi; j += i) temp = parseInt(temp+fre[j]); ans += parseInt(temp * (temp - 1) / 2 * mobius[i]); } // Return the number of pairs return ans; } // Driver code var a = [ 1, 2, 3, 4, 5, 6 ]; var n = a.length; // Function call document.write(gcd_pairs(a, n)); // This code contributed by Rajput-Ji </script> 11 Time Complexity: O(N2) Auxiliary Space: O(N) mohit kumar 29 nidhi_biet princiraj1992 Rajput-Ji abdelrahmanyossef12 tapasrnk subhamkumarm348 GCD-LCM number-theory Arrays Mathematical Arrays number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26071, "s": 26043, "text": "\n18 Mar, 2022" }, { "code": null, "e": 26202, "s": 26071, "text": "Given an array a of size N. The task is to find the number of pairs such that gcd(a[i], a[j]) is equal to 1, where 1 ≤ i < j ≤ N. " }, { "code": null, "e": 26214, "s": 26202, "text": "Examples: " }, { "code": null, "e": 26290, "s": 26214, "text": "Input : a[] = {1, 2, 4, 6} Output : 3 {1, 2}, {1, 4}, {1, 6} are such pairs" }, { "code": null, "e": 26337, "s": 26290, "text": "Input : a[] = {1, 2, 3, 4, 5, 6} Output : 11 " }, { "code": null, "e": 26967, "s": 26337, "text": "Approach : The answer is to sum of μ(X) * C(D(X), 2) overall integer X. Where, μ(X) is Mobius function, C(N, K) is the selection of K things from N and D(X) is the number of integers in the given sequence that are divisible by X.The correctness of the solution follows from the fact that we can do an inclusion-exclusion principle solution and to show that it is, in fact, equal to our answer. That means that we will add to the answer the number of pairs that are divisible by some intermediate (in the IEP) product D if D is formed by multiplication of even number of prime numbers and subtract this number of pairs otherwise. " }, { "code": null, "e": 26980, "s": 26967, "text": "So, we get: " }, { "code": null, "e": 27089, "s": 26980, "text": "1 for addition, because that is Möbius function for square-free numbers with even number of prime divisors." }, { "code": null, "e": 27195, "s": 27089, "text": "-1 for subtraction, that is Mobius function for square-free numbers with an odd number of prime divisors." }, { "code": null, "e": 27279, "s": 27195, "text": "0 for square-free numbers. By the definition, they can’t occur in our IEP solution." }, { "code": null, "e": 27333, "s": 27279, "text": "Below is the implementation of the above approach : " }, { "code": null, "e": 27337, "s": 27333, "text": "C++" }, { "code": null, "e": 27342, "s": 27337, "text": "Java" }, { "code": null, "e": 27350, "s": 27342, "text": "Python3" }, { "code": null, "e": 27353, "s": 27350, "text": "C#" }, { "code": null, "e": 27364, "s": 27353, "text": "Javascript" }, { "code": "// CPP program to find the number of pairs// such that gcd equals to 1#include <bits/stdc++.h>using namespace std; #define N 100050 int lpf[N], mobius[N]; // Function to calculate least// prime factor of each numbervoid least_prime_factor(){ for (int i = 2; i < N; i++) // If it is a prime number if (!lpf[i]) for (int j = i; j < N; j += i) // For all multiples which are not // visited yet. if (!lpf[j]) lpf[j] = i;} // Function to find the value of Mobius function// for all the numbers from 1 to nvoid Mobius(){ for (int i = 1; i < N; i++) { // If number is one if (i == 1) mobius[i] = 1; else { // If number has a squared prime factor if (lpf[i / lpf[i]] == lpf[i]) mobius[i] = 0; // Multiply -1 with the previous number else mobius[i] = -1 * mobius[i / lpf[i]]; } }} // Function to find the number of pairs// such that gcd equals to 1int gcd_pairs(int a[], int n){ // To store maximum number int maxi = 0; // To store frequency of each number int fre[N] = { 0 }; // Find frequency and maximum number for (int i = 0; i < n; i++) { fre[a[i]]++; maxi = max(a[i], maxi); } least_prime_factor(); Mobius(); // To store number of pairs with gcd equals to 1 int ans = 0; // Traverse through the all possible elements for (int i = 1; i <= maxi; i++) { if (!mobius[i]) continue; int temp = 0; for (int j = i; j <= maxi; j += i) temp += fre[j]; ans += temp * (temp - 1) / 2 * mobius[i]; } // Return the number of pairs return ans;} // Driver codeint main(){ int a[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(a) / sizeof(a[0]); // Function call cout << gcd_pairs(a, n); return 0;}", "e": 29290, "s": 27364, "text": null }, { "code": "// Java program to find the number of pairs// such that gcd equals to 1class GFG{ static int N = 100050; static int []lpf = new int[N];static int []mobius = new int[N]; // Function to calculate least// prime factor of each numberstatic void least_prime_factor(){ for (int i = 2; i < N; i++) // If it is a prime number if (lpf[i] == 0) for (int j = i; j < N; j += i) // For all multiples which are not // visited yet. if (lpf[j] == 0) lpf[j] = i;} // Function to find the value of Mobius function// for all the numbers from 1 to nstatic void Mobius(){ for (int i = 1; i < N; i++) { // If number is one if (i == 1) mobius[i] = 1; else { // If number has a squared prime factor if (lpf[i / lpf[i]] == lpf[i]) mobius[i] = 0; // Multiply -1 with the previous number else mobius[i] = -1 * mobius[i / lpf[i]]; } }} // Function to find the number of pairs// such that gcd equals to 1static int gcd_pairs(int a[], int n){ // To store maximum number int maxi = 0; // To store frequency of each number int []fre = new int[N]; // Find frequency and maximum number for (int i = 0; i < n; i++) { fre[a[i]]++; maxi = Math.max(a[i], maxi); } least_prime_factor(); Mobius(); // To store number of pairs with gcd equals to 1 int ans = 0; // Traverse through the all possible elements for (int i = 1; i <= maxi; i++) { if (mobius[i] == 0) continue; int temp = 0; for (int j = i; j <= maxi; j += i) temp += fre[j]; ans += temp * (temp - 1) / 2 * mobius[i]; } // Return the number of pairs return ans;} // Driver codepublic static void main (String[] args){ int a[] = { 1, 2, 3, 4, 5, 6 }; int n = a.length; // Function call System.out.print(gcd_pairs(a, n));}} // This code is contributed by PrinciRaj1992", "e": 31343, "s": 29290, "text": null }, { "code": "# Python3 program to find the number of pairs# such that gcd equals to 1N = 100050 lpf = [0 for i in range(N)]mobius = [0 for i in range(N)] # Function to calculate least# prime factor of each numberdef least_prime_factor(): for i in range(2, N): # If it is a prime number if (lpf[i] == 0): for j in range(i, N, i): # For all multiples which are not # visited yet. if (lpf[j] == 0): lpf[j] = i # Function to find the value of Mobius function# for all the numbers from 1 to ndef Mobius(): for i in range(1, N): # If number is one if (i == 1): mobius[i] = 1 else: # If number has a squared prime factor if (lpf[ (i // lpf[i]) ] == lpf[i]): mobius[i] = 0 # Multiply -1 with the previous number else: mobius[i] = -1 * mobius[i // lpf[i]] # Function to find the number of pairs# such that gcd equals to 1def gcd_pairs(a, n): # To store maximum number maxi = 0 # To store frequency of each number fre = [0 for i in range(N)] # Find frequency and maximum number for i in range(n): fre[a[i]] += 1 maxi = max(a[i], maxi) least_prime_factor() Mobius() # To store number of pairs with gcd equals to 1 ans = 0 # Traverse through the all possible elements for i in range(1, maxi + 1): if (mobius[i] == 0): continue temp = 0 for j in range(i, maxi + 1, i): temp += fre[j] ans += temp * (temp - 1) // 2 * mobius[i] # Return the number of pairs return ans # Driver codea = [1, 2, 3, 4, 5, 6] n = len(a) # Function callprint(gcd_pairs(a, n)) # This code is contributed by Mohit Kumar", "e": 33134, "s": 31343, "text": null }, { "code": "// C# program to find the number of pairs// such that gcd equals to 1using System; class GFG{static int N = 100050; static int []lpf = new int[N];static int []mobius = new int[N]; // Function to calculate least// prime factor of each numberstatic void least_prime_factor(){ for (int i = 2; i < N; i++) // If it is a prime number if (lpf[i] == 0) for (int j = i; j < N; j += i) // For all multiples which are not // visited yet. if (lpf[j] == 0) lpf[j] = i;} // Function to find the value of Mobius function// for all the numbers from 1 to nstatic void Mobius(){ for (int i = 1; i < N; i++) { // If number is one if (i == 1) mobius[i] = 1; else { // If number has a squared prime factor if (lpf[i / lpf[i]] == lpf[i]) mobius[i] = 0; // Multiply -1 with the previous number else mobius[i] = -1 * mobius[i / lpf[i]]; } }} // Function to find the number of pairs// such that gcd equals to 1static int gcd_pairs(int []a, int n){ // To store maximum number int maxi = 0; // To store frequency of each number int []fre = new int[N]; // Find frequency and maximum number for (int i = 0; i < n; i++) { fre[a[i]]++; maxi = Math.Max(a[i], maxi); } least_prime_factor(); Mobius(); // To store number of pairs with gcd equals to 1 int ans = 0; // Traverse through the all possible elements for (int i = 1; i <= maxi; i++) { if (mobius[i] == 0) continue; int temp = 0; for (int j = i; j <= maxi; j += i) temp += fre[j]; ans += temp * (temp - 1) / 2 * mobius[i]; } // Return the number of pairs return ans;} // Driver codepublic static void Main (String[] args){ int []a = { 1, 2, 3, 4, 5, 6 }; int n = a.Length; // Function call Console.Write(gcd_pairs(a, n));}} // This code is contributed by Rajput-Ji", "e": 35195, "s": 33134, "text": null }, { "code": "<script> // Javascript program to find the number of pairs// such that gcd equals to 1 var N = 100050; var lpf = Array(N).fill(0); var mobius = Array(N).fill(0); // Function to calculate least // prime factor of each number function least_prime_factor() { for (i = 2; i < N; i++) // If it is a prime number if (lpf[i] == 0) for (j = i; j < N; j += i) // For all multiples which are not // visited yet. if (lpf[j] == 0) lpf[j] = i; } // Function to find the value of Mobius function // for all the numbers from 1 to n function Mobius() { for (i = 1; i < N; i++) { // If number is one if (i == 1) mobius[i] = 1; else { // If number has a squared prime factor if (lpf[i / lpf[i]] == lpf[i]) mobius[i] = 0; // Multiply -1 with the previous number else mobius[i] = -1 * mobius[i / lpf[i]]; } } } // Function to find the number of pairs // such that gcd equals to 1 function gcd_pairs(a , n) { // To store maximum number var maxi = 0; // To store frequency of each number var fre = Array(n+1).fill(0); // Find frequency and maximum number for (i = 0; i < n; i++) { fre[a[i]]++; maxi = Math.max(a[i], maxi); } least_prime_factor(); Mobius(); // To store number of pairs with gcd equals to 1 var ans = 0; // Traverse through the all possible elements for (i = 1; i <= maxi; i++) { if (mobius[i] == 0) continue; var temp = 0; for (j = i; j <= maxi; j += i) temp = parseInt(temp+fre[j]); ans += parseInt(temp * (temp - 1) / 2 * mobius[i]); } // Return the number of pairs return ans; } // Driver code var a = [ 1, 2, 3, 4, 5, 6 ]; var n = a.length; // Function call document.write(gcd_pairs(a, n)); // This code contributed by Rajput-Ji </script>", "e": 37436, "s": 35195, "text": null }, { "code": null, "e": 37439, "s": 37436, "text": "11" }, { "code": null, "e": 37464, "s": 37441, "text": "Time Complexity: O(N2)" }, { "code": null, "e": 37486, "s": 37464, "text": "Auxiliary Space: O(N)" }, { "code": null, "e": 37501, "s": 37486, "text": "mohit kumar 29" }, { "code": null, "e": 37512, "s": 37501, "text": "nidhi_biet" }, { "code": null, "e": 37526, "s": 37512, "text": "princiraj1992" }, { "code": null, "e": 37536, "s": 37526, "text": "Rajput-Ji" }, { "code": null, "e": 37556, "s": 37536, "text": "abdelrahmanyossef12" }, { "code": null, "e": 37565, "s": 37556, "text": "tapasrnk" }, { "code": null, "e": 37581, "s": 37565, "text": "subhamkumarm348" }, { "code": null, "e": 37589, "s": 37581, "text": "GCD-LCM" }, { "code": null, "e": 37603, "s": 37589, "text": "number-theory" }, { "code": null, "e": 37610, "s": 37603, "text": "Arrays" }, { "code": null, "e": 37623, "s": 37610, "text": "Mathematical" }, { "code": null, "e": 37630, "s": 37623, "text": "Arrays" }, { "code": null, "e": 37644, "s": 37630, "text": "number-theory" }, { "code": null, "e": 37657, "s": 37644, "text": "Mathematical" }, { "code": null, "e": 37755, "s": 37657, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37823, "s": 37755, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 37867, "s": 37823, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 37890, "s": 37867, "text": "Introduction to Arrays" }, { "code": null, "e": 37922, "s": 37890, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37936, "s": 37922, "text": "Linear Search" }, { "code": null, "e": 37966, "s": 37936, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 38026, "s": 37966, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 38041, "s": 38026, "text": "C++ Data Types" }, { "code": null, "e": 38084, "s": 38041, "text": "Set in C++ Standard Template Library (STL)" } ]
How to make Incremental and Decremental counter using HTML, CSS and JavaScript? - GeeksforGeeks
26 Mar, 2021 While visiting different shopping websites like Flipkart and Amazon you have seen a counter on each product, that counter is used to specify the quantity of that product. Hence, counter is very useful part for many websites. In this article, we will design a counter using HTML, CSS, and JavaScript. A sample image is provided to give you a more clear idea about the article. Step by step implementation: Step 1: First, we will design a simple button using HTML. Refer to the comments in the code. index.html <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <!-- give a suitable heading using h1 tag--> <h1>Increment and Decrement counter</h1> <div="container"> <!-- adding button and heading to show the digits --> <!--increment() and decrement() functions on button click--> <button onclick="increment()">+</button> <h2 id="counting"></h2> <button onclick="decrement()">-</button> </div> </body> </html> Step 2: Next, we will use some CSS properties to design the button and use the hover class to get the animation effect when we hover the mouse over the button. style.css /*apply css properties to body tag*/ body { position: absolute; left: 0%; text-align: center;} /*apply css properties to container class*/ .container { justify-content: center; align-items: center; display: flex; height: 100%; text-align: center;} /*apply css properties to button tag*/ button { width: 90px; height: 60px; font-size: 30px; background-color: green; color: honeydew;} /*apply hover effect to button tag*/ button:hover { background-color: greenyellow; color: grey;} /*apply css properties to h2 tag*/ h2 { color: black; margin: 0 50px; font-size: 45px;} /*apply css properties to h1 tag*/ h1 { font-size: 35px; color: green; text-align: center; padding-left: 10%;} Step 3: Now, we will add some JavaScript code to add functionality to the buttons which we have created earlier. Refer to the comments in the code for help. index.js //initialising a variable name data var data = 0; //printing default value of data that is 0 in h2 tagdocument.getElementById("counting").innerText = data; //creation of increment functionfunction increment() { data = data + 1; document.getElementById("counting").innerText = data;}//creation of decrement functionfunction decrement() { data = data - 1; document.getElementById("counting").innerText = data;} Complete Code: In this section, we will combine the above three sections to create a counter. HTML <!DOCTYPE html><html> <head> <!-- CSS code--> <style> /*apply css properties to body tag*/ body { position: absolute; left: 0%; text-align: center; } /*apply css properties to container class*/ .container { justify-content: center; align-items: center; display: flex; height: 100%; text-align: center; } /*apply css properties to button tag*/ button { width: 90px; height: 60px; font-size: 30px; background-color: green; color: honeydew; } /*apply hover effect to button tag*/ button:hover { background-color: greenyellow; color: grey; } /*apply css properties to h2 tag*/ h2 { color: black; margin: 0 50px; font-size: 45px; } /*apply css properties to h1 tag*/ h1 { font-size: 35px; color: green; text-align: center; padding-left: 10%; } </style> </head> <body> <!-- give a suitable heading using h1 tag--> <h1>Increment and Decrement counter</h1> <div ="container"> <!-- adding button and heading to show the digits --> <!-- increment() and decrement() functions on button click--> <button onclick="increment()">+</button> <h2 id="counting"></h2> <button onclick="decrement()">-</button> </div> <!-- JavaScript code--> <script> //initialising a variable name data var data = 0; //printing default value of data that is 0 in h2 tag document.getElementById("counting").innerText = data; //creation of increment function function increment() { data = data + 1; document.getElementById("counting").innerText = data; } //creation of decrement function function decrement() { data = data - 1; document.getElementById("counting").innerText = data; } </script> </body></html> CSS-Properties HTML-Tags JavaScript-Questions CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26621, "s": 26593, "text": "\n26 Mar, 2021" }, { "code": null, "e": 26921, "s": 26621, "text": "While visiting different shopping websites like Flipkart and Amazon you have seen a counter on each product, that counter is used to specify the quantity of that product. Hence, counter is very useful part for many websites. In this article, we will design a counter using HTML, CSS, and JavaScript." }, { "code": null, "e": 26997, "s": 26921, "text": "A sample image is provided to give you a more clear idea about the article." }, { "code": null, "e": 27026, "s": 26997, "text": "Step by step implementation:" }, { "code": null, "e": 27119, "s": 27026, "text": "Step 1: First, we will design a simple button using HTML. Refer to the comments in the code." }, { "code": null, "e": 27130, "s": 27119, "text": "index.html" }, { "code": "<!DOCTYPE HTML> <html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /> </head> <body> <!-- give a suitable heading using h1 tag--> <h1>Increment and Decrement counter</h1> <div=\"container\"> <!-- adding button and heading to show the digits --> <!--increment() and decrement() functions on button click--> <button onclick=\"increment()\">+</button> <h2 id=\"counting\"></h2> <button onclick=\"decrement()\">-</button> </div> </body> </html> ", "e": 27723, "s": 27130, "text": null }, { "code": null, "e": 27883, "s": 27723, "text": "Step 2: Next, we will use some CSS properties to design the button and use the hover class to get the animation effect when we hover the mouse over the button." }, { "code": null, "e": 27893, "s": 27883, "text": "style.css" }, { "code": "/*apply css properties to body tag*/ body { position: absolute; left: 0%; text-align: center;} /*apply css properties to container class*/ .container { justify-content: center; align-items: center; display: flex; height: 100%; text-align: center;} /*apply css properties to button tag*/ button { width: 90px; height: 60px; font-size: 30px; background-color: green; color: honeydew;} /*apply hover effect to button tag*/ button:hover { background-color: greenyellow; color: grey;} /*apply css properties to h2 tag*/ h2 { color: black; margin: 0 50px; font-size: 45px;} /*apply css properties to h1 tag*/ h1 { font-size: 35px; color: green; text-align: center; padding-left: 10%;}", "e": 28649, "s": 27893, "text": null }, { "code": null, "e": 28806, "s": 28649, "text": "Step 3: Now, we will add some JavaScript code to add functionality to the buttons which we have created earlier. Refer to the comments in the code for help." }, { "code": null, "e": 28815, "s": 28806, "text": "index.js" }, { "code": "//initialising a variable name data var data = 0; //printing default value of data that is 0 in h2 tagdocument.getElementById(\"counting\").innerText = data; //creation of increment functionfunction increment() { data = data + 1; document.getElementById(\"counting\").innerText = data;}//creation of decrement functionfunction decrement() { data = data - 1; document.getElementById(\"counting\").innerText = data;}", "e": 29239, "s": 28815, "text": null }, { "code": null, "e": 29333, "s": 29239, "text": "Complete Code: In this section, we will combine the above three sections to create a counter." }, { "code": null, "e": 29338, "s": 29333, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- CSS code--> <style> /*apply css properties to body tag*/ body { position: absolute; left: 0%; text-align: center; } /*apply css properties to container class*/ .container { justify-content: center; align-items: center; display: flex; height: 100%; text-align: center; } /*apply css properties to button tag*/ button { width: 90px; height: 60px; font-size: 30px; background-color: green; color: honeydew; } /*apply hover effect to button tag*/ button:hover { background-color: greenyellow; color: grey; } /*apply css properties to h2 tag*/ h2 { color: black; margin: 0 50px; font-size: 45px; } /*apply css properties to h1 tag*/ h1 { font-size: 35px; color: green; text-align: center; padding-left: 10%; } </style> </head> <body> <!-- give a suitable heading using h1 tag--> <h1>Increment and Decrement counter</h1> <div =\"container\"> <!-- adding button and heading to show the digits --> <!-- increment() and decrement() functions on button click--> <button onclick=\"increment()\">+</button> <h2 id=\"counting\"></h2> <button onclick=\"decrement()\">-</button> </div> <!-- JavaScript code--> <script> //initialising a variable name data var data = 0; //printing default value of data that is 0 in h2 tag document.getElementById(\"counting\").innerText = data; //creation of increment function function increment() { data = data + 1; document.getElementById(\"counting\").innerText = data; } //creation of decrement function function decrement() { data = data - 1; document.getElementById(\"counting\").innerText = data; } </script> </body></html>", "e": 31773, "s": 29338, "text": null }, { "code": null, "e": 31788, "s": 31773, "text": "CSS-Properties" }, { "code": null, "e": 31798, "s": 31788, "text": "HTML-Tags" }, { "code": null, "e": 31819, "s": 31798, "text": "JavaScript-Questions" }, { "code": null, "e": 31823, "s": 31819, "text": "CSS" }, { "code": null, "e": 31828, "s": 31823, "text": "HTML" }, { "code": null, "e": 31839, "s": 31828, "text": "JavaScript" }, { "code": null, "e": 31856, "s": 31839, "text": "Web Technologies" }, { "code": null, "e": 31861, "s": 31856, "text": "HTML" }, { "code": null, "e": 31959, "s": 31861, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31998, "s": 31959, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 32035, "s": 31998, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 32064, "s": 32035, "text": "Form validation using jQuery" }, { "code": null, "e": 32099, "s": 32064, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 32141, "s": 32099, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 32201, "s": 32141, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 32254, "s": 32201, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 32315, "s": 32254, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 32339, "s": 32315, "text": "REST API (Introduction)" } ]
SDN Controllers (Ryu and ODL) - GeeksforGeeks
23 Oct, 2020 Before we move deeper with the SDN Controllers, let us understand what is SDN and SDN Controller. Software-Defined Networks (SDN) :It is one of the biggest and on-going platforms in the area of Networks which makes the network flexible and agile. SDN overcomes all the demerits of Traditional Networks. The main aim of the SDN is to control the network with the help of controllers. SDN is the future of Networking. As there is a rise in the storage and servers, the SDN introduces a new concept called “Network Function Virtualization (NFV)“. SDN architecture forms three major layers namely as: Infrastructure LayerControl LayerApplication Layer Infrastructure Layer Control Layer Application Layer Let’s discuss one by one.Infrastructure Layer :Infrastructure Layer consists of Networking Devices like Switches, Routers and it is also called a Data Plane. Control Layer :Control Layer consists of Controllers which controls the in and outflow of the data packets with the help of a controller. Let us understand the different controllers in detail. Application Layer :Application Layer consists of networking applications like monitoring, traffic control, network analysis, and security. SDN Controllers :As discussed in the previous section, controllers are present in the mid-layer. They are numerous SDN Controllers, namely as: RyuOpenDay LightRyu Controller Ryu OpenDay Light Ryu Controller It is one of the SDN controller specially designed for the agility of the network and for managing the higher traffic rate. Ryu includes well-defined software components along with API. Ryu makes the developers develop a new application and manage various other networking devices. Ryu controller is written in Python. Quick start with the Ryu Controller. Run all the below commands in your Ubuntu system or in the VMWare Workstation which is pre-installed with the SDN OVA file. // Python pip install ryu To Install the Ryu from the git repository follow the following commands as follows. git clone https://github.com / faucetsdn / ryu.git cd ryu; pip install OpenDay Light (ODL) Controller :ODL is one of the most versatile and largest open-source controllers. It is helpful for automating larger area networks and it is scalable. ODL is written in Java. Compared to all other SDN Controllers, this controller is the best out of all and it is well-known for its security. Below are the commands to install the controller and run it. // For Java $wget https : // nexus.opendaylight.org/content/repositories/ opendaylight.release/org/opendaylight/integration/ opendaylight/0.12.1/ opendaylight-0.12.1.zip $unzip opendaylight - 0.12.1.zip $yum install java - 11 $export JAVA_HOME = / usr / lib / jvm / jre - 11 $cd / root / opendaylight - 0.12.1 $./ bin / karaf Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advanced Encryption Standard (AES) Introduction and IPv4 Datagram Header Intrusion Detection System (IDS) Secure Socket Layer (SSL) Cryptography and its Types Multiple Access Protocols in Computer Network Routing Information Protocol (RIP) Wireless Sensor Network (WSN) Congestion Control in Computer Networks Architecture of Internet of Things (IoT)
[ { "code": null, "e": 25755, "s": 25727, "text": "\n23 Oct, 2020" }, { "code": null, "e": 25853, "s": 25755, "text": "Before we move deeper with the SDN Controllers, let us understand what is SDN and SDN Controller." }, { "code": null, "e": 26299, "s": 25853, "text": "Software-Defined Networks (SDN) :It is one of the biggest and on-going platforms in the area of Networks which makes the network flexible and agile. SDN overcomes all the demerits of Traditional Networks. The main aim of the SDN is to control the network with the help of controllers. SDN is the future of Networking. As there is a rise in the storage and servers, the SDN introduces a new concept called “Network Function Virtualization (NFV)“." }, { "code": null, "e": 26352, "s": 26299, "text": "SDN architecture forms three major layers namely as:" }, { "code": null, "e": 26403, "s": 26352, "text": "Infrastructure LayerControl LayerApplication Layer" }, { "code": null, "e": 26424, "s": 26403, "text": "Infrastructure Layer" }, { "code": null, "e": 26438, "s": 26424, "text": "Control Layer" }, { "code": null, "e": 26456, "s": 26438, "text": "Application Layer" }, { "code": null, "e": 26614, "s": 26456, "text": "Let’s discuss one by one.Infrastructure Layer :Infrastructure Layer consists of Networking Devices like Switches, Routers and it is also called a Data Plane." }, { "code": null, "e": 26807, "s": 26614, "text": "Control Layer :Control Layer consists of Controllers which controls the in and outflow of the data packets with the help of a controller. Let us understand the different controllers in detail." }, { "code": null, "e": 26946, "s": 26807, "text": "Application Layer :Application Layer consists of networking applications like monitoring, traffic control, network analysis, and security." }, { "code": null, "e": 27089, "s": 26946, "text": "SDN Controllers :As discussed in the previous section, controllers are present in the mid-layer. They are numerous SDN Controllers, namely as:" }, { "code": null, "e": 27120, "s": 27089, "text": "RyuOpenDay LightRyu Controller" }, { "code": null, "e": 27124, "s": 27120, "text": "Ryu" }, { "code": null, "e": 27138, "s": 27124, "text": "OpenDay Light" }, { "code": null, "e": 27153, "s": 27138, "text": "Ryu Controller" }, { "code": null, "e": 27472, "s": 27153, "text": "It is one of the SDN controller specially designed for the agility of the network and for managing the higher traffic rate. Ryu includes well-defined software components along with API. Ryu makes the developers develop a new application and manage various other networking devices. Ryu controller is written in Python." }, { "code": null, "e": 27633, "s": 27472, "text": "Quick start with the Ryu Controller. Run all the below commands in your Ubuntu system or in the VMWare Workstation which is pre-installed with the SDN OVA file." }, { "code": null, "e": 27660, "s": 27633, "text": "// Python \npip install ryu" }, { "code": null, "e": 27745, "s": 27660, "text": "To Install the Ryu from the git repository follow the following commands as follows." }, { "code": null, "e": 27817, "s": 27745, "text": "git clone https://github.com / faucetsdn / ryu.git\ncd ryu; pip install\n" }, { "code": null, "e": 28130, "s": 27817, "text": "OpenDay Light (ODL) Controller :ODL is one of the most versatile and largest open-source controllers. It is helpful for automating larger area networks and it is scalable. ODL is written in Java. Compared to all other SDN Controllers, this controller is the best out of all and it is well-known for its security." }, { "code": null, "e": 28191, "s": 28130, "text": "Below are the commands to install the controller and run it." }, { "code": null, "e": 28577, "s": 28191, "text": "// For Java\n$wget https : // nexus.opendaylight.org/content/repositories/\nopendaylight.release/org/opendaylight/integration/\nopendaylight/0.12.1/\nopendaylight-0.12.1.zip\n $unzip opendaylight\n - 0.12.1.zip $yum install java\n - 11 $export JAVA_HOME\n = / usr / lib / jvm / jre - 11 $cd / root / \n opendaylight - 0.12.1 $./ bin / karaf\n" }, { "code": null, "e": 28595, "s": 28577, "text": "Computer Networks" }, { "code": null, "e": 28613, "s": 28595, "text": "Computer Networks" }, { "code": null, "e": 28711, "s": 28613, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28746, "s": 28711, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 28784, "s": 28746, "text": "Introduction and IPv4 Datagram Header" }, { "code": null, "e": 28817, "s": 28784, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 28843, "s": 28817, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 28870, "s": 28843, "text": "Cryptography and its Types" }, { "code": null, "e": 28916, "s": 28870, "text": "Multiple Access Protocols in Computer Network" }, { "code": null, "e": 28951, "s": 28916, "text": "Routing Information Protocol (RIP)" }, { "code": null, "e": 28981, "s": 28951, "text": "Wireless Sensor Network (WSN)" }, { "code": null, "e": 29021, "s": 28981, "text": "Congestion Control in Computer Networks" } ]
Hello World in Tkinter - GeeksforGeeks
17 May, 2020 Tkinter is the Python GUI framework that is build into the Python standard library. Out of all the GUI methods, tkinter is the most commonly used method as it provides the fastest and the easiest way to create the GUI application. Lets start with the ‘hello world’ tutorial. Here is the explanation for the first program in tkinter: from tkinter import *In Python3 firstly we import all the classes, functions and variables from the tkinter package. from tkinter import * In Python3 firstly we import all the classes, functions and variables from the tkinter package. root=Tk()Now we create a root widget, by calling the Tk(). This automatically creates a graphical window with the title bar, minimize, maximize and close buttons. This handle allows us to put the contents in the window and reconfigure it as necessary. root=Tk() Now we create a root widget, by calling the Tk(). This automatically creates a graphical window with the title bar, minimize, maximize and close buttons. This handle allows us to put the contents in the window and reconfigure it as necessary. a = Label(root, text="Hello, world!")Now we create a Label widget as a child to the root window. Here root is the parent of our label widget. We set the default text to “Hello, World!”Note: This gets displayed in the window. A Label widget can display either text or an icon or other image. a = Label(root, text="Hello, world!") Now we create a Label widget as a child to the root window. Here root is the parent of our label widget. We set the default text to “Hello, World!” Note: This gets displayed in the window. A Label widget can display either text or an icon or other image. a.pack()Next, we call the pack() method on this widget. This tells it to size itself to fit the given text, and make itself visible.It just tells the geometry manager to put widgets in the same row or column. It’s usually the easiest to use if you just want one or a few widgets to appear. a.pack() Next, we call the pack() method on this widget. This tells it to size itself to fit the given text, and make itself visible.It just tells the geometry manager to put widgets in the same row or column. It’s usually the easiest to use if you just want one or a few widgets to appear. root.mainloop()The application window does not appear before you enter the main loop. This method says to take all the widgets and objects we created, render them on our screen, and respond to any interactions. The program stays in the loop until we close the window. root.mainloop() The application window does not appear before you enter the main loop. This method says to take all the widgets and objects we created, render them on our screen, and respond to any interactions. The program stays in the loop until we close the window. Below is the implementation. # Python tkinter hello world program from tkinter import * root = Tk()a = Label(root, text ="Hello World")a.pack() root.mainloop() Output: Python-tkinter 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": 25610, "s": 25582, "text": "\n17 May, 2020" }, { "code": null, "e": 25841, "s": 25610, "text": "Tkinter is the Python GUI framework that is build into the Python standard library. Out of all the GUI methods, tkinter is the most commonly used method as it provides the fastest and the easiest way to create the GUI application." }, { "code": null, "e": 25943, "s": 25841, "text": "Lets start with the ‘hello world’ tutorial. Here is the explanation for the first program in tkinter:" }, { "code": null, "e": 26060, "s": 25943, "text": "from tkinter import *In Python3 firstly we import all the classes, functions and variables from the tkinter package." }, { "code": null, "e": 26082, "s": 26060, "text": "from tkinter import *" }, { "code": null, "e": 26178, "s": 26082, "text": "In Python3 firstly we import all the classes, functions and variables from the tkinter package." }, { "code": null, "e": 26430, "s": 26178, "text": "root=Tk()Now we create a root widget, by calling the Tk(). This automatically creates a graphical window with the title bar, minimize, maximize and close buttons. This handle allows us to put the contents in the window and reconfigure it as necessary." }, { "code": null, "e": 26440, "s": 26430, "text": "root=Tk()" }, { "code": null, "e": 26683, "s": 26440, "text": "Now we create a root widget, by calling the Tk(). This automatically creates a graphical window with the title bar, minimize, maximize and close buttons. This handle allows us to put the contents in the window and reconfigure it as necessary." }, { "code": null, "e": 26974, "s": 26683, "text": "a = Label(root, text=\"Hello, world!\")Now we create a Label widget as a child to the root window. Here root is the parent of our label widget. We set the default text to “Hello, World!”Note: This gets displayed in the window. A Label widget can display either text or an icon or other image." }, { "code": null, "e": 27012, "s": 26974, "text": "a = Label(root, text=\"Hello, world!\")" }, { "code": null, "e": 27160, "s": 27012, "text": "Now we create a Label widget as a child to the root window. Here root is the parent of our label widget. We set the default text to “Hello, World!”" }, { "code": null, "e": 27267, "s": 27160, "text": "Note: This gets displayed in the window. A Label widget can display either text or an icon or other image." }, { "code": null, "e": 27557, "s": 27267, "text": "a.pack()Next, we call the pack() method on this widget. This tells it to size itself to fit the given text, and make itself visible.It just tells the geometry manager to put widgets in the same row or column. It’s usually the easiest to use if you just want one or a few widgets to appear." }, { "code": null, "e": 27566, "s": 27557, "text": "a.pack()" }, { "code": null, "e": 27848, "s": 27566, "text": "Next, we call the pack() method on this widget. This tells it to size itself to fit the given text, and make itself visible.It just tells the geometry manager to put widgets in the same row or column. It’s usually the easiest to use if you just want one or a few widgets to appear." }, { "code": null, "e": 28116, "s": 27848, "text": "root.mainloop()The application window does not appear before you enter the main loop. This method says to take all the widgets and objects we created, render them on our screen, and respond to any interactions. The program stays in the loop until we close the window." }, { "code": null, "e": 28132, "s": 28116, "text": "root.mainloop()" }, { "code": null, "e": 28385, "s": 28132, "text": "The application window does not appear before you enter the main loop. This method says to take all the widgets and objects we created, render them on our screen, and respond to any interactions. The program stays in the loop until we close the window." }, { "code": null, "e": 28414, "s": 28385, "text": "Below is the implementation." }, { "code": "# Python tkinter hello world program from tkinter import * root = Tk()a = Label(root, text =\"Hello World\")a.pack() root.mainloop()", "e": 28548, "s": 28414, "text": null }, { "code": null, "e": 28556, "s": 28548, "text": "Output:" }, { "code": null, "e": 28571, "s": 28556, "text": "Python-tkinter" }, { "code": null, "e": 28578, "s": 28571, "text": "Python" }, { "code": null, "e": 28676, "s": 28578, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28694, "s": 28676, "text": "Python Dictionary" }, { "code": null, "e": 28729, "s": 28694, "text": "Read a file line by line in Python" }, { "code": null, "e": 28761, "s": 28729, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28783, "s": 28761, "text": "Enumerate() in Python" }, { "code": null, "e": 28825, "s": 28783, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28855, "s": 28825, "text": "Iterate over a list in Python" }, { "code": null, "e": 28881, "s": 28855, "text": "Python String | replace()" }, { "code": null, "e": 28910, "s": 28881, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28954, "s": 28910, "text": "Reading and Writing to text files in Python" } ]
C Library Functions - GeeksforGeeks
13 Sep, 2021 The Standard Function Library in C is a huge library of sub-libraries, each of which contains the code for several functions. In order to make use of these libraries, link each library in the broader library through the use of header files. The definitions of these functions are present in their respective header files. In order to use these functions, we have to include the header file in the program. Below are some header files with descriptions: Implementation: Let’s discuss the implementation of the basic libraries with a C program: 1. stdio.h: This library is use to use the printf() function, the header file <stdio.h> should be included in the program. Below is the C program to implement the above approach: C // C program to implement// the above approach#include <stdio.h> // Driver codeint main(){ printf("GEEKS FOR GEEKS"); return 0;} GEEKS FOR GEEKS Note: If printf() function is used without including the header file <stdio.h>, an error will be displayed. 2. math.h– To perform any operation related to mathematics, it is necessary to include math.h header file. Example 1: sqrt() Syntax- double sqrt(double x) Below is the C program to calculate the square root of any number: C // C program to implement// the above approach#include <math.h>#include <stdio.h> // Driver codeint main(){ double number, squareRoot; number = 12.5; // Computing the square root squareRoot = sqrt(number); printf("Square root of %.2lf = %.2lf", number, squareRoot); return 0;} Square root of 12.50 = 3.54 Example 2- pow(): Syntax: double pow(double x, double y) Below is the C program to calculate the power of any number: C // C program to implement// the above approach#include <math.h>#include <stdio.h> // Driver codeint main(){ double base, power, result; base = 10.0; power = 2.0; // Calculate the result result = pow(base, power); printf("%.1lf^%.1lf = %.2lf", base, power, result); return 0;} 10.0^2.0 = 100.00 Example 3- sin(): Syntax: double sin(double x) Below is the C program to calculate the sine of an argument: C // C program to implement// the above approach#include <math.h>#include <stdio.h> // Driver codeint main(){ double x; double result; x = 2.3; result = sin(x); printf("sin(%.2lf) = %.2lf\n", x, result); x = -2.3; result = sin(x); printf("sin(%.2lf) = %.2lf\n", x, result); x = 0; result = sin(x); printf("sin(%.2lf) = %.2lf\n", x, result); return 0;} sin(2.30) = 0.75 sin(-2.30) = -0.75 sin(0.00) = 0.00 Example 4- cos(): Syntax: double cos(double x); Below is the C program to calculate the cosine of an argument: C // C program to implement// the above approach#include <math.h>#include <stdio.h>#define PI 3.141592654 // Driver codeint main(){ double arg = 30, result; // Converting to radian arg = (arg * PI) / 180; result = cos(arg); printf("cos of %.2lf radian = %.2lf", arg, result); return 0;} cos of 0.52 radian = 0.87 Example 5- tan(): Syntax: double tan(double x); Below is the C program to calculate the tangent of the argument: C // C program to implement// the above approach#include <math.h>#include <stdio.h> // Driver codeint main(){ double x; double result; x = 2.3; result = tan(x); printf("tan(%.2lf) = %.2lf\n", x, result); x = -2.3; result = tan(x); printf("tan(%.2lf) = %.2lf\n", x, result); return 0;} tan(2.30) = -1.12 tan(-2.30) = 1.12 Example 6- log(): Syntax- double log( double arg ); Below is the C program to calculate the natural logarithm of an argument- C // C program to implement// the above approach#include <math.h>#include <stdio.h> // Driver codeint main(){ double num = 5.6, result; result = log(num); printf("log(%.1f) = %.2f", num, result); return 0;} log(5.6) = 1.72 3. float.h: The float.h header file of the C Standard Library contains a set of various platform-dependent constants related to floating-point values. Below is the C program to implement the above approach- C // C program to implement// the above approach#include <float.h>#include <stdio.h> // Driver codeint main(){ printf("Maximum value of float = %.10e\n", FLT_MAX); printf("Minimum value of float = %.10e\n", FLT_MIN);} Maximum value of float = 3.4028234664e+38 Minimum value of float = 1.1754943508e-38 4. limits.h: The limits.h header determines various properties of the various variable types. The macros defined in this header limits the values of various variable types like char, int, and long. Below is the C program to implement the above approach- C // C program to implement// the above approach#include <limits.h>#include <stdio.h> // Driver codeint main(){ printf("Number of bits in a byte %d\n", CHAR_BIT); printf("Minimum value of SIGNED CHAR = %d\n", SCHAR_MIN); printf("Maximum value of SIGNED CHAR = %d\n", SCHAR_MAX); printf("Maximum value of UNSIGNED CHAR = %d\n", UCHAR_MAX); printf("Minimum value of SHORT INT = %d\n", SHRT_MIN); printf("Maximum value of SHORT INT = %d\n", SHRT_MAX); printf("Minimum value of INT = %d\n", INT_MIN); printf("Maximum value of INT = %d\n", INT_MAX); printf("Minimum value of CHAR = %d\n", CHAR_MIN); printf("Maximum value of CHAR = %d\n", CHAR_MAX); printf("Minimum value of LONG = %ld\n", LONG_MIN); printf("Maximum value of LONG = %ld\n", LONG_MAX); return (0);} Number of bits in a byte 8 Minimum value of SIGNED CHAR = -128 Maximum value of SIGNED CHAR = 127 Maximum value of UNSIGNED CHAR = 255 Minimum value of SHORT INT = -32768 Maximum value of SHORT INT = 32767 Minimum value of INT = -2147483648 Maximum value of INT = 2147483647 Minimum value of CHAR = -128 Maximum value of CHAR = 127 Minimum value of LONG = -9223372036854775808 Maximum value of LONG = 9223372036854775807 5. time.h: This header file defines the date and time functions. Below is the C program to implement time() and localtime() functions- C // C program to implement// the above approach#include <stdio.h>#include <time.h>#define SIZE 256 // Driver codeint main(void){ char buffer[SIZE]; time_t curtime; struct tm* loctime; // Get the current time. curtime = time(NULL); // Convert it to local time // representation. loctime = localtime(&curtime); // Print out the date and time // in the standard format. fputs(asctime(loctime), stdout); // Print it out strftime(buffer, SIZE, "Today is %A, %B %d.\n", loctime); fputs(buffer, stdout); strftime(buffer, SIZE, "The time is %I:%M %p.\n", loctime); fputs(buffer, stdout); return 0;} Sun May 30 17:27:47 2021 Today is Sunday, May 30. The time is 05:27 PM. 6. string.h: For using string functions, it is necessary to include string.h header file in the program. Example 1: strcat(): In C programming, the strcat() functions are used to concatenate(join) two strings. This function concatenates the destination string and the source string, and the result is stored in the destination string. Syntax- char *strcat(char *destination, const char *source) Below is the C program to implement strcat(): C // C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ char str1[100] = "Geeks ", str2[100] = " For Geeks"; // Concatenates str1 and str2 strcat(str1, str2); // Resultant string is stored // in str1 puts(str1); return 0;} Geeks For Geeks Example 2- strcmp(): It compares two strings. If the return value is 0 then the strings are equal or if the return value is non-zero then the strings are not equal. Syntax: int strcmp (const char* str1, const char* str2); Below is the C program to implement strcmp(): C // C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ char str1[] = "Geeks", str2[] = "gEeks", str3[] = "Geeks"; int result; // Comparing strings str1 // and str2 result = strcmp(str1, str2); printf("strcmp(str1, str2) = %d\n", result); // Comparing strings str1 and str3 result = strcmp(str1, str3); printf("strcmp(str1, str3) = %d\n", result); return 0;} strcmp(str1, str2) = -32 strcmp(str1, str3) = 0 Example 3 – strcpy(): The strcpy() function copies the string pointed by the source to the destination. Syntax: char* strcpy(char* destination, const char* source); Below is the C program to implement the strcpy(): C // C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ char str1[20] = "Geeks For Geeks"; char str2[20]; // Copying str1 to str2 strcpy(str2, str1); puts(str2); return 0;} Geeks For Geeks Example 4 – strlen(): This function calculates the length of the given string. Syntax: int strlen(char a[]); Below is the C program to implement strlen(): C // C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ char a[20] = "Program"; char b[20] = { "Geeks for Geeks" }; printf("Length of string a = %zu \n", strlen(a)); printf("Length of string b = %zu \n", strlen(b)); return 0;} Length of string a = 7 Length of string b = 15 7. complex.h: Functions in this header file are used to perform various operations on complex numbers. Complex numbers are the ones with the real and imaginary parts. Below is the C program to implement conjugate of a complex number- C // C program to implement// the above approach#include <complex.h>#include <stdio.h> // Driver codeint main(void){ double real = 1.3, imag = 4.9; double complex z = CMPLX(real, imag); double complex conj_f = conjf(z); printf("z = %.1f% + .1fi\n", creal(conj_f), cimag(conj_f));} Output: z = 1.3 - 4.9i 8. assert.h: Assertions are statements used to test assumptions made by programmers. For example, we may use an assertion to check if the pointer returned by malloc() is NULL or not. Syntax- void assert(int expression); C++ // C program to implement// the above approach#include <assert.h>#include <stdio.h> // Driver codeint main(){ int x = 7; // Some big code in between // and let's say x is accidentally // changed to 9 x = 9; // Programmer assumes x to be 7 // in rest of the code assert(x == 7); // Rest of the code return 0;} Output Assertion failed: x==7, file test.cpp, line 13 This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. anikakapoor C Basics C-Functions C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses Basics of File Handling in C
[ { "code": null, "e": 25478, "s": 25450, "text": "\n13 Sep, 2021" }, { "code": null, "e": 25931, "s": 25478, "text": "The Standard Function Library in C is a huge library of sub-libraries, each of which contains the code for several functions. In order to make use of these libraries, link each library in the broader library through the use of header files. The definitions of these functions are present in their respective header files. In order to use these functions, we have to include the header file in the program. Below are some header files with descriptions:" }, { "code": null, "e": 26021, "s": 25931, "text": "Implementation: Let’s discuss the implementation of the basic libraries with a C program:" }, { "code": null, "e": 26200, "s": 26021, "text": "1. stdio.h: This library is use to use the printf() function, the header file <stdio.h> should be included in the program. Below is the C program to implement the above approach:" }, { "code": null, "e": 26202, "s": 26200, "text": "C" }, { "code": "// C program to implement// the above approach#include <stdio.h> // Driver codeint main(){ printf(\"GEEKS FOR GEEKS\"); return 0;}", "e": 26337, "s": 26202, "text": null }, { "code": null, "e": 26353, "s": 26337, "text": "GEEKS FOR GEEKS" }, { "code": null, "e": 26461, "s": 26353, "text": "Note: If printf() function is used without including the header file <stdio.h>, an error will be displayed." }, { "code": null, "e": 26569, "s": 26461, "text": "2. math.h– To perform any operation related to mathematics, it is necessary to include math.h header file. " }, { "code": null, "e": 26587, "s": 26569, "text": "Example 1: sqrt()" }, { "code": null, "e": 26595, "s": 26587, "text": "Syntax-" }, { "code": null, "e": 26617, "s": 26595, "text": "double sqrt(double x)" }, { "code": null, "e": 26684, "s": 26617, "text": "Below is the C program to calculate the square root of any number:" }, { "code": null, "e": 26686, "s": 26684, "text": "C" }, { "code": "// C program to implement// the above approach#include <math.h>#include <stdio.h> // Driver codeint main(){ double number, squareRoot; number = 12.5; // Computing the square root squareRoot = sqrt(number); printf(\"Square root of %.2lf = %.2lf\", number, squareRoot); return 0;}", "e": 26995, "s": 26686, "text": null }, { "code": null, "e": 27024, "s": 26995, "text": "Square root of 12.50 = 3.54" }, { "code": null, "e": 27042, "s": 27024, "text": "Example 2- pow():" }, { "code": null, "e": 27050, "s": 27042, "text": "Syntax:" }, { "code": null, "e": 27081, "s": 27050, "text": "double pow(double x, double y)" }, { "code": null, "e": 27142, "s": 27081, "text": "Below is the C program to calculate the power of any number:" }, { "code": null, "e": 27144, "s": 27142, "text": "C" }, { "code": "// C program to implement// the above approach#include <math.h>#include <stdio.h> // Driver codeint main(){ double base, power, result; base = 10.0; power = 2.0; // Calculate the result result = pow(base, power); printf(\"%.1lf^%.1lf = %.2lf\", base, power, result); return 0;}", "e": 27452, "s": 27144, "text": null }, { "code": null, "e": 27470, "s": 27452, "text": "10.0^2.0 = 100.00" }, { "code": null, "e": 27488, "s": 27470, "text": "Example 3- sin():" }, { "code": null, "e": 27496, "s": 27488, "text": "Syntax:" }, { "code": null, "e": 27517, "s": 27496, "text": "double sin(double x)" }, { "code": null, "e": 27578, "s": 27517, "text": "Below is the C program to calculate the sine of an argument:" }, { "code": null, "e": 27580, "s": 27578, "text": "C" }, { "code": "// C program to implement// the above approach#include <math.h>#include <stdio.h> // Driver codeint main(){ double x; double result; x = 2.3; result = sin(x); printf(\"sin(%.2lf) = %.2lf\\n\", x, result); x = -2.3; result = sin(x); printf(\"sin(%.2lf) = %.2lf\\n\", x, result); x = 0; result = sin(x); printf(\"sin(%.2lf) = %.2lf\\n\", x, result); return 0;}", "e": 27996, "s": 27580, "text": null }, { "code": null, "e": 28049, "s": 27996, "text": "sin(2.30) = 0.75\nsin(-2.30) = -0.75\nsin(0.00) = 0.00" }, { "code": null, "e": 28067, "s": 28049, "text": "Example 4- cos():" }, { "code": null, "e": 28075, "s": 28067, "text": "Syntax:" }, { "code": null, "e": 28097, "s": 28075, "text": "double cos(double x);" }, { "code": null, "e": 28161, "s": 28097, "text": "Below is the C program to calculate the cosine of an argument: " }, { "code": null, "e": 28163, "s": 28161, "text": "C" }, { "code": "// C program to implement// the above approach#include <math.h>#include <stdio.h>#define PI 3.141592654 // Driver codeint main(){ double arg = 30, result; // Converting to radian arg = (arg * PI) / 180; result = cos(arg); printf(\"cos of %.2lf radian = %.2lf\", arg, result); return 0;}", "e": 28478, "s": 28163, "text": null }, { "code": null, "e": 28504, "s": 28478, "text": "cos of 0.52 radian = 0.87" }, { "code": null, "e": 28522, "s": 28504, "text": "Example 5- tan():" }, { "code": null, "e": 28530, "s": 28522, "text": "Syntax:" }, { "code": null, "e": 28552, "s": 28530, "text": "double tan(double x);" }, { "code": null, "e": 28617, "s": 28552, "text": "Below is the C program to calculate the tangent of the argument:" }, { "code": null, "e": 28619, "s": 28617, "text": "C" }, { "code": "// C program to implement// the above approach#include <math.h>#include <stdio.h> // Driver codeint main(){ double x; double result; x = 2.3; result = tan(x); printf(\"tan(%.2lf) = %.2lf\\n\", x, result); x = -2.3; result = tan(x); printf(\"tan(%.2lf) = %.2lf\\n\", x, result); return 0;}", "e": 28949, "s": 28619, "text": null }, { "code": null, "e": 28985, "s": 28949, "text": "tan(2.30) = -1.12\ntan(-2.30) = 1.12" }, { "code": null, "e": 29003, "s": 28985, "text": "Example 6- log():" }, { "code": null, "e": 29012, "s": 29003, "text": "Syntax- " }, { "code": null, "e": 29038, "s": 29012, "text": "double log( double arg );" }, { "code": null, "e": 29112, "s": 29038, "text": "Below is the C program to calculate the natural logarithm of an argument-" }, { "code": null, "e": 29114, "s": 29112, "text": "C" }, { "code": "// C program to implement// the above approach#include <math.h>#include <stdio.h> // Driver codeint main(){ double num = 5.6, result; result = log(num); printf(\"log(%.1f) = %.2f\", num, result); return 0;}", "e": 29341, "s": 29114, "text": null }, { "code": null, "e": 29357, "s": 29341, "text": "log(5.6) = 1.72" }, { "code": null, "e": 29564, "s": 29357, "text": "3. float.h: The float.h header file of the C Standard Library contains a set of various platform-dependent constants related to floating-point values. Below is the C program to implement the above approach-" }, { "code": null, "e": 29566, "s": 29564, "text": "C" }, { "code": "// C program to implement// the above approach#include <float.h>#include <stdio.h> // Driver codeint main(){ printf(\"Maximum value of float = %.10e\\n\", FLT_MAX); printf(\"Minimum value of float = %.10e\\n\", FLT_MIN);}", "e": 29808, "s": 29566, "text": null }, { "code": null, "e": 29892, "s": 29808, "text": "Maximum value of float = 3.4028234664e+38\nMinimum value of float = 1.1754943508e-38" }, { "code": null, "e": 30146, "s": 29892, "text": "4. limits.h: The limits.h header determines various properties of the various variable types. The macros defined in this header limits the values of various variable types like char, int, and long. Below is the C program to implement the above approach-" }, { "code": null, "e": 30148, "s": 30146, "text": "C" }, { "code": "// C program to implement// the above approach#include <limits.h>#include <stdio.h> // Driver codeint main(){ printf(\"Number of bits in a byte %d\\n\", CHAR_BIT); printf(\"Minimum value of SIGNED CHAR = %d\\n\", SCHAR_MIN); printf(\"Maximum value of SIGNED CHAR = %d\\n\", SCHAR_MAX); printf(\"Maximum value of UNSIGNED CHAR = %d\\n\", UCHAR_MAX); printf(\"Minimum value of SHORT INT = %d\\n\", SHRT_MIN); printf(\"Maximum value of SHORT INT = %d\\n\", SHRT_MAX); printf(\"Minimum value of INT = %d\\n\", INT_MIN); printf(\"Maximum value of INT = %d\\n\", INT_MAX); printf(\"Minimum value of CHAR = %d\\n\", CHAR_MIN); printf(\"Maximum value of CHAR = %d\\n\", CHAR_MAX); printf(\"Minimum value of LONG = %ld\\n\", LONG_MIN); printf(\"Maximum value of LONG = %ld\\n\", LONG_MAX); return (0);}", "e": 31065, "s": 30148, "text": null }, { "code": null, "e": 31486, "s": 31065, "text": "Number of bits in a byte 8\nMinimum value of SIGNED CHAR = -128\nMaximum value of SIGNED CHAR = 127\nMaximum value of UNSIGNED CHAR = 255\nMinimum value of SHORT INT = -32768\nMaximum value of SHORT INT = 32767\nMinimum value of INT = -2147483648\nMaximum value of INT = 2147483647\nMinimum value of CHAR = -128\nMaximum value of CHAR = 127\nMinimum value of LONG = -9223372036854775808\nMaximum value of LONG = 9223372036854775807" }, { "code": null, "e": 31621, "s": 31486, "text": "5. time.h: This header file defines the date and time functions. Below is the C program to implement time() and localtime() functions-" }, { "code": null, "e": 31623, "s": 31621, "text": "C" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <time.h>#define SIZE 256 // Driver codeint main(void){ char buffer[SIZE]; time_t curtime; struct tm* loctime; // Get the current time. curtime = time(NULL); // Convert it to local time // representation. loctime = localtime(&curtime); // Print out the date and time // in the standard format. fputs(asctime(loctime), stdout); // Print it out strftime(buffer, SIZE, \"Today is %A, %B %d.\\n\", loctime); fputs(buffer, stdout); strftime(buffer, SIZE, \"The time is %I:%M %p.\\n\", loctime); fputs(buffer, stdout); return 0;}", "e": 32317, "s": 31623, "text": null }, { "code": null, "e": 32389, "s": 32317, "text": "Sun May 30 17:27:47 2021\nToday is Sunday, May 30.\nThe time is 05:27 PM." }, { "code": null, "e": 32494, "s": 32389, "text": "6. string.h: For using string functions, it is necessary to include string.h header file in the program." }, { "code": null, "e": 32724, "s": 32494, "text": "Example 1: strcat(): In C programming, the strcat() functions are used to concatenate(join) two strings. This function concatenates the destination string and the source string, and the result is stored in the destination string." }, { "code": null, "e": 32733, "s": 32724, "text": "Syntax- " }, { "code": null, "e": 32785, "s": 32733, "text": "char *strcat(char *destination, const char *source)" }, { "code": null, "e": 32831, "s": 32785, "text": "Below is the C program to implement strcat():" }, { "code": null, "e": 32833, "s": 32831, "text": "C" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ char str1[100] = \"Geeks \", str2[100] = \" For Geeks\"; // Concatenates str1 and str2 strcat(str1, str2); // Resultant string is stored // in str1 puts(str1); return 0;}", "e": 33142, "s": 32833, "text": null }, { "code": null, "e": 33159, "s": 33142, "text": "Geeks For Geeks" }, { "code": null, "e": 33325, "s": 33159, "text": "Example 2- strcmp(): It compares two strings. If the return value is 0 then the strings are equal or if the return value is non-zero then the strings are not equal." }, { "code": null, "e": 33333, "s": 33325, "text": "Syntax:" }, { "code": null, "e": 33382, "s": 33333, "text": "int strcmp (const char* str1, const char* str2);" }, { "code": null, "e": 33429, "s": 33382, "text": " Below is the C program to implement strcmp():" }, { "code": null, "e": 33431, "s": 33429, "text": "C" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ char str1[] = \"Geeks\", str2[] = \"gEeks\", str3[] = \"Geeks\"; int result; // Comparing strings str1 // and str2 result = strcmp(str1, str2); printf(\"strcmp(str1, str2) = %d\\n\", result); // Comparing strings str1 and str3 result = strcmp(str1, str3); printf(\"strcmp(str1, str3) = %d\\n\", result); return 0;}", "e": 33914, "s": 33431, "text": null }, { "code": null, "e": 33962, "s": 33914, "text": "strcmp(str1, str2) = -32\nstrcmp(str1, str3) = 0" }, { "code": null, "e": 34066, "s": 33962, "text": "Example 3 – strcpy(): The strcpy() function copies the string pointed by the source to the destination." }, { "code": null, "e": 34074, "s": 34066, "text": "Syntax:" }, { "code": null, "e": 34127, "s": 34074, "text": "char* strcpy(char* destination, const char* source);" }, { "code": null, "e": 34177, "s": 34127, "text": "Below is the C program to implement the strcpy():" }, { "code": null, "e": 34179, "s": 34177, "text": "C" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ char str1[20] = \"Geeks For Geeks\"; char str2[20]; // Copying str1 to str2 strcpy(str2, str1); puts(str2); return 0;}", "e": 34426, "s": 34179, "text": null }, { "code": null, "e": 34442, "s": 34426, "text": "Geeks For Geeks" }, { "code": null, "e": 34521, "s": 34442, "text": "Example 4 – strlen(): This function calculates the length of the given string." }, { "code": null, "e": 34529, "s": 34521, "text": "Syntax:" }, { "code": null, "e": 34551, "s": 34529, "text": "int strlen(char a[]);" }, { "code": null, "e": 34598, "s": 34551, "text": " Below is the C program to implement strlen():" }, { "code": null, "e": 34600, "s": 34598, "text": "C" }, { "code": "// C program to implement// the above approach#include <stdio.h>#include <string.h> // Driver codeint main(){ char a[20] = \"Program\"; char b[20] = { \"Geeks for Geeks\" }; printf(\"Length of string a = %zu \\n\", strlen(a)); printf(\"Length of string b = %zu \\n\", strlen(b)); return 0;}", "e": 34916, "s": 34600, "text": null }, { "code": null, "e": 34965, "s": 34916, "text": "Length of string a = 7 \nLength of string b = 15 " }, { "code": null, "e": 35132, "s": 34965, "text": "7. complex.h: Functions in this header file are used to perform various operations on complex numbers. Complex numbers are the ones with the real and imaginary parts." }, { "code": null, "e": 35200, "s": 35132, "text": "Below is the C program to implement conjugate of a complex number- " }, { "code": null, "e": 35202, "s": 35200, "text": "C" }, { "code": "// C program to implement// the above approach#include <complex.h>#include <stdio.h> // Driver codeint main(void){ double real = 1.3, imag = 4.9; double complex z = CMPLX(real, imag); double complex conj_f = conjf(z); printf(\"z = %.1f% + .1fi\\n\", creal(conj_f), cimag(conj_f));}", "e": 35551, "s": 35202, "text": null }, { "code": null, "e": 35559, "s": 35551, "text": "Output:" }, { "code": null, "e": 35574, "s": 35559, "text": "z = 1.3 - 4.9i" }, { "code": null, "e": 35757, "s": 35574, "text": "8. assert.h: Assertions are statements used to test assumptions made by programmers. For example, we may use an assertion to check if the pointer returned by malloc() is NULL or not." }, { "code": null, "e": 35765, "s": 35757, "text": "Syntax-" }, { "code": null, "e": 35795, "s": 35765, "text": "void assert(int expression); " }, { "code": null, "e": 35799, "s": 35795, "text": "C++" }, { "code": "// C program to implement// the above approach#include <assert.h>#include <stdio.h> // Driver codeint main(){ int x = 7; // Some big code in between // and let's say x is accidentally // changed to 9 x = 9; // Programmer assumes x to be 7 // in rest of the code assert(x == 7); // Rest of the code return 0;}", "e": 36142, "s": 35799, "text": null }, { "code": null, "e": 36149, "s": 36142, "text": "Output" }, { "code": null, "e": 36344, "s": 36149, "text": "Assertion failed: x==7, file test.cpp, line 13 \nThis application has requested the Runtime to terminate it in an unusual \nway. Please contact the application's support team for more information." }, { "code": null, "e": 36356, "s": 36344, "text": "anikakapoor" }, { "code": null, "e": 36365, "s": 36356, "text": "C Basics" }, { "code": null, "e": 36377, "s": 36365, "text": "C-Functions" }, { "code": null, "e": 36388, "s": 36377, "text": "C Language" }, { "code": null, "e": 36399, "s": 36388, "text": "C Programs" }, { "code": null, "e": 36497, "s": 36399, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36535, "s": 36497, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 36561, "s": 36535, "text": "Exception Handling in C++" }, { "code": null, "e": 36581, "s": 36561, "text": "Multithreading in C" }, { "code": null, "e": 36603, "s": 36581, "text": "'this' pointer in C++" }, { "code": null, "e": 36644, "s": 36603, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 36657, "s": 36644, "text": "Strings in C" }, { "code": null, "e": 36698, "s": 36657, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 36739, "s": 36698, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 36774, "s": 36739, "text": "Header files in C/C++ and its uses" } ]
Fabric.js Image scaleX Property - GeeksforGeeks
29 Jan, 2021 Fabric.js is a JavaScript library that is used to work with canvas. The canvas Image is one of the class of fabric.js that is used to create Image instances. The Image in Fabric.js is movable and can be stretched according to requirement. In this article, we will be using the scaleX property to set the horizontal scale of the canvas Image. Approach: First import the Fabric.js library. After importing the library, create a canvas block in the body tag which will contain the Image. After this, initialize an instance of Canvas and Image class provided by Fabric.js, use the scaleX property to set the default horizontal scale of the Image, and render this Image on the Canvas. Syntax: fabric.Image(image, { scaleX : number }); Parameters: This function accepts a single parameter as mentioned above and described below: scaleX: It specifies the default horizontal scale. Example: This example uses Fabric.js to set the scaleX property of the canvas Image as shown in the below example: HTML <html> <head> <!-- Adding the FabricJS library --> <script src= "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"> </script> </head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <b> Fabric.js | Image scaleX Property </b> <canvas id="canvas" width="400" height="300" style="border:2px solid #000000"> </canvas> <img src= "https://media.geeksforgeeks.org/wp-content/uploads/20200327230544/g4gicon.png" width="100" height="100" id="my-image" style="display: none;"> <br> <script> // Creating the instance of canvas object var canvas = new fabric.Canvas("canvas"); // Getting the Image var img = document.getElementById('my-image'); // Creating the Image instance var geeks = new fabric.Image(img, { scaleX : 2.3 }); canvas.add(geeks); canvas.centerObject(geeks); </script> </body> </html> Output: Fabric.js HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 26139, "s": 26111, "text": "\n29 Jan, 2021" }, { "code": null, "e": 26481, "s": 26139, "text": "Fabric.js is a JavaScript library that is used to work with canvas. The canvas Image is one of the class of fabric.js that is used to create Image instances. The Image in Fabric.js is movable and can be stretched according to requirement. In this article, we will be using the scaleX property to set the horizontal scale of the canvas Image." }, { "code": null, "e": 26819, "s": 26481, "text": "Approach: First import the Fabric.js library. After importing the library, create a canvas block in the body tag which will contain the Image. After this, initialize an instance of Canvas and Image class provided by Fabric.js, use the scaleX property to set the default horizontal scale of the Image, and render this Image on the Canvas." }, { "code": null, "e": 26827, "s": 26819, "text": "Syntax:" }, { "code": null, "e": 26871, "s": 26827, "text": "fabric.Image(image, {\n scaleX : number\n});" }, { "code": null, "e": 26964, "s": 26871, "text": "Parameters: This function accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 27015, "s": 26964, "text": "scaleX: It specifies the default horizontal scale." }, { "code": null, "e": 27130, "s": 27015, "text": "Example: This example uses Fabric.js to set the scaleX property of the canvas Image as shown in the below example:" }, { "code": null, "e": 27135, "s": 27130, "text": "HTML" }, { "code": "<html> <head> <!-- Adding the FabricJS library --> <script src= \"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js\"> </script> </head> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> Fabric.js | Image scaleX Property </b> <canvas id=\"canvas\" width=\"400\" height=\"300\" style=\"border:2px solid #000000\"> </canvas> <img src= \"https://media.geeksforgeeks.org/wp-content/uploads/20200327230544/g4gicon.png\" width=\"100\" height=\"100\" id=\"my-image\" style=\"display: none;\"> <br> <script> // Creating the instance of canvas object var canvas = new fabric.Canvas(\"canvas\"); // Getting the Image var img = document.getElementById('my-image'); // Creating the Image instance var geeks = new fabric.Image(img, { scaleX : 2.3 }); canvas.add(geeks); canvas.centerObject(geeks); </script> </body> </html>", "e": 28131, "s": 27135, "text": null }, { "code": null, "e": 28139, "s": 28131, "text": "Output:" }, { "code": null, "e": 28149, "s": 28139, "text": "Fabric.js" }, { "code": null, "e": 28154, "s": 28149, "text": "HTML" }, { "code": null, "e": 28165, "s": 28154, "text": "JavaScript" }, { "code": null, "e": 28182, "s": 28165, "text": "Web Technologies" }, { "code": null, "e": 28187, "s": 28182, "text": "HTML" }, { "code": null, "e": 28285, "s": 28187, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28309, "s": 28285, "text": "REST API (Introduction)" }, { "code": null, "e": 28350, "s": 28309, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28387, "s": 28350, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28416, "s": 28387, "text": "Form validation using jQuery" }, { "code": null, "e": 28436, "s": 28416, "text": "Angular File Upload" }, { "code": null, "e": 28476, "s": 28436, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28521, "s": 28476, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28582, "s": 28521, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28654, "s": 28582, "text": "Differences between Functional Components and Class Components in React" } ]
PyQt5 - Create a User form to get information - GeeksforGeeks
03 Jan, 2022 In this article we will see how we can create a user form in PyQt5. A user form is basically a dialog box that makes a user data entry more controllable and easier to use for the user. Sometimes while creating a large user interface application there is need of creating user form in order to get essential information. Implementation steps : 1. Create a window class that inherits QDialog2. Add window title and set its geometry3. Create a QGropBox object4. Create line edit to get the name, spin box to get the age and combo box to select the degree5. Create a createForm method that will create a form6. Inside the create form method, create a form layout and add rows7. Each row should be has a label and the input method example name label and line edit for input, similarly label for degree and age and combo box and spin box for input.8. Create a QDialogButtonBox for ok and cancel state9. Add action to the button for acceptance and for rejection10. If ok button is pressed just print all the information and if the cancel button is pressed window will get closed Below is the implementation Python3 # importing librariesfrom PyQt5.QtWidgets import * import sys # creating a class# that inherits the QDialog classclass Window(QDialog): # constructor def __init__(self): super(Window, self).__init__() # setting window title self.setWindowTitle("Python") # setting geometry to the window self.setGeometry(100, 100, 300, 400) # creating a group box self.formGroupBox = QGroupBox("Form 1") # creating spin box to select age self.ageSpinBar = QSpinBox() # creating combo box to select degree self.degreeComboBox = QComboBox() # adding items to the combo box self.degreeComboBox.addItems(["BTech", "MTech", "PhD"]) # creating a line edit self.nameLineEdit = QLineEdit() # calling the method that create the form self.createForm() # creating a dialog button for ok and cancel self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) # adding action when form is accepted self.buttonBox.accepted.connect(self.getInfo) # adding action when form is rejected self.buttonBox.rejected.connect(self.reject) # creating a vertical layout mainLayout = QVBoxLayout() # adding form group box to the layout mainLayout.addWidget(self.formGroupBox) # adding button box to the layout mainLayout.addWidget(self.buttonBox) # setting lay out self.setLayout(mainLayout) # get info method called when form is accepted def getInfo(self): # printing the form information print("Person Name : {0}".format(self.nameLineEdit.text())) print("Degree : {0}".format(self.degreeComboBox.currentText())) print("Age : {0}".format(self.ageSpinBar.text())) # closing the window self.close() # creat form method def createForm(self): # creating a form layout layout = QFormLayout() # adding rows # for name and adding input text layout.addRow(QLabel("Name"), self.nameLineEdit) # for degree and adding combo box layout.addRow(QLabel("Degree"), self.degreeComboBox) # for age and adding spin box layout.addRow(QLabel("Age"), self.ageSpinBar) # setting layout self.formGroupBox.setLayout(layout) # main methodif __name__ == '__main__': # create pyqt5 app app = QApplication(sys.argv) # create the instance of our Window window = Window() # showing the window window.show() # start the app sys.exit(app.exec()) Output : Person Name : Geek Degree : BTech Age : 20 akshaysingh98088 PyQt-exercise Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Convert integer to string in Python
[ { "code": null, "e": 25457, "s": 25429, "text": "\n03 Jan, 2022" }, { "code": null, "e": 25777, "s": 25457, "text": "In this article we will see how we can create a user form in PyQt5. A user form is basically a dialog box that makes a user data entry more controllable and easier to use for the user. Sometimes while creating a large user interface application there is need of creating user form in order to get essential information." }, { "code": null, "e": 25800, "s": 25777, "text": "Implementation steps :" }, { "code": null, "e": 26529, "s": 25800, "text": "1. Create a window class that inherits QDialog2. Add window title and set its geometry3. Create a QGropBox object4. Create line edit to get the name, spin box to get the age and combo box to select the degree5. Create a createForm method that will create a form6. Inside the create form method, create a form layout and add rows7. Each row should be has a label and the input method example name label and line edit for input, similarly label for degree and age and combo box and spin box for input.8. Create a QDialogButtonBox for ok and cancel state9. Add action to the button for acceptance and for rejection10. If ok button is pressed just print all the information and if the cancel button is pressed window will get closed" }, { "code": null, "e": 26557, "s": 26529, "text": "Below is the implementation" }, { "code": null, "e": 26565, "s": 26557, "text": "Python3" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * import sys # creating a class# that inherits the QDialog classclass Window(QDialog): # constructor def __init__(self): super(Window, self).__init__() # setting window title self.setWindowTitle(\"Python\") # setting geometry to the window self.setGeometry(100, 100, 300, 400) # creating a group box self.formGroupBox = QGroupBox(\"Form 1\") # creating spin box to select age self.ageSpinBar = QSpinBox() # creating combo box to select degree self.degreeComboBox = QComboBox() # adding items to the combo box self.degreeComboBox.addItems([\"BTech\", \"MTech\", \"PhD\"]) # creating a line edit self.nameLineEdit = QLineEdit() # calling the method that create the form self.createForm() # creating a dialog button for ok and cancel self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) # adding action when form is accepted self.buttonBox.accepted.connect(self.getInfo) # adding action when form is rejected self.buttonBox.rejected.connect(self.reject) # creating a vertical layout mainLayout = QVBoxLayout() # adding form group box to the layout mainLayout.addWidget(self.formGroupBox) # adding button box to the layout mainLayout.addWidget(self.buttonBox) # setting lay out self.setLayout(mainLayout) # get info method called when form is accepted def getInfo(self): # printing the form information print(\"Person Name : {0}\".format(self.nameLineEdit.text())) print(\"Degree : {0}\".format(self.degreeComboBox.currentText())) print(\"Age : {0}\".format(self.ageSpinBar.text())) # closing the window self.close() # creat form method def createForm(self): # creating a form layout layout = QFormLayout() # adding rows # for name and adding input text layout.addRow(QLabel(\"Name\"), self.nameLineEdit) # for degree and adding combo box layout.addRow(QLabel(\"Degree\"), self.degreeComboBox) # for age and adding spin box layout.addRow(QLabel(\"Age\"), self.ageSpinBar) # setting layout self.formGroupBox.setLayout(layout) # main methodif __name__ == '__main__': # create pyqt5 app app = QApplication(sys.argv) # create the instance of our Window window = Window() # showing the window window.show() # start the app sys.exit(app.exec())", "e": 29195, "s": 26565, "text": null }, { "code": null, "e": 29204, "s": 29195, "text": "Output :" }, { "code": null, "e": 29248, "s": 29204, "text": "Person Name : Geek\nDegree : BTech\nAge : 20\n" }, { "code": null, "e": 29265, "s": 29248, "text": "akshaysingh98088" }, { "code": null, "e": 29279, "s": 29265, "text": "PyQt-exercise" }, { "code": null, "e": 29290, "s": 29279, "text": "Python-gui" }, { "code": null, "e": 29302, "s": 29290, "text": "Python-PyQt" }, { "code": null, "e": 29309, "s": 29302, "text": "Python" }, { "code": null, "e": 29407, "s": 29309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29442, "s": 29407, "text": "Read a file line by line in Python" }, { "code": null, "e": 29474, "s": 29442, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29496, "s": 29474, "text": "Enumerate() in Python" }, { "code": null, "e": 29538, "s": 29496, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29568, "s": 29538, "text": "Iterate over a list in Python" }, { "code": null, "e": 29594, "s": 29568, "text": "Python String | replace()" }, { "code": null, "e": 29623, "s": 29594, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29667, "s": 29623, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29704, "s": 29667, "text": "Create a Pandas DataFrame from Lists" } ]
Python | Pandas Series.as_matrix() - GeeksforGeeks
27 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.as_matrix() function is used to convert the given series or dataframe object to Numpy-array representation. Syntax: Series.as_matrix(columns=None) Parameter :columns : If None, return all columns, otherwise, returns specified columns. Returns : values : ndarray Example #1: Use Series.as_matrix() function to return the numpy-array representation of the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output : City 1 New York City 2 Chicago City 3 Toronto City 4 Lisbon City 5 Rio dtype: object Now we will use Series.as_matrix() function to return the numpy array representation of the given series object. # return numpy array representationresult = sr.as_matrix() # Print the resultprint(result) Output : ['New York' 'Chicago' 'Toronto' 'Lisbon' 'Rio'] As we can see in the output, the Series.as_matrix() function has successfully returned the numpy array representation of the given series object. Example #2 : Use Series.as_matrix() function to return the numpy-array representation of the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None]) # Create the Index# apply yearly frequencyindex_ = pd.date_range('2010-10-09 08:45', periods = 11, freq ='Y') # set the indexsr.index = index_ # Print the seriesprint(sr) Output : 2010-12-31 08:45:00 11.0 2011-12-31 08:45:00 21.0 2012-12-31 08:45:00 8.0 2013-12-31 08:45:00 18.0 2014-12-31 08:45:00 65.0 2015-12-31 08:45:00 18.0 2016-12-31 08:45:00 32.0 2017-12-31 08:45:00 10.0 2018-12-31 08:45:00 5.0 2019-12-31 08:45:00 32.0 2020-12-31 08:45:00 NaN Freq: A-DEC, dtype: float64 Now we will use Series.as_matrix() function to return the numpy array representation of the given series object. # return numpy array representationresult = sr.as_matrix() # Print the resultprint(result) Output : [ 11. 21. 8. 18. 65. 18. 32. 10. 5. 32. nan] As we can see in the output, the Series.as_matrix() function has successfully returned the numpy array representation of the given series object. Python pandas-series Python pandas-series-methods 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": 26236, "s": 26208, "text": "\n27 Feb, 2019" }, { "code": null, "e": 26493, "s": 26236, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 26615, "s": 26493, "text": "Pandas Series.as_matrix() function is used to convert the given series or dataframe object to Numpy-array representation." }, { "code": null, "e": 26654, "s": 26615, "text": "Syntax: Series.as_matrix(columns=None)" }, { "code": null, "e": 26742, "s": 26654, "text": "Parameter :columns : If None, return all columns, otherwise, returns specified columns." }, { "code": null, "e": 26769, "s": 26742, "text": "Returns : values : ndarray" }, { "code": null, "e": 26882, "s": 26769, "text": "Example #1: Use Series.as_matrix() function to return the numpy-array representation of the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 27159, "s": 26882, "text": null }, { "code": null, "e": 27168, "s": 27159, "text": "Output :" }, { "code": null, "e": 27277, "s": 27168, "text": "City 1 New York\nCity 2 Chicago\nCity 3 Toronto\nCity 4 Lisbon\nCity 5 Rio\ndtype: object" }, { "code": null, "e": 27390, "s": 27277, "text": "Now we will use Series.as_matrix() function to return the numpy array representation of the given series object." }, { "code": "# return numpy array representationresult = sr.as_matrix() # Print the resultprint(result)", "e": 27482, "s": 27390, "text": null }, { "code": null, "e": 27491, "s": 27482, "text": "Output :" }, { "code": null, "e": 27540, "s": 27491, "text": "['New York' 'Chicago' 'Toronto' 'Lisbon' 'Rio']\n" }, { "code": null, "e": 27800, "s": 27540, "text": "As we can see in the output, the Series.as_matrix() function has successfully returned the numpy array representation of the given series object. Example #2 : Use Series.as_matrix() function to return the numpy-array representation of the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None]) # Create the Index# apply yearly frequencyindex_ = pd.date_range('2010-10-09 08:45', periods = 11, freq ='Y') # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 28101, "s": 27800, "text": null }, { "code": null, "e": 28110, "s": 28101, "text": "Output :" }, { "code": null, "e": 28446, "s": 28110, "text": "2010-12-31 08:45:00 11.0\n2011-12-31 08:45:00 21.0\n2012-12-31 08:45:00 8.0\n2013-12-31 08:45:00 18.0\n2014-12-31 08:45:00 65.0\n2015-12-31 08:45:00 18.0\n2016-12-31 08:45:00 32.0\n2017-12-31 08:45:00 10.0\n2018-12-31 08:45:00 5.0\n2019-12-31 08:45:00 32.0\n2020-12-31 08:45:00 NaN\nFreq: A-DEC, dtype: float64" }, { "code": null, "e": 28559, "s": 28446, "text": "Now we will use Series.as_matrix() function to return the numpy array representation of the given series object." }, { "code": "# return numpy array representationresult = sr.as_matrix() # Print the resultprint(result)", "e": 28651, "s": 28559, "text": null }, { "code": null, "e": 28660, "s": 28651, "text": "Output :" }, { "code": null, "e": 28717, "s": 28660, "text": "[ 11. 21. 8. 18. 65. 18. 32. 10. 5. 32. nan]" }, { "code": null, "e": 28863, "s": 28717, "text": "As we can see in the output, the Series.as_matrix() function has successfully returned the numpy array representation of the given series object." }, { "code": null, "e": 28884, "s": 28863, "text": "Python pandas-series" }, { "code": null, "e": 28913, "s": 28884, "text": "Python pandas-series-methods" }, { "code": null, "e": 28927, "s": 28913, "text": "Python-pandas" }, { "code": null, "e": 28934, "s": 28927, "text": "Python" }, { "code": null, "e": 29032, "s": 28934, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29050, "s": 29032, "text": "Python Dictionary" }, { "code": null, "e": 29085, "s": 29050, "text": "Read a file line by line in Python" }, { "code": null, "e": 29117, "s": 29085, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29139, "s": 29117, "text": "Enumerate() in Python" }, { "code": null, "e": 29181, "s": 29139, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29211, "s": 29181, "text": "Iterate over a list in Python" }, { "code": null, "e": 29237, "s": 29211, "text": "Python String | replace()" }, { "code": null, "e": 29266, "s": 29237, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29310, "s": 29266, "text": "Reading and Writing to text files in Python" } ]
Accessing array out of bounds in C/C++
In a language such as Java, an exception such as java.lang.ArrayIndexOutOfBoundsException may occur if an array is accessed out of bounds. But there is no such functionality in C and undefined behaviour may occur if an array is accessed out of bounds. A program that demonstrates this in C is given as follows. Live Demo #include <stdio.h> int main() { int arr[] = {1,2,3,4,5}; printf("The elements of array : "); for(int i = 0; i<6; i++) printf(" %d",arr[i]); return 0; } The output of the above program is as follows. The elements of array : 1 2 3 4 5 32765 Now let us understand the above program. The array arr has assigned values only till subscript 4. So when the array elements are printed, arr[5] results in a garbage value. The code snippet that shows this is as follows. int arr[] = {1,2,3,4,5}; printf("The elements of array : "); for(int i = 0; i<6; i++) printf(" %d",arr[i]);
[ { "code": null, "e": 1314, "s": 1062, "text": "In a language such as Java, an exception such as java.lang.ArrayIndexOutOfBoundsException may occur if an array is accessed out of bounds. But there is no such functionality in C and undefined behaviour may occur if an array is accessed out of bounds." }, { "code": null, "e": 1373, "s": 1314, "text": "A program that demonstrates this in C is given as follows." }, { "code": null, "e": 1384, "s": 1373, "text": " Live Demo" }, { "code": null, "e": 1551, "s": 1384, "text": "#include <stdio.h>\nint main() {\n int arr[] = {1,2,3,4,5};\n printf(\"The elements of array : \");\n for(int i = 0; i<6; i++)\n printf(\" %d\",arr[i]);\n return 0;\n}" }, { "code": null, "e": 1598, "s": 1551, "text": "The output of the above program is as follows." }, { "code": null, "e": 1638, "s": 1598, "text": "The elements of array : 1 2 3 4 5 32765" }, { "code": null, "e": 1679, "s": 1638, "text": "Now let us understand the above program." }, { "code": null, "e": 1859, "s": 1679, "text": "The array arr has assigned values only till subscript 4. So when the array elements are printed, arr[5] results in a garbage value. The code snippet that shows this is as follows." }, { "code": null, "e": 1967, "s": 1859, "text": "int arr[] = {1,2,3,4,5};\nprintf(\"The elements of array : \");\nfor(int i = 0; i<6; i++)\nprintf(\" %d\",arr[i]);" } ]
list remove() function in C++ STL - GeeksforGeeks
20 Jun, 2018 The list::remove() is a built-in function in C++ STL which is used to remove elements from a list container. It removes elements comparing to a value. It takes a value as the parameter and removes all the elements from the list container whose value is equal to the value passed in the parameter of the function. Syntax: list_name.remove(val) Parameters: This function accepts a single parameter val which refers to the value of elements needed to be removed from the list. The remove() function will remove all the elements from the list whose value is equal to val. Return Value: This function does not returns any value. Below program illustrates the list::remove() function. // CPP program to illustrate the// list::remove() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // Add elements to the List demoList.push_back(10); demoList.push_back(20); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); // List before removing elements cout << "List before removing elements: "; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) { cout << *itr << " "; } // delete all elements with value 20 demoList.remove(20); // List after removing elements cout << "\nList after removing elements: "; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) { cout << *itr << " "; } return 0;} List before removing elements: 10 20 20 30 40 List after removing elements: 10 30 40 Note: This function works in linear time complexity. CPP-Functions cpp-list STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inheritance in C++ Socket Programming in C/C++ Map in C++ Standard Template Library (STL) Iterators in C++ STL C++ Classes and Objects Operator Overloading in C++ Multidimensional Arrays in C / C++ Constructors in C++ Object Oriented Programming in C++ Virtual Function in C++
[ { "code": null, "e": 24602, "s": 24574, "text": "\n20 Jun, 2018" }, { "code": null, "e": 24915, "s": 24602, "text": "The list::remove() is a built-in function in C++ STL which is used to remove elements from a list container. It removes elements comparing to a value. It takes a value as the parameter and removes all the elements from the list container whose value is equal to the value passed in the parameter of the function." }, { "code": null, "e": 24923, "s": 24915, "text": "Syntax:" }, { "code": null, "e": 24947, "s": 24923, "text": "list_name.remove(val) \n" }, { "code": null, "e": 25172, "s": 24947, "text": "Parameters: This function accepts a single parameter val which refers to the value of elements needed to be removed from the list. The remove() function will remove all the elements from the list whose value is equal to val." }, { "code": null, "e": 25228, "s": 25172, "text": "Return Value: This function does not returns any value." }, { "code": null, "e": 25283, "s": 25228, "text": "Below program illustrates the list::remove() function." }, { "code": "// CPP program to illustrate the// list::remove() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // Add elements to the List demoList.push_back(10); demoList.push_back(20); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); // List before removing elements cout << \"List before removing elements: \"; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) { cout << *itr << \" \"; } // delete all elements with value 20 demoList.remove(20); // List after removing elements cout << \"\\nList after removing elements: \"; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) { cout << *itr << \" \"; } return 0;}", "e": 26082, "s": 25283, "text": null }, { "code": null, "e": 26169, "s": 26082, "text": "List before removing elements: 10 20 20 30 40 \nList after removing elements: 10 30 40\n" }, { "code": null, "e": 26222, "s": 26169, "text": "Note: This function works in linear time complexity." }, { "code": null, "e": 26236, "s": 26222, "text": "CPP-Functions" }, { "code": null, "e": 26245, "s": 26236, "text": "cpp-list" }, { "code": null, "e": 26249, "s": 26245, "text": "STL" }, { "code": null, "e": 26253, "s": 26249, "text": "C++" }, { "code": null, "e": 26257, "s": 26253, "text": "STL" }, { "code": null, "e": 26261, "s": 26257, "text": "CPP" }, { "code": null, "e": 26359, "s": 26261, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26368, "s": 26359, "text": "Comments" }, { "code": null, "e": 26381, "s": 26368, "text": "Old Comments" }, { "code": null, "e": 26400, "s": 26381, "text": "Inheritance in C++" }, { "code": null, "e": 26428, "s": 26400, "text": "Socket Programming in C/C++" }, { "code": null, "e": 26471, "s": 26428, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 26492, "s": 26471, "text": "Iterators in C++ STL" }, { "code": null, "e": 26516, "s": 26492, "text": "C++ Classes and Objects" }, { "code": null, "e": 26544, "s": 26516, "text": "Operator Overloading in C++" }, { "code": null, "e": 26579, "s": 26544, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 26599, "s": 26579, "text": "Constructors in C++" }, { "code": null, "e": 26634, "s": 26599, "text": "Object Oriented Programming in C++" } ]
Ten random useful things in R that you might not know about | by Keith McNulty | Towards Data Science
Often I find myself telling my colleagues and fellow coders simple things that I use in R that really help me with the tasks that I need to progress on. These range from trivial shortcuts, to little known functions, to handy little tricks. Because the R ecosystem is so rich and constantly growing, people can often miss out on knowing about something that can really help them in a task that they have to complete. So I often get a surprised reaction from my audience along the lines of ‘I never knew about that!’. Here are ten things that make my life easier working in R. If you already know them all, sorry for wasting your reading time, and please consider adding a comment with something else that you find useful for the benefit of other readers. I LOVE switch(). It’s basically a convenient shortening of an if statement that chooses its value according to the value of another variable. I find it particularly useful when I am writing code that needs to load a different dataset according to a prior choice you make. For example, if you have a variable called animal and you want to load a different set of data according to whether animal is a dog, cat or rabbit you might write this: data <- read.csv( switch(animal, "dog" = "dogdata.csv", "cat" = "catdata.csv", "rabbit" = "rabbitdata.csv")) This is particularly useful in Shiny apps where you might want to load different datasets or even environment files depending on one or more of the input menu choices. This is less an R hack and more about the RStudio IDE, but the shortcut keys available for common commands are super useful and can save a lot of typing time. My two favourite are Ctrl+Shift+M for the pipe operator %>% and Alt+- for the assignment operator<-. If you want to see a full set of these awesome shortcuts just type Atl+Shift+K in RStudio. If you want to get a quick Shiny dashboard up and running with a minimum of fuss, the flexdashboard package has everything you need. It provides simple HTML shortcuts that allow easy construction of sidebars and the organization of your display into rows and columns. It also has a super flexible title bar where you can organize your app into different pages and put in icons and links to Github code or an email address or whatever. As a package which operates within RMarkdown it also allows you to keep all your app in one Rmd file rather than needing to break it out into separate server and UI files like for example shinydashboard. I use flexdashboard whenever I need to create a simple prototype version of a dashboard before moving it on to more advanced design. I can often get dashboards up and running within an hour using flexdashboard. R Shiny development can be frustrating, especially when you get generic error messages that don’t help you understand what is going wrong under the hood. As Shiny develops, more and more validation and testing functions are being added to help better diagnose and alert when specific errors occur. The req() function allows you to prevent an action from occurring unless a another variable is present in the environment, but does so silently and without displaying an error. So you can make the display of UI elements conditional on previous actions. For example, with reference to my example no 1 above: output$go_button <- shiny::renderUI({ # only display button if an animal input has been chosen shiny::req(input$animal) # display button shiny::actionButton("go", paste("Conduct", input$animal, "analysis!") )}) validate() checks before rendering an output and enables you to return a tailored error message should a certain condition not be fulfilled, for example if the user uploaded the wrong file: # get csv input fileinFile <- input$file1data <- inFile$datapath# render table only if it is dogsshiny::renderTable({ # check that it is the dog file, not cats or rabbits shiny::validate( need("Dog Name" %in% colnames(data)), "Dog Name column not found - did you load the right file?" ) data}) For more on these function see my other article here. If you are sharing code that requires login credentials to databases and the like, you can use the .Reviron file to avoid posting those credentials to Github or other spaces where they might be at risk. .Renviron is a file where you can store important environment variables, and is easily editable using the function edit_r_environ() inside the usethis package. As an example, you can set an alias for your remote database credentials in .Renviron, for example: DSN = "database_name", UID = "User ID", PASS = "Password" Then in your shared script, you can call these variables. For example: db <- DBI::dbConnect( drv = odbc::odbc(), dsn = Sys.getenv("DSN"), uid = Sys.getenv("UID"), pwd = Sys.getenv("PASS")) Its been a tough day, you’ve had a lot on your plate. Your code isn’t as neat as you’d like and you don’t have time to line edit it. Fear not. The stylerpackage has numerous functions to allow automatic restyling of your code to match tidyverse style. It’s a simple as running styler::style_file() on your messy script and it will do a lot (though not all) of the work for you. So you write a lovely R Markdown document where you’ve analyzed a whole bunch of facts about dogs. And then you get told — ‘nah, I’m more interested in cats’. Never fear. You can automate a similar report about cats in just one command if you parameterize your R markdown document. You can do this by defining parameters in the YAML header of your R Markdown document, and giving each parameter a value. For example: ---title: "Animal Analysis"author: "Keith McNulty"date: "21 March 2019"output: html_document: code_folding: "hide"params: animal_name: value: Dog choices: - Dog - Cat - Rabbit years_of_study: input: slider min: 2000 max: 2019 step: 1 round: 1 sep: '' value: [2010, 2017]--- Now you can write these variables into the R code in your document as params$animal_name and params$years_of_study. If you knit your document as normal, it will knit with the default values of these parameters as per the value variable. However, if you knit with parameters by selecting this option in RStudio’s Knit dropdown (or by using knit_with_parameters()), a lovely menu option appears for you to select your parameters before you knit the document. Awesome! revealjs is a package which allows you to create beautiful presentations in HTML with an intuitive slide navigation menu, with embedded R code. It can be used inside R Markdown and has very intuitive HTML shortcuts to allow you to create a nested, logical structure of pretty slides with a variety of styling options. The fact that the presentation is in HTML means that people can follow along on their tablets or phones as they listen to you speak, which is really handy. You can set up a revealjspresentation by installing the package and then calling it in your YAML header. Here’s an example YAML header of a talk I gave recently using revealjs ---title: "Exporing the Edge of the People Analytics Universe"author: "Keith McNulty"output: revealjs::revealjs_presentation: center: yes template: starwars.html theme: blackdate: "HR Analytics Meetup London - 18 March, 2019"resource_files:- darth.png- deathstar.png- hanchewy.png- millenium.png- r2d2-threepio.png- starwars.html- starwars.png- stormtrooper.png--- and here’s an example page. You can find the code here and the presentation here. Most people don’t take full advantage of the HTML tags available in R Shiny. There are 110 tags which offer shortcuts to various HTML formatting and other commands. Recently I built a shiny app that took a long time to perform a task. Knowing that the user would likely multitask while waiting for it to complete, I used tags$audio to have the app play a victory fanfare to alert the user when the task was complete. Ridiculously simple but also awesome, the praise package delivers praise to users. While this can appear like pointless self-admiration, it’s actually super useful in writing R packages where you can offer praise or encouragement to someone if they do something right, for example if a process completes successfully. You can also just put it at the end of a complicated script to give you that extra shot of happiness when it runs successfully. Originally I was a Pure Mathematician, then I became a Psychometrician and a Data Scientist. I am passionate about applying the rigor of all those disciplines to complex people questions. I’m also a coding geek and a massive fan of Japanese RPGs. Find me on LinkedIn or on Twitter.
[ { "code": null, "e": 411, "s": 171, "text": "Often I find myself telling my colleagues and fellow coders simple things that I use in R that really help me with the tasks that I need to progress on. These range from trivial shortcuts, to little known functions, to handy little tricks." }, { "code": null, "e": 687, "s": 411, "text": "Because the R ecosystem is so rich and constantly growing, people can often miss out on knowing about something that can really help them in a task that they have to complete. So I often get a surprised reaction from my audience along the lines of ‘I never knew about that!’." }, { "code": null, "e": 925, "s": 687, "text": "Here are ten things that make my life easier working in R. If you already know them all, sorry for wasting your reading time, and please consider adding a comment with something else that you find useful for the benefit of other readers." }, { "code": null, "e": 1366, "s": 925, "text": "I LOVE switch(). It’s basically a convenient shortening of an if statement that chooses its value according to the value of another variable. I find it particularly useful when I am writing code that needs to load a different dataset according to a prior choice you make. For example, if you have a variable called animal and you want to load a different set of data according to whether animal is a dog, cat or rabbit you might write this:" }, { "code": null, "e": 1502, "s": 1366, "text": "data <- read.csv( switch(animal, \"dog\" = \"dogdata.csv\", \"cat\" = \"catdata.csv\", \"rabbit\" = \"rabbitdata.csv\"))" }, { "code": null, "e": 1670, "s": 1502, "text": "This is particularly useful in Shiny apps where you might want to load different datasets or even environment files depending on one or more of the input menu choices." }, { "code": null, "e": 2021, "s": 1670, "text": "This is less an R hack and more about the RStudio IDE, but the shortcut keys available for common commands are super useful and can save a lot of typing time. My two favourite are Ctrl+Shift+M for the pipe operator %>% and Alt+- for the assignment operator<-. If you want to see a full set of these awesome shortcuts just type Atl+Shift+K in RStudio." }, { "code": null, "e": 2871, "s": 2021, "text": "If you want to get a quick Shiny dashboard up and running with a minimum of fuss, the flexdashboard package has everything you need. It provides simple HTML shortcuts that allow easy construction of sidebars and the organization of your display into rows and columns. It also has a super flexible title bar where you can organize your app into different pages and put in icons and links to Github code or an email address or whatever. As a package which operates within RMarkdown it also allows you to keep all your app in one Rmd file rather than needing to break it out into separate server and UI files like for example shinydashboard. I use flexdashboard whenever I need to create a simple prototype version of a dashboard before moving it on to more advanced design. I can often get dashboards up and running within an hour using flexdashboard." }, { "code": null, "e": 3476, "s": 2871, "text": "R Shiny development can be frustrating, especially when you get generic error messages that don’t help you understand what is going wrong under the hood. As Shiny develops, more and more validation and testing functions are being added to help better diagnose and alert when specific errors occur. The req() function allows you to prevent an action from occurring unless a another variable is present in the environment, but does so silently and without displaying an error. So you can make the display of UI elements conditional on previous actions. For example, with reference to my example no 1 above:" }, { "code": null, "e": 3717, "s": 3476, "text": "output$go_button <- shiny::renderUI({ # only display button if an animal input has been chosen shiny::req(input$animal) # display button shiny::actionButton(\"go\", paste(\"Conduct\", input$animal, \"analysis!\") )})" }, { "code": null, "e": 3907, "s": 3717, "text": "validate() checks before rendering an output and enables you to return a tailored error message should a certain condition not be fulfilled, for example if the user uploaded the wrong file:" }, { "code": null, "e": 4211, "s": 3907, "text": "# get csv input fileinFile <- input$file1data <- inFile$datapath# render table only if it is dogsshiny::renderTable({ # check that it is the dog file, not cats or rabbits shiny::validate( need(\"Dog Name\" %in% colnames(data)), \"Dog Name column not found - did you load the right file?\" ) data})" }, { "code": null, "e": 4265, "s": 4211, "text": "For more on these function see my other article here." }, { "code": null, "e": 4728, "s": 4265, "text": "If you are sharing code that requires login credentials to databases and the like, you can use the .Reviron file to avoid posting those credentials to Github or other spaces where they might be at risk. .Renviron is a file where you can store important environment variables, and is easily editable using the function edit_r_environ() inside the usethis package. As an example, you can set an alias for your remote database credentials in .Renviron, for example:" }, { "code": null, "e": 4790, "s": 4728, "text": " DSN = \"database_name\", UID = \"User ID\", PASS = \"Password\"" }, { "code": null, "e": 4861, "s": 4790, "text": "Then in your shared script, you can call these variables. For example:" }, { "code": null, "e": 4983, "s": 4861, "text": "db <- DBI::dbConnect( drv = odbc::odbc(), dsn = Sys.getenv(\"DSN\"), uid = Sys.getenv(\"UID\"), pwd = Sys.getenv(\"PASS\"))" }, { "code": null, "e": 5361, "s": 4983, "text": "Its been a tough day, you’ve had a lot on your plate. Your code isn’t as neat as you’d like and you don’t have time to line edit it. Fear not. The stylerpackage has numerous functions to allow automatic restyling of your code to match tidyverse style. It’s a simple as running styler::style_file() on your messy script and it will do a lot (though not all) of the work for you." }, { "code": null, "e": 5643, "s": 5361, "text": "So you write a lovely R Markdown document where you’ve analyzed a whole bunch of facts about dogs. And then you get told — ‘nah, I’m more interested in cats’. Never fear. You can automate a similar report about cats in just one command if you parameterize your R markdown document." }, { "code": null, "e": 5778, "s": 5643, "text": "You can do this by defining parameters in the YAML header of your R Markdown document, and giving each parameter a value. For example:" }, { "code": null, "e": 6100, "s": 5778, "text": "---title: \"Animal Analysis\"author: \"Keith McNulty\"date: \"21 March 2019\"output: html_document: code_folding: \"hide\"params: animal_name: value: Dog choices: - Dog - Cat - Rabbit years_of_study: input: slider min: 2000 max: 2019 step: 1 round: 1 sep: '' value: [2010, 2017]---" }, { "code": null, "e": 6566, "s": 6100, "text": "Now you can write these variables into the R code in your document as params$animal_name and params$years_of_study. If you knit your document as normal, it will knit with the default values of these parameters as per the value variable. However, if you knit with parameters by selecting this option in RStudio’s Knit dropdown (or by using knit_with_parameters()), a lovely menu option appears for you to select your parameters before you knit the document. Awesome!" }, { "code": null, "e": 7216, "s": 6566, "text": "revealjs is a package which allows you to create beautiful presentations in HTML with an intuitive slide navigation menu, with embedded R code. It can be used inside R Markdown and has very intuitive HTML shortcuts to allow you to create a nested, logical structure of pretty slides with a variety of styling options. The fact that the presentation is in HTML means that people can follow along on their tablets or phones as they listen to you speak, which is really handy. You can set up a revealjspresentation by installing the package and then calling it in your YAML header. Here’s an example YAML header of a talk I gave recently using revealjs" }, { "code": null, "e": 7591, "s": 7216, "text": "---title: \"Exporing the Edge of the People Analytics Universe\"author: \"Keith McNulty\"output: revealjs::revealjs_presentation: center: yes template: starwars.html theme: blackdate: \"HR Analytics Meetup London - 18 March, 2019\"resource_files:- darth.png- deathstar.png- hanchewy.png- millenium.png- r2d2-threepio.png- starwars.html- starwars.png- stormtrooper.png---" }, { "code": null, "e": 7673, "s": 7591, "text": "and here’s an example page. You can find the code here and the presentation here." }, { "code": null, "e": 8090, "s": 7673, "text": "Most people don’t take full advantage of the HTML tags available in R Shiny. There are 110 tags which offer shortcuts to various HTML formatting and other commands. Recently I built a shiny app that took a long time to perform a task. Knowing that the user would likely multitask while waiting for it to complete, I used tags$audio to have the app play a victory fanfare to alert the user when the task was complete." }, { "code": null, "e": 8536, "s": 8090, "text": "Ridiculously simple but also awesome, the praise package delivers praise to users. While this can appear like pointless self-admiration, it’s actually super useful in writing R packages where you can offer praise or encouragement to someone if they do something right, for example if a process completes successfully. You can also just put it at the end of a complicated script to give you that extra shot of happiness when it runs successfully." } ]
Java Substring Comparisons
Following is an example which compares Strings and portion of strings in Java? Explain with an example. Live Demo public class StringDemo { public static void main(String[] args) { String str1 = "tutorials point"; String str2 = str1.substring(10); int result = str1.compareTo(str2); // prints the return value of the comparison if (result < 0) { System.out.println("str1 is greater than str2"); }else if (result == 0) { System.out.println("str1 is equal to str2"); }else { System.out.println("str1 is less than str2"); } } } str1 is less than str2
[ { "code": null, "e": 1166, "s": 1062, "text": "Following is an example which compares Strings and portion of strings in Java? Explain with an example." }, { "code": null, "e": 1176, "s": 1166, "text": "Live Demo" }, { "code": null, "e": 1668, "s": 1176, "text": "public class StringDemo {\n public static void main(String[] args) {\n String str1 = \"tutorials point\";\n String str2 = str1.substring(10);\n int result = str1.compareTo(str2);\n // prints the return value of the comparison\n if (result < 0) {\n System.out.println(\"str1 is greater than str2\");\n }else if (result == 0) {\n System.out.println(\"str1 is equal to str2\");\n }else {\n System.out.println(\"str1 is less than str2\");\n }\n }\n}" }, { "code": null, "e": 1691, "s": 1668, "text": "str1 is less than str2" } ]
How to create a TreeMap in reverse order in Java - GeeksforGeeks
25 Oct, 2019 By default TreeMap elements in Java are sorted in ascending order of keys. However, we can create the TreeMap in reverse order using Collections.reverseOrder() method in Java and display the elements in descending order of keys. The Collections.reverseOrderS() method in Java returns a Comparator that imposes reverse order of a passed Comparator object. We can use this method to sort any list or any other collection in reverse order of user defined Comparator. Examples: // Insert elements to the TreeMap Input : treemap.put("1", "Welcome"); treemap.put("2", "to"); treemap.put("3", "the"); treemap.put("4", "Geeks"); treemap.put("5", "Community"); // Elements should be printed in reverse order // of their insertion Output : 5: Community 4: Geeks 3: the 2: to 1: Welcome Below program shows how to traverse a TreeMap in reverse order: // Java program to traverse a TreeMap// in reverse orderimport java.util.*; class GFG { public static void main(String args[]) { // Map to store the elements Map<String, String> treemap = new TreeMap<String, String>(Collections.reverseOrder()); // Put elements to the map treemap.put("1", "Welcome"); treemap.put("2", "to"); treemap.put("3", "the"); treemap.put("4", "Geeks"); treemap.put("5", "Community"); Set set = treemap.entrySet(); Iterator i = set.iterator(); // Traverse map and print elements while (i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } }} 5: Community 4: Geeks 3: the 2: to 1: Welcome nidhi_biet Java-Collections Java-Map-Programs java-TreeMap Picked Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Multithreading in Java Collections in Java Initializing a List in Java Overriding in Java
[ { "code": null, "e": 25463, "s": 25435, "text": "\n25 Oct, 2019" }, { "code": null, "e": 25692, "s": 25463, "text": "By default TreeMap elements in Java are sorted in ascending order of keys. However, we can create the TreeMap in reverse order using Collections.reverseOrder() method in Java and display the elements in descending order of keys." }, { "code": null, "e": 25927, "s": 25692, "text": "The Collections.reverseOrderS() method in Java returns a Comparator that imposes reverse order of a passed Comparator object. We can use this method to sort any list or any other collection in reverse order of user defined Comparator." }, { "code": null, "e": 25937, "s": 25927, "text": "Examples:" }, { "code": null, "e": 26354, "s": 25937, "text": "// Insert elements to the TreeMap\n\nInput : treemap.put(\"1\", \"Welcome\");\n treemap.put(\"2\", \"to\");\n treemap.put(\"3\", \"the\");\n treemap.put(\"4\", \"Geeks\");\n treemap.put(\"5\", \"Community\");\n\n// Elements should be printed in reverse order\n// of their insertion\nOutput : 5: Community\n 4: Geeks\n 3: the\n 2: to\n 1: Welcome\n" }, { "code": null, "e": 26418, "s": 26354, "text": "Below program shows how to traverse a TreeMap in reverse order:" }, { "code": "// Java program to traverse a TreeMap// in reverse orderimport java.util.*; class GFG { public static void main(String args[]) { // Map to store the elements Map<String, String> treemap = new TreeMap<String, String>(Collections.reverseOrder()); // Put elements to the map treemap.put(\"1\", \"Welcome\"); treemap.put(\"2\", \"to\"); treemap.put(\"3\", \"the\"); treemap.put(\"4\", \"Geeks\"); treemap.put(\"5\", \"Community\"); Set set = treemap.entrySet(); Iterator i = set.iterator(); // Traverse map and print elements while (i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + \": \"); System.out.println(me.getValue()); } }}", "e": 27211, "s": 26418, "text": null }, { "code": null, "e": 27258, "s": 27211, "text": "5: Community\n4: Geeks\n3: the\n2: to\n1: Welcome\n" }, { "code": null, "e": 27269, "s": 27258, "text": "nidhi_biet" }, { "code": null, "e": 27286, "s": 27269, "text": "Java-Collections" }, { "code": null, "e": 27304, "s": 27286, "text": "Java-Map-Programs" }, { "code": null, "e": 27317, "s": 27304, "text": "java-TreeMap" }, { "code": null, "e": 27324, "s": 27317, "text": "Picked" }, { "code": null, "e": 27329, "s": 27324, "text": "Java" }, { "code": null, "e": 27334, "s": 27329, "text": "Java" }, { "code": null, "e": 27351, "s": 27334, "text": "Java-Collections" }, { "code": null, "e": 27449, "s": 27351, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27464, "s": 27449, "text": "Stream In Java" }, { "code": null, "e": 27483, "s": 27464, "text": "Interfaces in Java" }, { "code": null, "e": 27501, "s": 27483, "text": "ArrayList in Java" }, { "code": null, "e": 27521, "s": 27501, "text": "Stack Class in Java" }, { "code": null, "e": 27545, "s": 27521, "text": "Singleton Class in Java" }, { "code": null, "e": 27577, "s": 27545, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27600, "s": 27577, "text": "Multithreading in Java" }, { "code": null, "e": 27620, "s": 27600, "text": "Collections in Java" }, { "code": null, "e": 27648, "s": 27620, "text": "Initializing a List in Java" } ]
How to render plain text of HTML in Node.js ? - GeeksforGeeks
10 Oct, 2021 Express Js is the web application framework based on Node.js web server functionality that helps us to create the application endpoints that respond based on the HTTP request (POST, GET, etc) method and the requested route. The res.sendFile() method of the express.js module is used to render a particular HTML file that is present in the local machine. Syntax: res.sendFile(path,[options],[fn]) Parameters: The path parameter describes the path and the options parameter contains various properties like maxAge, root, etc and fn is the callback function. Returns: It returns an Object. Project Setup: Step 1: Install Node.js if Node.js is not installed in your machine. Step 2: Create a new folder named public, inside the public folders. Create two files named index.html and products.html inside the public folder. Step 3: Now, initialize a new Node.js project with default configurations using the following command on the command line. npm init -y Step 5: Now install express inside your project using the following command on the command line. npm install express Project Structure: After following the steps your project structure will look like. app.js // Importing modulesconst express = require('express');const path = require('path');const app = express(); app.get('/', (req, res) => { // Sending our index.html file as // response. In path.join() method // __dirname is the directory where // our app.js file is present. In // this case __dirname is the root // folder of the project. res.sendFile(path.join(__dirname, '/public/index.html'));}); app.get('/products', (req, res) => { res.sendFile(path.join(__dirname, '/public/products.html'));}); app.listen(3000, () => { console.log('Server is up on port 3000');}); index.html <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title>HTML render demo</title> </head> <body> <h1>Home page</h1> </body></html> products.html <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title>HTML render demo</title> </head> <body> <h1>Products page</h1> </body></html> Run app.js file using below command: node app.js Output: Open the browser and go to http://localhost:3000, and manually switch to http://localhost:3000/products and you will see the following output. NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between dependencies, devDependencies and peerDependencies How to connect Node.js with React.js ? Node.js Export Module Mongoose find() Function Mongoose Populate() Method Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26267, "s": 26239, "text": "\n10 Oct, 2021" }, { "code": null, "e": 26621, "s": 26267, "text": "Express Js is the web application framework based on Node.js web server functionality that helps us to create the application endpoints that respond based on the HTTP request (POST, GET, etc) method and the requested route. The res.sendFile() method of the express.js module is used to render a particular HTML file that is present in the local machine." }, { "code": null, "e": 26629, "s": 26621, "text": "Syntax:" }, { "code": null, "e": 26663, "s": 26629, "text": "res.sendFile(path,[options],[fn])" }, { "code": null, "e": 26823, "s": 26663, "text": "Parameters: The path parameter describes the path and the options parameter contains various properties like maxAge, root, etc and fn is the callback function." }, { "code": null, "e": 26854, "s": 26823, "text": "Returns: It returns an Object." }, { "code": null, "e": 26871, "s": 26856, "text": "Project Setup:" }, { "code": null, "e": 26940, "s": 26871, "text": "Step 1: Install Node.js if Node.js is not installed in your machine." }, { "code": null, "e": 27087, "s": 26940, "text": "Step 2: Create a new folder named public, inside the public folders. Create two files named index.html and products.html inside the public folder." }, { "code": null, "e": 27210, "s": 27087, "text": "Step 3: Now, initialize a new Node.js project with default configurations using the following command on the command line." }, { "code": null, "e": 27222, "s": 27210, "text": "npm init -y" }, { "code": null, "e": 27319, "s": 27222, "text": "Step 5: Now install express inside your project using the following command on the command line." }, { "code": null, "e": 27339, "s": 27319, "text": "npm install express" }, { "code": null, "e": 27423, "s": 27339, "text": "Project Structure: After following the steps your project structure will look like." }, { "code": null, "e": 27430, "s": 27423, "text": "app.js" }, { "code": "// Importing modulesconst express = require('express');const path = require('path');const app = express(); app.get('/', (req, res) => { // Sending our index.html file as // response. In path.join() method // __dirname is the directory where // our app.js file is present. In // this case __dirname is the root // folder of the project. res.sendFile(path.join(__dirname, '/public/index.html'));}); app.get('/products', (req, res) => { res.sendFile(path.join(__dirname, '/public/products.html'));}); app.listen(3000, () => { console.log('Server is up on port 3000');});", "e": 28014, "s": 27430, "text": null }, { "code": null, "e": 28025, "s": 28014, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title>HTML render demo</title> </head> <body> <h1>Home page</h1> </body></html>", "e": 28324, "s": 28025, "text": null }, { "code": null, "e": 28338, "s": 28324, "text": "products.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title>HTML render demo</title> </head> <body> <h1>Products page</h1> </body></html>", "e": 28641, "s": 28338, "text": null }, { "code": null, "e": 28678, "s": 28641, "text": "Run app.js file using below command:" }, { "code": null, "e": 28690, "s": 28678, "text": "node app.js" }, { "code": null, "e": 28841, "s": 28690, "text": "Output: Open the browser and go to http://localhost:3000, and manually switch to http://localhost:3000/products and you will see the following output." }, { "code": null, "e": 28858, "s": 28841, "text": "NodeJS-Questions" }, { "code": null, "e": 28865, "s": 28858, "text": "Picked" }, { "code": null, "e": 28873, "s": 28865, "text": "Node.js" }, { "code": null, "e": 28890, "s": 28873, "text": "Web Technologies" }, { "code": null, "e": 28988, "s": 28890, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29058, "s": 28988, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 29097, "s": 29058, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 29119, "s": 29097, "text": "Node.js Export Module" }, { "code": null, "e": 29144, "s": 29119, "text": "Mongoose find() Function" }, { "code": null, "e": 29171, "s": 29144, "text": "Mongoose Populate() Method" }, { "code": null, "e": 29211, "s": 29171, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29256, "s": 29211, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29299, "s": 29256, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29349, "s": 29299, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to create HTTPS Server with Node.js ? - GeeksforGeeks
01 Oct, 2021 The HTTP protocol is one of the most important protocols for smooth communication between the networks but in the HTTP protocol, data is not encrypted so any sensitive information can be sniffed during the communication so there is another version of the HTTP i.e HTTPS that encrypts the data during the transmission between a browser and the server. In this article, we will discuss how we can create an HTTPS server using Node.js. To built an HTTPS server with nodeJs, we need an SSL (Secure Sockets Layer) certificate. We can create a self-signed SSL certificate on our local machine. Let’s first create an SSL certificate on our machine first. Step 1: First of all we would generate a self-signed certificate. Open your terminal or git bash and run the following command: openssl req -nodes -new -x509 -keyout server.key -out server.cert After running this command, we would get some options to fill. We can keep those options default or empty by entering ‘.‘ (dot). We would fill only two options for current as that would work fine for us. Common Name (e.g. server FQDN or your name): localhost Email Address : *************@****** (enter your email) Other options such as Country Name, State or Province Name, Locality Name, Organization Name, and Organizational Unit Name are self-explanatory and also the system gives their example for help. creating SSL Certificate This would generate two files: server.cert: The self-signed certificate file. server.key: The private key of the certificate. Step 2: Now let’s code the index.html file. We will create a form to send a message to the server through a POST request. index.html <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content ="width=device-width, initial-scale=1.0"> <title>HTTPS Server</title></head> <body> <h1>Welcome to HTTPS Server</h1> <br><br> <h3>Enter your message</h3> <!-- sending post request to "mssg" with the message from the textarea --> <form action="mssg" method="post"> <textarea name="message" id="" cols="30" rows="10"></textarea> <button type="submit">Send</button> </form></body> </html> Step 3: Now create an app.js file. We would initialize the project using npm in the terminal npm init We would also install express for handling server requests and body-parser for taking input from the form in the POST request. npm install express npm install body-parser Project Structure: file structure Step 4: Now we will code the app.js file. In this file, we create an HTTPS server using createServer() function. We pass the certificate and key files of the SSL certificate as options object in createServer() function. We handle GET and POST requests using express in NodeJs. app.js // Requiring in-built https for creating// https serverconst https = require("https"); // Express for handling GET and POST requestconst express = require("express");const app = express(); // Requiring file system to use local filesconst fs = require("fs"); // Parsing the form of body to take// input from formsconst bodyParser = require("body-parser"); // Configuring express to use body-parser// as middle-wareapp.use(bodyParser.urlencoded({ extended: false }));app.use(bodyParser.json()); // Get request for root of the appapp.get("/", function (req, res) { // Sending index.html to the browser res.sendFile(__dirname + "/index.html");}); // Post request for geetting input from// the formapp.post("/mssg", function (req, res) { // Logging the form body console.log(req.body); // Redirecting to the root res.redirect("/");}); // Creating object of key and certificate// for SSLconst options = { key: fs.readFileSync("server.key"), cert: fs.readFileSync("server.cert"),}; // Creating https server by passing// options and app objecthttps.createServer(options, app).listen(3000, function (req, res) { console.log("Server started at port 3000");}); Step 5: Run node app.js file using below command: node app.js Now open the browser and type the running server address: https://localhost:3000/ Now you would see a webpage running with HTTPS. Write your message in the text area. Web page view Now hit the send button and see it in your console. The output would be: Output in console So, In this way, we can create an HTTPS server using Node.js Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Questions NodeJS-Questions Picked HTML Node.js Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Installation of Node.js on Linux Node.js fs.readFileSync() Method Node.js fs.writeFile() Method Node.js fs.readFile() Method How to update NPM ?
[ { "code": null, "e": 26401, "s": 26373, "text": "\n01 Oct, 2021" }, { "code": null, "e": 26834, "s": 26401, "text": "The HTTP protocol is one of the most important protocols for smooth communication between the networks but in the HTTP protocol, data is not encrypted so any sensitive information can be sniffed during the communication so there is another version of the HTTP i.e HTTPS that encrypts the data during the transmission between a browser and the server. In this article, we will discuss how we can create an HTTPS server using Node.js." }, { "code": null, "e": 27049, "s": 26834, "text": "To built an HTTPS server with nodeJs, we need an SSL (Secure Sockets Layer) certificate. We can create a self-signed SSL certificate on our local machine. Let’s first create an SSL certificate on our machine first." }, { "code": null, "e": 27177, "s": 27049, "text": "Step 1: First of all we would generate a self-signed certificate. Open your terminal or git bash and run the following command:" }, { "code": null, "e": 27243, "s": 27177, "text": "openssl req -nodes -new -x509 -keyout server.key -out server.cert" }, { "code": null, "e": 27447, "s": 27243, "text": "After running this command, we would get some options to fill. We can keep those options default or empty by entering ‘.‘ (dot). We would fill only two options for current as that would work fine for us." }, { "code": null, "e": 27502, "s": 27447, "text": "Common Name (e.g. server FQDN or your name): localhost" }, { "code": null, "e": 27558, "s": 27502, "text": "Email Address : *************@****** (enter your email)" }, { "code": null, "e": 27752, "s": 27558, "text": "Other options such as Country Name, State or Province Name, Locality Name, Organization Name, and Organizational Unit Name are self-explanatory and also the system gives their example for help." }, { "code": null, "e": 27777, "s": 27752, "text": "creating SSL Certificate" }, { "code": null, "e": 27808, "s": 27777, "text": "This would generate two files:" }, { "code": null, "e": 27855, "s": 27808, "text": "server.cert: The self-signed certificate file." }, { "code": null, "e": 27903, "s": 27855, "text": "server.key: The private key of the certificate." }, { "code": null, "e": 28025, "s": 27903, "text": "Step 2: Now let’s code the index.html file. We will create a form to send a message to the server through a POST request." }, { "code": null, "e": 28036, "s": 28025, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content =\"width=device-width, initial-scale=1.0\"> <title>HTTPS Server</title></head> <body> <h1>Welcome to HTTPS Server</h1> <br><br> <h3>Enter your message</h3> <!-- sending post request to \"mssg\" with the message from the textarea --> <form action=\"mssg\" method=\"post\"> <textarea name=\"message\" id=\"\" cols=\"30\" rows=\"10\"></textarea> <button type=\"submit\">Send</button> </form></body> </html>", "e": 28645, "s": 28036, "text": null }, { "code": null, "e": 28738, "s": 28645, "text": "Step 3: Now create an app.js file. We would initialize the project using npm in the terminal" }, { "code": null, "e": 28747, "s": 28738, "text": "npm init" }, { "code": null, "e": 28874, "s": 28747, "text": "We would also install express for handling server requests and body-parser for taking input from the form in the POST request." }, { "code": null, "e": 28918, "s": 28874, "text": "npm install express\nnpm install body-parser" }, { "code": null, "e": 28937, "s": 28918, "text": "Project Structure:" }, { "code": null, "e": 28952, "s": 28937, "text": "file structure" }, { "code": null, "e": 29230, "s": 28952, "text": "Step 4: Now we will code the app.js file. In this file, we create an HTTPS server using createServer() function. We pass the certificate and key files of the SSL certificate as options object in createServer() function. We handle GET and POST requests using express in NodeJs." }, { "code": null, "e": 29237, "s": 29230, "text": "app.js" }, { "code": "// Requiring in-built https for creating// https serverconst https = require(\"https\"); // Express for handling GET and POST requestconst express = require(\"express\");const app = express(); // Requiring file system to use local filesconst fs = require(\"fs\"); // Parsing the form of body to take// input from formsconst bodyParser = require(\"body-parser\"); // Configuring express to use body-parser// as middle-wareapp.use(bodyParser.urlencoded({ extended: false }));app.use(bodyParser.json()); // Get request for root of the appapp.get(\"/\", function (req, res) { // Sending index.html to the browser res.sendFile(__dirname + \"/index.html\");}); // Post request for geetting input from// the formapp.post(\"/mssg\", function (req, res) { // Logging the form body console.log(req.body); // Redirecting to the root res.redirect(\"/\");}); // Creating object of key and certificate// for SSLconst options = { key: fs.readFileSync(\"server.key\"), cert: fs.readFileSync(\"server.cert\"),}; // Creating https server by passing// options and app objecthttps.createServer(options, app).listen(3000, function (req, res) { console.log(\"Server started at port 3000\");});", "e": 30410, "s": 29237, "text": null }, { "code": null, "e": 30460, "s": 30410, "text": "Step 5: Run node app.js file using below command:" }, { "code": null, "e": 30472, "s": 30460, "text": "node app.js" }, { "code": null, "e": 30530, "s": 30472, "text": "Now open the browser and type the running server address:" }, { "code": null, "e": 30554, "s": 30530, "text": "https://localhost:3000/" }, { "code": null, "e": 30639, "s": 30554, "text": "Now you would see a webpage running with HTTPS. Write your message in the text area." }, { "code": null, "e": 30653, "s": 30639, "text": "Web page view" }, { "code": null, "e": 30726, "s": 30653, "text": "Now hit the send button and see it in your console. The output would be:" }, { "code": null, "e": 30744, "s": 30726, "text": "Output in console" }, { "code": null, "e": 30805, "s": 30744, "text": "So, In this way, we can create an HTTPS server using Node.js" }, { "code": null, "e": 30942, "s": 30805, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 30957, "s": 30942, "text": "HTML-Questions" }, { "code": null, "e": 30974, "s": 30957, "text": "NodeJS-Questions" }, { "code": null, "e": 30981, "s": 30974, "text": "Picked" }, { "code": null, "e": 30986, "s": 30981, "text": "HTML" }, { "code": null, "e": 30994, "s": 30986, "text": "Node.js" }, { "code": null, "e": 31011, "s": 30994, "text": "Web Technologies" }, { "code": null, "e": 31016, "s": 31011, "text": "HTML" }, { "code": null, "e": 31114, "s": 31016, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31138, "s": 31114, "text": "REST API (Introduction)" }, { "code": null, "e": 31179, "s": 31138, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 31216, "s": 31179, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31245, "s": 31216, "text": "Form validation using jQuery" }, { "code": null, "e": 31265, "s": 31245, "text": "Angular File Upload" }, { "code": null, "e": 31298, "s": 31265, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31331, "s": 31298, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 31361, "s": 31331, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 31390, "s": 31361, "text": "Node.js fs.readFile() Method" } ]
How to create five equal columns in Bootstrap ? - GeeksforGeeks
19 Jun, 2019 Creating any number of equal columns in a ‘row’ was never as easier as it is now of Bootstrap 4.0+. With the introduction of ‘flexbox’ approach to the grid system, designers don’t have to worry about adding additional CSS to make it work. Here’s how it is done. Go to the Bootstrap site and get the latest Bootstrap files onto your computer. Write a basic HTML template using these files. Once everything is set up, create a simple ‘container’ div inside <body> tag. Inside the ‘container’, create another div with class ‘row’ and as the name suggests, we are creating a row for handling columns. Populate the ‘row’ div with 5 divs with class ‘col’. Because Bootstrap 4.0+ grid system has now shifted to Flexbox, the columns will arrange by themselves into five equally sized DOM elements. Example: <!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" /> <title>5 cols a row</title> <style> .row .col { height: 100px; background: green; } </style></head> <body> <div class="container px-5 py-5"> <div class="row"> <div class="col mx-1">1</div> <div class="col mx-1">2</div> <div class="col mx-1">3</div> <div class="col mx-1">4</div> <div class="col mx-1">5</div> </div> </div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"> </script></body> </html> To distinguish between the columns, a small margin is added to each of the columns. Output: Bootstrap-Misc Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? Difference between Bootstrap 4 and Bootstrap 5 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 ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26700, "s": 26672, "text": "\n19 Jun, 2019" }, { "code": null, "e": 26962, "s": 26700, "text": "Creating any number of equal columns in a ‘row’ was never as easier as it is now of Bootstrap 4.0+. With the introduction of ‘flexbox’ approach to the grid system, designers don’t have to worry about adding additional CSS to make it work. Here’s how it is done." }, { "code": null, "e": 27042, "s": 26962, "text": "Go to the Bootstrap site and get the latest Bootstrap files onto your computer." }, { "code": null, "e": 27089, "s": 27042, "text": "Write a basic HTML template using these files." }, { "code": null, "e": 27167, "s": 27089, "text": "Once everything is set up, create a simple ‘container’ div inside <body> tag." }, { "code": null, "e": 27490, "s": 27167, "text": "Inside the ‘container’, create another div with class ‘row’ and as the name suggests, we are creating a row for handling columns. Populate the ‘row’ div with 5 divs with class ‘col’. Because Bootstrap 4.0+ grid system has now shifted to Flexbox, the columns will arrange by themselves into five equally sized DOM elements." }, { "code": null, "e": 27499, "s": 27490, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" /> <title>5 cols a row</title> <style> .row .col { height: 100px; background: green; } </style></head> <body> <div class=\"container px-5 py-5\"> <div class=\"row\"> <div class=\"col mx-1\">1</div> <div class=\"col mx-1\">2</div> <div class=\"col mx-1\">3</div> <div class=\"col mx-1\">4</div> <div class=\"col mx-1\">5</div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\"> </script></body> </html>", "e": 28452, "s": 27499, "text": null }, { "code": null, "e": 28536, "s": 28452, "text": "To distinguish between the columns, a small margin is added to each of the columns." }, { "code": null, "e": 28544, "s": 28536, "text": "Output:" }, { "code": null, "e": 28559, "s": 28544, "text": "Bootstrap-Misc" }, { "code": null, "e": 28566, "s": 28559, "text": "Picked" }, { "code": null, "e": 28576, "s": 28566, "text": "Bootstrap" }, { "code": null, "e": 28593, "s": 28576, "text": "Web Technologies" }, { "code": null, "e": 28691, "s": 28593, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28732, "s": 28691, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 28773, "s": 28732, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 28836, "s": 28773, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 28869, "s": 28836, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 28916, "s": 28869, "text": "Difference between Bootstrap 4 and Bootstrap 5" }, { "code": null, "e": 28956, "s": 28916, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28989, "s": 28956, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29034, "s": 28989, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29077, "s": 29034, "text": "How to fetch data from an API in ReactJS ?" } ]
firstof - Django Template Tags - GeeksforGeeks
27 Dec, 2021 A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variables, for loops, comments, firstof, etc. This article revolves about how to use firstof tag in Templates. firstof tag Outputs the first argument variable that is not “false” (i.e. exists, is not empty, is not a false boolean value, and is not a zero numeric value). Outputs nothing if all the passed variables are “false”. Syntax {% firstof var1 var2 var3... %} Example {% firstof var1 var2 var3 %} This is equivalent to: {% if var1 %} {{ var1 }} {% elif var2 %} {{ var2 }} {% elif var3 %} {{ var3 }} {% endif %} One can also use a literal string as a fallback value in case all passed variables are False: {% firstof var1 var2 var3 "fallback value" %} Illustration of How to use firstof tag in Django templates using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Now create a view through which we will access the template, In geeks/views.py, Python3 # import Http Response from django# import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request): # create a dictionary context = { "var1":None, "var2":None, "var3":"GeeksForGeeks" } # return response return render(request, "geeks.html", context) Create a url path to map to this view. In geeks/urls.py, Python3 from django.urls import path # importing views from views.pyfrom .views import geeks_view urlpatterns = [ path('', geeks_view),] Create a template in templates/geeks.html. html <h3>Variable displayed : </h3> {% firstof var1 var2 var3 %} Let’s check if data is displayed from the third variable in geeks.html This tag auto-escapes variable values. You can disable auto-escaping with: {% autoescape off %} {% firstof var1 var2 var3 "fallback value" %} {% endautoescape %} Or if only some variables should be escaped, you can use: {% firstof var1 var2|safe var3 "fallback value"|safe %} You can use the syntax {% firstof var1 var2 var3 as value %} to store the output inside a variable. surindertarika1234 Django-templates Python Django 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 Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25561, "s": 25533, "text": "\n27 Dec, 2021" }, { "code": null, "e": 26232, "s": 25561, "text": "A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variables, for loops, comments, firstof, etc. This article revolves about how to use firstof tag in Templates. firstof tag Outputs the first argument variable that is not “false” (i.e. exists, is not empty, is not a false boolean value, and is not a zero numeric value). Outputs nothing if all the passed variables are “false”. " }, { "code": null, "e": 26239, "s": 26232, "text": "Syntax" }, { "code": null, "e": 26271, "s": 26239, "text": "{% firstof var1 var2 var3... %}" }, { "code": null, "e": 26279, "s": 26271, "text": "Example" }, { "code": null, "e": 26308, "s": 26279, "text": "{% firstof var1 var2 var3 %}" }, { "code": null, "e": 26332, "s": 26308, "text": "This is equivalent to: " }, { "code": null, "e": 26435, "s": 26332, "text": "{% if var1 %}\n {{ var1 }}\n{% elif var2 %}\n {{ var2 }}\n{% elif var3 %}\n {{ var3 }}\n{% endif %}" }, { "code": null, "e": 26530, "s": 26435, "text": "One can also use a literal string as a fallback value in case all passed variables are False: " }, { "code": null, "e": 26576, "s": 26530, "text": "{% firstof var1 var2 var3 \"fallback value\" %}" }, { "code": null, "e": 26723, "s": 26578, "text": "Illustration of How to use firstof tag in Django templates using an Example. Consider a project named geeksforgeeks having an app named geeks. " }, { "code": null, "e": 26812, "s": 26723, "text": "Refer to the following articles to check how to create a project and an app in Django. " }, { "code": null, "e": 26863, "s": 26812, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 26896, "s": 26863, "text": "How to Create an App in Django ?" }, { "code": null, "e": 26978, "s": 26896, "text": "Now create a view through which we will access the template, In geeks/views.py, " }, { "code": null, "e": 26986, "s": 26978, "text": "Python3" }, { "code": "# import Http Response from django# import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request): # create a dictionary context = { \"var1\":None, \"var2\":None, \"var3\":\"GeeksForGeeks\" } # return response return render(request, \"geeks.html\", context)", "e": 27319, "s": 26986, "text": null }, { "code": null, "e": 27377, "s": 27319, "text": "Create a url path to map to this view. In geeks/urls.py, " }, { "code": null, "e": 27385, "s": 27377, "text": "Python3" }, { "code": "from django.urls import path # importing views from views.pyfrom .views import geeks_view urlpatterns = [ path('', geeks_view),]", "e": 27517, "s": 27385, "text": null }, { "code": null, "e": 27562, "s": 27517, "text": "Create a template in templates/geeks.html. " }, { "code": null, "e": 27567, "s": 27562, "text": "html" }, { "code": "<h3>Variable displayed : </h3> {% firstof var1 var2 var3 %}", "e": 27627, "s": 27567, "text": null }, { "code": null, "e": 27700, "s": 27627, "text": "Let’s check if data is displayed from the third variable in geeks.html " }, { "code": null, "e": 27779, "s": 27702, "text": "This tag auto-escapes variable values. You can disable auto-escaping with: " }, { "code": null, "e": 27870, "s": 27779, "text": "{% autoescape off %}\n {% firstof var1 var2 var3 \"fallback value\" %}\n{% endautoescape %}" }, { "code": null, "e": 27929, "s": 27870, "text": "Or if only some variables should be escaped, you can use: " }, { "code": null, "e": 27985, "s": 27929, "text": "{% firstof var1 var2|safe var3 \"fallback value\"|safe %}" }, { "code": null, "e": 28086, "s": 27985, "text": "You can use the syntax {% firstof var1 var2 var3 as value %} to store the output inside a variable. " }, { "code": null, "e": 28105, "s": 28086, "text": "surindertarika1234" }, { "code": null, "e": 28122, "s": 28105, "text": "Django-templates" }, { "code": null, "e": 28136, "s": 28122, "text": "Python Django" }, { "code": null, "e": 28143, "s": 28136, "text": "Python" }, { "code": null, "e": 28241, "s": 28143, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28273, "s": 28241, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28315, "s": 28273, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28357, "s": 28315, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28384, "s": 28357, "text": "Python Classes and Objects" }, { "code": null, "e": 28440, "s": 28384, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28479, "s": 28440, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28501, "s": 28479, "text": "Defaultdict in Python" }, { "code": null, "e": 28532, "s": 28501, "text": "Python | os.path.join() method" }, { "code": null, "e": 28561, "s": 28532, "text": "Create a directory in Python" } ]
Python | String startswith() - GeeksforGeeks
11 Jan, 2018 The startswith() method returns True if a string starts with the given prefix otherwise returns False. Syntax : str.startswith(prefix, start, end) Parameters : prefix : prefix ix nothing but a string which needs to be checked. start : Starting position where prefix is needs to be checked within the string. end : Ending position where prefix is needs to be checked within the string. NOTE : If start and end index is not provided then by default it takes 0 and length-1 as starting and ending indexes where ending indes is not included in our search. Returns : It returns True if strings starts with the given prefix otherwise returns False. Examples: Input : text = "geeks for geeks." result = text.startswith('for geeks') Output : False Input : text = "geeks for geeks." result = text.startswith('geeks', 0) Output : True Error : ValueError : This error is raised in the case when the argument string is not found in the target string # Python code shows the working of# .startsswith() function text = "geeks for geeks." # returns Falseresult = text.startswith('for geeks')print (result) # returns Trueresult = text.startswith('geeks')print (result) # returns Falseresult = text.startswith('for geeks.')print (result) # returns Trueresult = text.startswith('geeks for geeks.')print (result) Output: False True False True python-string 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 How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 24682, "s": 24654, "text": "\n11 Jan, 2018" }, { "code": null, "e": 24785, "s": 24682, "text": "The startswith() method returns True if a string starts with the given prefix otherwise returns False." }, { "code": null, "e": 24794, "s": 24785, "text": "Syntax :" }, { "code": null, "e": 24830, "s": 24794, "text": "str.startswith(prefix, start, end)\n" }, { "code": null, "e": 24843, "s": 24830, "text": "Parameters :" }, { "code": null, "e": 25069, "s": 24843, "text": "prefix : prefix ix nothing but a string which needs to be checked.\nstart : Starting position where prefix is needs to be checked within the string.\nend : Ending position where prefix is needs to be checked within the string.\n" }, { "code": null, "e": 25236, "s": 25069, "text": "NOTE : If start and end index is not provided then by default it takes 0 and length-1 as starting and ending indexes where ending indes is not included in our search." }, { "code": null, "e": 25246, "s": 25236, "text": "Returns :" }, { "code": null, "e": 25328, "s": 25246, "text": "It returns True if strings starts with the given\nprefix otherwise returns False.\n" }, { "code": null, "e": 25338, "s": 25328, "text": "Examples:" }, { "code": null, "e": 25528, "s": 25338, "text": "Input : text = \"geeks for geeks.\"\n result = text.startswith('for geeks')\nOutput : False\n\nInput : text = \"geeks for geeks.\"\n result = text.startswith('geeks', 0)\nOutput : True\n" }, { "code": null, "e": 25641, "s": 25528, "text": "Error : ValueError : This error is raised in the case when the argument string is not found in the target string" }, { "code": "# Python code shows the working of# .startsswith() function text = \"geeks for geeks.\" # returns Falseresult = text.startswith('for geeks')print (result) # returns Trueresult = text.startswith('geeks')print (result) # returns Falseresult = text.startswith('for geeks.')print (result) # returns Trueresult = text.startswith('geeks for geeks.')print (result)", "e": 26007, "s": 25641, "text": null }, { "code": null, "e": 26015, "s": 26007, "text": "Output:" }, { "code": null, "e": 26038, "s": 26015, "text": "False\nTrue\nFalse\nTrue\n" }, { "code": null, "e": 26052, "s": 26038, "text": "python-string" }, { "code": null, "e": 26059, "s": 26052, "text": "Python" }, { "code": null, "e": 26157, "s": 26059, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26185, "s": 26157, "text": "Read JSON file using Python" }, { "code": null, "e": 26235, "s": 26185, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 26257, "s": 26235, "text": "Python map() function" }, { "code": null, "e": 26301, "s": 26257, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 26319, "s": 26301, "text": "Python Dictionary" }, { "code": null, "e": 26342, "s": 26319, "text": "Taking input in Python" }, { "code": null, "e": 26377, "s": 26342, "text": "Read a file line by line in Python" }, { "code": null, "e": 26409, "s": 26377, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26431, "s": 26409, "text": "Enumerate() in Python" } ]
Linear Regression using PyTorch - GeeksforGeeks
17 Sep, 2021 Linear Regression is a very commonly used statistical method that allows us to determine and study the relationship between two continuous variables. The various properties of linear regression and its Python implementation have been covered in this article previously. Now, we shall find out how to implement this in PyTorch, a very popular deep learning library that is being developed by Facebook.Firstly, you will need to install PyTorch into your Python environment. The easiest way to do this is to use the pip or conda tool. Visit pytorch.org and install the version of your Python interpreter and the package manager that you would like to use. Python3 # We can run this Python code on a Jupyter notebook# to automatically install the correct version of# PyTorch. # http://pytorch.org / from os import pathfrom wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tagplatform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag()) accelerator = 'cu80' if path.exists('/opt / bin / nvidia-smi') else 'cpu' ! pip install -q http://download.pytorch.org / whl/{accelerator}/torch-1.3.1.post4-{platform}-linux_x86_64.whl torchvision With PyTorch installed, let us now have a look at the code. Write the two lines given below to import the necessary library functions and objects. Python3 import torchfrom torch.autograd import Variable We also define some data and assign them to variables x_data and y_data as given below: Python3 x_data = Variable(torch.Tensor([[1.0], [2.0], [3.0]]))y_data = Variable(torch.Tensor([[2.0], [4.0], [6.0]])) Here, x_data is our independent variable and y_data is our dependent variable. This will be our dataset for now. Next, we need to define our model. There are two main steps associated with defining our model. They are: Initializing our model.Declaring the forward pass. Initializing our model. Declaring the forward pass. We use the class given below: Python3 class LinearRegressionModel(torch.nn.Module): def __init__(self): super(LinearRegressionModel, self).__init__() self.linear = torch.nn.Linear(1, 1) # One in and one out def forward(self, x): y_pred = self.linear(x) return y_pred As you can see, our Model class is a subclass of torch.nn.module. Also, since here we have only one input and one output, we use a Linear model with both the input and output dimension as 1.Next, we create an object of this model. Python3 # our modelour_model = LinearRegressionModel() After this, we select the optimizer and the loss criteria. Here, we will use the mean squared error (MSE) as our loss function and stochastic gradient descent (SGD) as our optimizer. Also, we arbitrarily fix a learning rate of 0.01. Python3 criterion = torch.nn.MSELoss(size_average = False)optimizer = torch.optim.SGD(our_model.parameters(), lr = 0.01) We now arrive at our training step. We perform the following tasks 500 times during training: Perform a forward pass bypassing our data and finding out the predicted value of y.Compute the loss using MSE.Reset all the gradients to 0, perform a backpropagation and then, update the weights. Perform a forward pass bypassing our data and finding out the predicted value of y. Compute the loss using MSE. Reset all the gradients to 0, perform a backpropagation and then, update the weights. Python3 for epoch in range(500): # Forward pass: Compute predicted y by passing # x to the model pred_y = our_model(x_data) # Compute and print loss loss = criterion(pred_y, y_data) # Zero gradients, perform a backward pass, # and update the weights. optimizer.zero_grad() loss.backward() optimizer.step() print('epoch {}, loss {}'.format(epoch, loss.item())) Once the training is completed, we test if we are getting correct results using the model that we defined. So, we test it for an unknown value of x_data, in this case, 4.0. Python3 new_var = Variable(torch.Tensor([[4.0]]))pred_y = our_model(new_var)print("predict (after training)", 4, our_model(new_var).item()) If you performed all steps correctly, you will see that for input 4.0, you are getting a value that is very close to 8.0 as below. So, our model inherently learns the relationship between the input data and the output data without being programmed explicitly.predict (after training) 4 7.966438293457031For your reference, you can find the entire code of this article given below: Python3 import torchfrom torch.autograd import Variable x_data = Variable(torch.Tensor([[1.0], [2.0], [3.0]]))y_data = Variable(torch.Tensor([[2.0], [4.0], [6.0]])) class LinearRegressionModel(torch.nn.Module): def __init__(self): super(LinearRegressionModel, self).__init__() self.linear = torch.nn.Linear(1, 1) # One in and one out def forward(self, x): y_pred = self.linear(x) return y_pred # our modelour_model = LinearRegressionModel() criterion = torch.nn.MSELoss(size_average = False)optimizer = torch.optim.SGD(our_model.parameters(), lr = 0.01) for epoch in range(500): # Forward pass: Compute predicted y by passing # x to the model pred_y = our_model(x_data) # Compute and print loss loss = criterion(pred_y, y_data) # Zero gradients, perform a backward pass, # and update the weights. optimizer.zero_grad() loss.backward() optimizer.step() print('epoch {}, loss {}'.format(epoch, loss.item())) new_var = Variable(torch.Tensor([[4.0]]))pred_y = our_model(new_var)print("predict (after training)", 4, our_model(new_var).item()) PyTorchZeroToAll Penn State STAT 501 davidbrear04 anikakapoor tanwarsinghvaibhav Advanced Computer Subject Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Tree System Design Tutorial Decision Tree Introduction with example Python | Decision tree implementation Copying Files to and from Docker Containers Decision Tree Agents in Artificial Intelligence Activation functions in Neural Networks Decision Tree Introduction with example Introduction to Recurrent Neural Network
[ { "code": null, "e": 25499, "s": 25471, "text": "\n17 Sep, 2021" }, { "code": null, "e": 26154, "s": 25499, "text": "Linear Regression is a very commonly used statistical method that allows us to determine and study the relationship between two continuous variables. The various properties of linear regression and its Python implementation have been covered in this article previously. Now, we shall find out how to implement this in PyTorch, a very popular deep learning library that is being developed by Facebook.Firstly, you will need to install PyTorch into your Python environment. The easiest way to do this is to use the pip or conda tool. Visit pytorch.org and install the version of your Python interpreter and the package manager that you would like to use. " }, { "code": null, "e": 26162, "s": 26154, "text": "Python3" }, { "code": "# We can run this Python code on a Jupyter notebook# to automatically install the correct version of# PyTorch. # http://pytorch.org / from os import pathfrom wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tagplatform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag()) accelerator = 'cu80' if path.exists('/opt / bin / nvidia-smi') else 'cpu' ! pip install -q http://download.pytorch.org / whl/{accelerator}/torch-1.3.1.post4-{platform}-linux_x86_64.whl torchvision", "e": 26657, "s": 26162, "text": null }, { "code": null, "e": 26806, "s": 26657, "text": "With PyTorch installed, let us now have a look at the code. Write the two lines given below to import the necessary library functions and objects. " }, { "code": null, "e": 26814, "s": 26806, "text": "Python3" }, { "code": "import torchfrom torch.autograd import Variable", "e": 26862, "s": 26814, "text": null }, { "code": null, "e": 26952, "s": 26862, "text": "We also define some data and assign them to variables x_data and y_data as given below: " }, { "code": null, "e": 26960, "s": 26952, "text": "Python3" }, { "code": "x_data = Variable(torch.Tensor([[1.0], [2.0], [3.0]]))y_data = Variable(torch.Tensor([[2.0], [4.0], [6.0]]))", "e": 27069, "s": 26960, "text": null }, { "code": null, "e": 27290, "s": 27069, "text": "Here, x_data is our independent variable and y_data is our dependent variable. This will be our dataset for now. Next, we need to define our model. There are two main steps associated with defining our model. They are: " }, { "code": null, "e": 27341, "s": 27290, "text": "Initializing our model.Declaring the forward pass." }, { "code": null, "e": 27365, "s": 27341, "text": "Initializing our model." }, { "code": null, "e": 27393, "s": 27365, "text": "Declaring the forward pass." }, { "code": null, "e": 27425, "s": 27393, "text": "We use the class given below: " }, { "code": null, "e": 27433, "s": 27425, "text": "Python3" }, { "code": "class LinearRegressionModel(torch.nn.Module): def __init__(self): super(LinearRegressionModel, self).__init__() self.linear = torch.nn.Linear(1, 1) # One in and one out def forward(self, x): y_pred = self.linear(x) return y_pred", "e": 27699, "s": 27433, "text": null }, { "code": null, "e": 27932, "s": 27699, "text": "As you can see, our Model class is a subclass of torch.nn.module. Also, since here we have only one input and one output, we use a Linear model with both the input and output dimension as 1.Next, we create an object of this model. " }, { "code": null, "e": 27940, "s": 27932, "text": "Python3" }, { "code": "# our modelour_model = LinearRegressionModel()", "e": 27987, "s": 27940, "text": null }, { "code": null, "e": 28221, "s": 27987, "text": "After this, we select the optimizer and the loss criteria. Here, we will use the mean squared error (MSE) as our loss function and stochastic gradient descent (SGD) as our optimizer. Also, we arbitrarily fix a learning rate of 0.01. " }, { "code": null, "e": 28229, "s": 28221, "text": "Python3" }, { "code": "criterion = torch.nn.MSELoss(size_average = False)optimizer = torch.optim.SGD(our_model.parameters(), lr = 0.01)", "e": 28342, "s": 28229, "text": null }, { "code": null, "e": 28438, "s": 28342, "text": "We now arrive at our training step. We perform the following tasks 500 times during training: " }, { "code": null, "e": 28634, "s": 28438, "text": "Perform a forward pass bypassing our data and finding out the predicted value of y.Compute the loss using MSE.Reset all the gradients to 0, perform a backpropagation and then, update the weights." }, { "code": null, "e": 28718, "s": 28634, "text": "Perform a forward pass bypassing our data and finding out the predicted value of y." }, { "code": null, "e": 28746, "s": 28718, "text": "Compute the loss using MSE." }, { "code": null, "e": 28832, "s": 28746, "text": "Reset all the gradients to 0, perform a backpropagation and then, update the weights." }, { "code": null, "e": 28842, "s": 28834, "text": "Python3" }, { "code": "for epoch in range(500): # Forward pass: Compute predicted y by passing # x to the model pred_y = our_model(x_data) # Compute and print loss loss = criterion(pred_y, y_data) # Zero gradients, perform a backward pass, # and update the weights. optimizer.zero_grad() loss.backward() optimizer.step() print('epoch {}, loss {}'.format(epoch, loss.item()))", "e": 29230, "s": 28842, "text": null }, { "code": null, "e": 29405, "s": 29230, "text": "Once the training is completed, we test if we are getting correct results using the model that we defined. So, we test it for an unknown value of x_data, in this case, 4.0. " }, { "code": null, "e": 29413, "s": 29405, "text": "Python3" }, { "code": "new_var = Variable(torch.Tensor([[4.0]]))pred_y = our_model(new_var)print(\"predict (after training)\", 4, our_model(new_var).item())", "e": 29545, "s": 29413, "text": null }, { "code": null, "e": 29928, "s": 29545, "text": "If you performed all steps correctly, you will see that for input 4.0, you are getting a value that is very close to 8.0 as below. So, our model inherently learns the relationship between the input data and the output data without being programmed explicitly.predict (after training) 4 7.966438293457031For your reference, you can find the entire code of this article given below: " }, { "code": null, "e": 29936, "s": 29928, "text": "Python3" }, { "code": "import torchfrom torch.autograd import Variable x_data = Variable(torch.Tensor([[1.0], [2.0], [3.0]]))y_data = Variable(torch.Tensor([[2.0], [4.0], [6.0]])) class LinearRegressionModel(torch.nn.Module): def __init__(self): super(LinearRegressionModel, self).__init__() self.linear = torch.nn.Linear(1, 1) # One in and one out def forward(self, x): y_pred = self.linear(x) return y_pred # our modelour_model = LinearRegressionModel() criterion = torch.nn.MSELoss(size_average = False)optimizer = torch.optim.SGD(our_model.parameters(), lr = 0.01) for epoch in range(500): # Forward pass: Compute predicted y by passing # x to the model pred_y = our_model(x_data) # Compute and print loss loss = criterion(pred_y, y_data) # Zero gradients, perform a backward pass, # and update the weights. optimizer.zero_grad() loss.backward() optimizer.step() print('epoch {}, loss {}'.format(epoch, loss.item())) new_var = Variable(torch.Tensor([[4.0]]))pred_y = our_model(new_var)print(\"predict (after training)\", 4, our_model(new_var).item())", "e": 31040, "s": 29936, "text": null }, { "code": null, "e": 31057, "s": 31040, "text": "PyTorchZeroToAll" }, { "code": null, "e": 31077, "s": 31057, "text": "Penn State STAT 501" }, { "code": null, "e": 31090, "s": 31077, "text": "davidbrear04" }, { "code": null, "e": 31102, "s": 31090, "text": "anikakapoor" }, { "code": null, "e": 31121, "s": 31102, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 31147, "s": 31121, "text": "Advanced Computer Subject" }, { "code": null, "e": 31164, "s": 31147, "text": "Machine Learning" }, { "code": null, "e": 31171, "s": 31164, "text": "Python" }, { "code": null, "e": 31188, "s": 31171, "text": "Machine Learning" }, { "code": null, "e": 31286, "s": 31188, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31300, "s": 31286, "text": "Decision Tree" }, { "code": null, "e": 31323, "s": 31300, "text": "System Design Tutorial" }, { "code": null, "e": 31363, "s": 31323, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 31401, "s": 31363, "text": "Python | Decision tree implementation" }, { "code": null, "e": 31445, "s": 31401, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 31459, "s": 31445, "text": "Decision Tree" }, { "code": null, "e": 31493, "s": 31459, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 31533, "s": 31493, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 31573, "s": 31533, "text": "Decision Tree Introduction with example" } ]
Maximum execution time taken by a PHP Script - GeeksforGeeks
25 Jan, 2022 One important aspect of PHP programs is that the maximum time taken to execute a script is 30 seconds. The time limit varies depending on the hosting companies but the maximum execution time is between 30 to 60 seconds. The user may get errors of maximum time limit exceeds due to some heavy import or export of files or program which involves sending mail to many recipients. To avoid the situation, you need to increase the execution time limit.This article describes how to change or control the maximum execution time of a PHP script.Prerequisite required: You have already a custom php.ini file set up in your application or a request has to be done to the owner who maintains it. If some of the PHP scripts take longer time then the server stops and throws an error: Fatal error: Maximum execution time of..seconds exceeded in this_file.php on line... To avoid this situation, you can change the max_execution_time directive in php.ini configuration file. Let us look at the ways by which we can set time for script execution in PHP. These are listed below: Search for max_execution_time directive in the php.ini file and edit the value of it, as required by the PHP script. ; Maximum execution time of each script, in seconds ; http://php.net/max-execution-time ; Note: This directive is hardcoded to 0 for the CLI SAPI max_execution_time = 4000 The default value of the directive is changed as required. Note: We have to restart the web-server, once the changes are done in the configuration file. By this setting, the configuration is made global to all PHP scripts. Changes done to this file in an incorrect way can create problems to the web-server or live projects. Use PHP inbuilt function set_time_limit(seconds) where seconds is the argument passed which is the time limit in seconds. It is used, when the user changes the setting outside the php.ini file. The function is called within your own PHP code. Use set_time_limit(0) when the safe mode is off.Note: If the function is called at the very start of the program, then the value passed to the function will be the time limit for the execution of the script. Otherwise, if the function is called in the middle of the code, then the partial script is executed and then for the rest of the script, the time limit is applied. Use PHP inbuilt function ini_set(option, value) where the parameters are the given configuration option and the value to be set. php // The program is executed for 3mns.<?phpini_set('max_execution_time', 180);?> It is used when you need to override the configuration value at run-time. This function is called from your own PHP code and will only affect the script which calls this function. Use init_set(‘max_execution_time’0) when you want to set unlimited execution time for the script.Note: Use init_set() function when the safe mode is off. php <?php// Sets to unlimited period of timeini_set('max_execution_time', 0);?> Note: This function with ‘0’ as a parameter is not a good programming practice but can be used for developing and testing purpose. Before the code is moved to live or production mode, make sure the settings are revoked. For allowing to run the script forever and ignore user aborts, set PHP inbuilt function ignore_user_abort(true). By default, it set to False which throws fatal error when client aborts to stop the script. php <?phpignore_user_abort();?> Use php_value command to change the settings in Apache configuration files and .htaccess files. Syntax: php_value name value This sets the value for that particular directive as specified. php_value max_execution_time 200 Use of cPanel configuration setting options for changing the execution time of a script. This can be done in cPanel’s dashboard and can be used for setting the time limit for PHP script. adnanirshad158 PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PHP | MySQL ( Creating Database ) How to Insert Form Data into Database using PHP ? Advantages and Disadvantages of PHP Create a drop-down list that options fetched from a MySQL database in PHP Best way to initialize empty array in PHP How to call PHP function on the click of a Button ? How to Insert Form Data into Database using PHP ? Best way to initialize empty array in PHP Comparing two dates in PHP How to Encrypt and Decrypt a PHP String ?
[ { "code": null, "e": 26153, "s": 26125, "text": "\n25 Jan, 2022" }, { "code": null, "e": 26927, "s": 26153, "text": "One important aspect of PHP programs is that the maximum time taken to execute a script is 30 seconds. The time limit varies depending on the hosting companies but the maximum execution time is between 30 to 60 seconds. The user may get errors of maximum time limit exceeds due to some heavy import or export of files or program which involves sending mail to many recipients. To avoid the situation, you need to increase the execution time limit.This article describes how to change or control the maximum execution time of a PHP script.Prerequisite required: You have already a custom php.ini file set up in your application or a request has to be done to the owner who maintains it. If some of the PHP scripts take longer time then the server stops and throws an error: " }, { "code": null, "e": 27012, "s": 26927, "text": "Fatal error: Maximum execution time of..seconds exceeded in this_file.php on line..." }, { "code": null, "e": 27219, "s": 27012, "text": "To avoid this situation, you can change the max_execution_time directive in php.ini configuration file. Let us look at the ways by which we can set time for script execution in PHP. These are listed below: " }, { "code": null, "e": 27337, "s": 27219, "text": "Search for max_execution_time directive in the php.ini file and edit the value of it, as required by the PHP script. " }, { "code": null, "e": 27509, "s": 27337, "text": "; Maximum execution time of each script, in seconds\n; http://php.net/max-execution-time\n; Note: This directive is hardcoded to 0 for the CLI SAPI\nmax_execution_time = 4000" }, { "code": null, "e": 27569, "s": 27509, "text": "The default value of the directive is changed as required. " }, { "code": null, "e": 27835, "s": 27569, "text": "Note: We have to restart the web-server, once the changes are done in the configuration file. By this setting, the configuration is made global to all PHP scripts. Changes done to this file in an incorrect way can create problems to the web-server or live projects." }, { "code": null, "e": 28450, "s": 27835, "text": "Use PHP inbuilt function set_time_limit(seconds) where seconds is the argument passed which is the time limit in seconds. It is used, when the user changes the setting outside the php.ini file. The function is called within your own PHP code. Use set_time_limit(0) when the safe mode is off.Note: If the function is called at the very start of the program, then the value passed to the function will be the time limit for the execution of the script. Otherwise, if the function is called in the middle of the code, then the partial script is executed and then for the rest of the script, the time limit is applied." }, { "code": null, "e": 28580, "s": 28450, "text": "Use PHP inbuilt function ini_set(option, value) where the parameters are the given configuration option and the value to be set. " }, { "code": null, "e": 28584, "s": 28580, "text": "php" }, { "code": "// The program is executed for 3mns.<?phpini_set('max_execution_time', 180);?>", "e": 28663, "s": 28584, "text": null }, { "code": null, "e": 28998, "s": 28663, "text": "It is used when you need to override the configuration value at run-time. This function is called from your own PHP code and will only affect the script which calls this function. Use init_set(‘max_execution_time’0) when you want to set unlimited execution time for the script.Note: Use init_set() function when the safe mode is off. " }, { "code": null, "e": 29002, "s": 28998, "text": "php" }, { "code": "<?php// Sets to unlimited period of timeini_set('max_execution_time', 0);?>", "e": 29078, "s": 29002, "text": null }, { "code": null, "e": 29298, "s": 29078, "text": "Note: This function with ‘0’ as a parameter is not a good programming practice but can be used for developing and testing purpose. Before the code is moved to live or production mode, make sure the settings are revoked." }, { "code": null, "e": 29504, "s": 29298, "text": "For allowing to run the script forever and ignore user aborts, set PHP inbuilt function ignore_user_abort(true). By default, it set to False which throws fatal error when client aborts to stop the script. " }, { "code": null, "e": 29508, "s": 29504, "text": "php" }, { "code": "<?phpignore_user_abort();?>", "e": 29536, "s": 29508, "text": null }, { "code": null, "e": 29641, "s": 29536, "text": "Use php_value command to change the settings in Apache configuration files and .htaccess files. Syntax: " }, { "code": null, "e": 29662, "s": 29641, "text": "php_value name value" }, { "code": null, "e": 29727, "s": 29662, "text": "This sets the value for that particular directive as specified. " }, { "code": null, "e": 29760, "s": 29727, "text": "php_value max_execution_time 200" }, { "code": null, "e": 29947, "s": 29760, "text": "Use of cPanel configuration setting options for changing the execution time of a script. This can be done in cPanel’s dashboard and can be used for setting the time limit for PHP script." }, { "code": null, "e": 29962, "s": 29947, "text": "adnanirshad158" }, { "code": null, "e": 29966, "s": 29962, "text": "PHP" }, { "code": null, "e": 29979, "s": 29966, "text": "PHP Programs" }, { "code": null, "e": 29996, "s": 29979, "text": "Web Technologies" }, { "code": null, "e": 30023, "s": 29996, "text": "Web technologies Questions" }, { "code": null, "e": 30027, "s": 30023, "text": "PHP" }, { "code": null, "e": 30125, "s": 30027, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30159, "s": 30125, "text": "PHP | MySQL ( Creating Database )" }, { "code": null, "e": 30209, "s": 30159, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 30245, "s": 30209, "text": "Advantages and Disadvantages of PHP" }, { "code": null, "e": 30319, "s": 30245, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 30361, "s": 30319, "text": "Best way to initialize empty array in PHP" }, { "code": null, "e": 30413, "s": 30361, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 30463, "s": 30413, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 30505, "s": 30463, "text": "Best way to initialize empty array in PHP" }, { "code": null, "e": 30532, "s": 30505, "text": "Comparing two dates in PHP" } ]
5 Must-Know Terms in Time Series Analysis | by Soner Yıldırım | Towards Data Science
A time series is a sequence of observations or measurements ordered in time. The first picture that comes to mind when talking about time series is usually stock prices. However, time series are ubiquitous. Yearly rainfall amounts in a geographical location, the daily sales amount of a product in a supermarket, monthly power consumption of a factory, hourly measurements of a chemical process are all examples of time series. Time series analysis is a fundamental area in data science and has a wide range of applications. If you become an expert in this area, your chance of getting a data scientist job might increase dramatically. In this article, we will go over 5 must-know terms and concepts in time series analysis. It is better to start our discussion by distinguishing between deterministic and stochastic processes. The time-dependent values in a deterministic process can be calculated. For instance, how much you will have in your savings account in two years can be calculated using the initial deposited amount and the interest rate. We can’t really talk about randomness in deterministic processes. On the other hand, stochastic processes are based on randomness. We cannot calculate the future values in a stochastic process but we can talk about the probability of future values being in a range. There is a 90% chance that the rainfall amount in California in 2022 will be 21 inches. My assumption is based on the probability distribution of rainfall amounts in California and there is, of course, randomness associated with my assumption. In this sense, a stochastic process can be considered as a collection of random variables ordered in time. Then, a time series is a realization of a stochastic process. We have just defined time series as a realization of a stochastic process. Stationarity means that the statistical properties of the process that generates the time series do not change over time. In a stationary time series, we cannot observe a systematic change in mean or variance. Consider we take two intervals from a stationary time series as below: N observations from time t to time t + N Another N observations from time t + k to t + N + k The statistical properties of these two intervals are much alike. There is no systematic difference between the mean or variation between these two intervals. Thus, a stationary time series does not possess Seasonality Trend Periodic fluctuations The following figure shows a stationary time series. The values might be generated by a random noise but we do not observe a trend or seasonality. The following figure shows a non-stationary time series. We can clearly observe the increasing trend. We should first understand what covariance means. Covariance is a measure of linear dependence between two random variables. It compares two random variables with respect to the deviations from their mean (or expected) value. The formula of the covariance between random variables X and Y: If the values of X and Y change in the same direction (i.e. they both increase or decrease), the covariance between them will be positive. I tried to explain the covariance and correlation in more detail if you’d like to learn more: medium.com Going back to our discussion on autocovariance, recall that time series is a realization of a stochastic process that can be defined as a sequence of random variables (X1, X2, X3, ...). Assuming we have a stationary time series, let’s take two random variables from this time series: Xt Xt + k The k is the time difference between these two random variables. The autocovariance function between these two random variables is: The autocovariance function only depends on the time difference (i.e. value of k) because we assume stationarity. The properties of a stationary time series do not change when it is shifted in time. The ck is the estimation of the autocovariance function at lag k. In other words, the properties of the following parts of this time series are the same. From Xt to Xt + k From Xt + n to Xt + n + k We now have an understanding of the autocovariance function. The next step is the autocovariance coefficients which are of great importance in time series analysis. Autocovariance coefficients at different time lags are defined as: The autocovariance function cannot be computed exactly for a finite time series so we calculate an estimation, ck, as follows: The value x-bar is the sample average. Consider we want to calculate the autocovariance coefficient for lag 5 of a time series with 50 values (k=5 and N=50). The numerator of the above equation is calculated for X1 vs X6, X2 vs X7, ..., X40 vs X45. We then take the sum of all the combinations and divide by 50. We can easily calculate the autocovariance coefficients in R using the acf routine. Let’s first create a random time series with 50 values. random_time_series <- ts(rnorm(50))plot(random_time_series) We can calculate the autocovariance coefficients as follows: acf(random_time_series, type="covariance") The values of autocovariance coefficients depend on the values in the time series. There is no standard between the autocovariance coefficients of different time series. What we can use instead is the autocorrelation function (ACF). The autocorrelation coefficient at lag k can be calculated as follows. We divide the autocovariance coefficient at lag k by the autocovariance coefficient at lag 0. Similarly, the estimation of the autocorrelation coefficient can be calculated as follows: The value of an autocorrelation coefficient is always between -1 and 1. In R, we can use the acf routine to calculate the autocorrelation coefficients as well. acf(random_time_series) The autocorrelation coefficients always start with 1 because C0 / C0 is equal to 1. The dashed blue lines represent the significance levels. As we observe in the plot, the correlation values between different time lags are very low because we generated this data randomly. The ACF plot is also called correlogram. Time series analysis is widely used in data science. We have made an introduction to time series analysis by covering 5 fundamental terms and concepts. There is, of course, much more to cover in this area since time-series data has its own dynamics and requires specific techniques for analysis. You can become a Medium member to unlock full access to my writing, plus the rest of Medium. If you do so using the following link, I will receive a portion of your membership fee at no additional cost to you. sonery.medium.com Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 379, "s": 172, "text": "A time series is a sequence of observations or measurements ordered in time. The first picture that comes to mind when talking about time series is usually stock prices. However, time series are ubiquitous." }, { "code": null, "e": 600, "s": 379, "text": "Yearly rainfall amounts in a geographical location, the daily sales amount of a product in a supermarket, monthly power consumption of a factory, hourly measurements of a chemical process are all examples of time series." }, { "code": null, "e": 808, "s": 600, "text": "Time series analysis is a fundamental area in data science and has a wide range of applications. If you become an expert in this area, your chance of getting a data scientist job might increase dramatically." }, { "code": null, "e": 897, "s": 808, "text": "In this article, we will go over 5 must-know terms and concepts in time series analysis." }, { "code": null, "e": 1000, "s": 897, "text": "It is better to start our discussion by distinguishing between deterministic and stochastic processes." }, { "code": null, "e": 1288, "s": 1000, "text": "The time-dependent values in a deterministic process can be calculated. For instance, how much you will have in your savings account in two years can be calculated using the initial deposited amount and the interest rate. We can’t really talk about randomness in deterministic processes." }, { "code": null, "e": 1488, "s": 1288, "text": "On the other hand, stochastic processes are based on randomness. We cannot calculate the future values in a stochastic process but we can talk about the probability of future values being in a range." }, { "code": null, "e": 1732, "s": 1488, "text": "There is a 90% chance that the rainfall amount in California in 2022 will be 21 inches. My assumption is based on the probability distribution of rainfall amounts in California and there is, of course, randomness associated with my assumption." }, { "code": null, "e": 1901, "s": 1732, "text": "In this sense, a stochastic process can be considered as a collection of random variables ordered in time. Then, a time series is a realization of a stochastic process." }, { "code": null, "e": 2098, "s": 1901, "text": "We have just defined time series as a realization of a stochastic process. Stationarity means that the statistical properties of the process that generates the time series do not change over time." }, { "code": null, "e": 2257, "s": 2098, "text": "In a stationary time series, we cannot observe a systematic change in mean or variance. Consider we take two intervals from a stationary time series as below:" }, { "code": null, "e": 2298, "s": 2257, "text": "N observations from time t to time t + N" }, { "code": null, "e": 2350, "s": 2298, "text": "Another N observations from time t + k to t + N + k" }, { "code": null, "e": 2509, "s": 2350, "text": "The statistical properties of these two intervals are much alike. There is no systematic difference between the mean or variation between these two intervals." }, { "code": null, "e": 2557, "s": 2509, "text": "Thus, a stationary time series does not possess" }, { "code": null, "e": 2569, "s": 2557, "text": "Seasonality" }, { "code": null, "e": 2575, "s": 2569, "text": "Trend" }, { "code": null, "e": 2597, "s": 2575, "text": "Periodic fluctuations" }, { "code": null, "e": 2744, "s": 2597, "text": "The following figure shows a stationary time series. The values might be generated by a random noise but we do not observe a trend or seasonality." }, { "code": null, "e": 2846, "s": 2744, "text": "The following figure shows a non-stationary time series. We can clearly observe the increasing trend." }, { "code": null, "e": 2896, "s": 2846, "text": "We should first understand what covariance means." }, { "code": null, "e": 3072, "s": 2896, "text": "Covariance is a measure of linear dependence between two random variables. It compares two random variables with respect to the deviations from their mean (or expected) value." }, { "code": null, "e": 3136, "s": 3072, "text": "The formula of the covariance between random variables X and Y:" }, { "code": null, "e": 3275, "s": 3136, "text": "If the values of X and Y change in the same direction (i.e. they both increase or decrease), the covariance between them will be positive." }, { "code": null, "e": 3369, "s": 3275, "text": "I tried to explain the covariance and correlation in more detail if you’d like to learn more:" }, { "code": null, "e": 3380, "s": 3369, "text": "medium.com" }, { "code": null, "e": 3566, "s": 3380, "text": "Going back to our discussion on autocovariance, recall that time series is a realization of a stochastic process that can be defined as a sequence of random variables (X1, X2, X3, ...)." }, { "code": null, "e": 3664, "s": 3566, "text": "Assuming we have a stationary time series, let’s take two random variables from this time series:" }, { "code": null, "e": 3667, "s": 3664, "text": "Xt" }, { "code": null, "e": 3674, "s": 3667, "text": "Xt + k" }, { "code": null, "e": 3806, "s": 3674, "text": "The k is the time difference between these two random variables. The autocovariance function between these two random variables is:" }, { "code": null, "e": 4005, "s": 3806, "text": "The autocovariance function only depends on the time difference (i.e. value of k) because we assume stationarity. The properties of a stationary time series do not change when it is shifted in time." }, { "code": null, "e": 4071, "s": 4005, "text": "The ck is the estimation of the autocovariance function at lag k." }, { "code": null, "e": 4159, "s": 4071, "text": "In other words, the properties of the following parts of this time series are the same." }, { "code": null, "e": 4177, "s": 4159, "text": "From Xt to Xt + k" }, { "code": null, "e": 4203, "s": 4177, "text": "From Xt + n to Xt + n + k" }, { "code": null, "e": 4368, "s": 4203, "text": "We now have an understanding of the autocovariance function. The next step is the autocovariance coefficients which are of great importance in time series analysis." }, { "code": null, "e": 4435, "s": 4368, "text": "Autocovariance coefficients at different time lags are defined as:" }, { "code": null, "e": 4562, "s": 4435, "text": "The autocovariance function cannot be computed exactly for a finite time series so we calculate an estimation, ck, as follows:" }, { "code": null, "e": 4601, "s": 4562, "text": "The value x-bar is the sample average." }, { "code": null, "e": 4720, "s": 4601, "text": "Consider we want to calculate the autocovariance coefficient for lag 5 of a time series with 50 values (k=5 and N=50)." }, { "code": null, "e": 4874, "s": 4720, "text": "The numerator of the above equation is calculated for X1 vs X6, X2 vs X7, ..., X40 vs X45. We then take the sum of all the combinations and divide by 50." }, { "code": null, "e": 4958, "s": 4874, "text": "We can easily calculate the autocovariance coefficients in R using the acf routine." }, { "code": null, "e": 5014, "s": 4958, "text": "Let’s first create a random time series with 50 values." }, { "code": null, "e": 5074, "s": 5014, "text": "random_time_series <- ts(rnorm(50))plot(random_time_series)" }, { "code": null, "e": 5135, "s": 5074, "text": "We can calculate the autocovariance coefficients as follows:" }, { "code": null, "e": 5178, "s": 5135, "text": "acf(random_time_series, type=\"covariance\")" }, { "code": null, "e": 5348, "s": 5178, "text": "The values of autocovariance coefficients depend on the values in the time series. There is no standard between the autocovariance coefficients of different time series." }, { "code": null, "e": 5482, "s": 5348, "text": "What we can use instead is the autocorrelation function (ACF). The autocorrelation coefficient at lag k can be calculated as follows." }, { "code": null, "e": 5576, "s": 5482, "text": "We divide the autocovariance coefficient at lag k by the autocovariance coefficient at lag 0." }, { "code": null, "e": 5667, "s": 5576, "text": "Similarly, the estimation of the autocorrelation coefficient can be calculated as follows:" }, { "code": null, "e": 5739, "s": 5667, "text": "The value of an autocorrelation coefficient is always between -1 and 1." }, { "code": null, "e": 5827, "s": 5739, "text": "In R, we can use the acf routine to calculate the autocorrelation coefficients as well." }, { "code": null, "e": 5851, "s": 5827, "text": "acf(random_time_series)" }, { "code": null, "e": 5935, "s": 5851, "text": "The autocorrelation coefficients always start with 1 because C0 / C0 is equal to 1." }, { "code": null, "e": 6124, "s": 5935, "text": "The dashed blue lines represent the significance levels. As we observe in the plot, the correlation values between different time lags are very low because we generated this data randomly." }, { "code": null, "e": 6165, "s": 6124, "text": "The ACF plot is also called correlogram." }, { "code": null, "e": 6317, "s": 6165, "text": "Time series analysis is widely used in data science. We have made an introduction to time series analysis by covering 5 fundamental terms and concepts." }, { "code": null, "e": 6461, "s": 6317, "text": "There is, of course, much more to cover in this area since time-series data has its own dynamics and requires specific techniques for analysis." }, { "code": null, "e": 6671, "s": 6461, "text": "You can become a Medium member to unlock full access to my writing, plus the rest of Medium. If you do so using the following link, I will receive a portion of your membership fee at no additional cost to you." }, { "code": null, "e": 6689, "s": 6671, "text": "sonery.medium.com" } ]
How to copy readonly and hidden files/folders in the PowerShell?
To copy the readonly and hidden items from one location to another, you need to use the –Force parameter with Copy-Item cmdlet. When you run the command without Force parameter for the readonly/hidden files, you will get the error. An example is given below. Copy-Item D:\Temp\Readonlyfile.txt -Destination D:\TempContent\ PS C:\WINDOWS\system32> Copy-Item D:\Temp\Readonlyfile.txt -Destination D:\TempContent\ Copy-Item : Access to the path 'D:\TempContent\Readonlyfile.txt' is denied. At line:1 char:1 + Copy-Item D:\Temp\Readonlyfile.txt -Destination D:\TempContent\ + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (D:\Temp\Readonlyfile.txt:FileInfo) [Copy-Item], UnauthorizedAccessException + FullyQualifiedErrorId : CopyFileInfoItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand When you add the –Force parameter in the cmdlet, it can copy the readonly/ hidden files as well. An example is given below for the readonly file. Copy-Item D:\Temp\Readonlyfile.txt -Destination D:\TempContent\ -Force -PassThru PS C:\WINDOWS\system32> Copy-Item D:\Temp\Readonlyfile.txt -Destination D:\TempContent\ -Force -PassThru Directory: D:\TempContent Mode LastWriteTime Length Name ---- ------------- ------ ---- -ar--- 13-01-2020 18:19 0 Readonlyfile.txt The below example is for the Hidden file. Copy-Item D:\Temp\hiddenfile.xlsx -Destination D:\TempContent\ -Force -PassThru PS C:\WINDOWS\system32> Copy-Item D:\Temp\hiddenfile.xlsx -Destination D:\TempContent\ -Force -PassThru Directory: D:\TempContent Mode LastWriteTime Length Name ---- ------------- ------ ---- -a-h-- 13-12-2019 09:52 6182 hiddenfile.xlsx
[ { "code": null, "e": 1190, "s": 1062, "text": "To copy the readonly and hidden items from one location to another, you need to use the –Force parameter with Copy-Item cmdlet." }, { "code": null, "e": 1321, "s": 1190, "text": "When you run the command without Force parameter for the readonly/hidden files, you will get the error. An example is given below." }, { "code": null, "e": 1385, "s": 1321, "text": "Copy-Item D:\\Temp\\Readonlyfile.txt -Destination D:\\TempContent\\" }, { "code": null, "e": 1928, "s": 1385, "text": "PS C:\\WINDOWS\\system32> Copy-Item D:\\Temp\\Readonlyfile.txt -Destination D:\\TempContent\\\nCopy-Item : Access to the path 'D:\\TempContent\\Readonlyfile.txt' is denied.\nAt line:1 char:1\n+ Copy-Item D:\\Temp\\Readonlyfile.txt -Destination D:\\TempContent\\\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n + CategoryInfo : PermissionDenied: (D:\\Temp\\Readonlyfile.txt:FileInfo) [Copy-Item], UnauthorizedAccessException\n + FullyQualifiedErrorId : CopyFileInfoItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand" }, { "code": null, "e": 2025, "s": 1928, "text": "When you add the –Force parameter in the cmdlet, it can copy the readonly/ hidden files as well." }, { "code": null, "e": 2074, "s": 2025, "text": "An example is given below for the readonly file." }, { "code": null, "e": 2155, "s": 2074, "text": "Copy-Item D:\\Temp\\Readonlyfile.txt -Destination D:\\TempContent\\ -Force -PassThru" }, { "code": null, "e": 2464, "s": 2155, "text": "PS C:\\WINDOWS\\system32> Copy-Item D:\\Temp\\Readonlyfile.txt -Destination D:\\TempContent\\ -Force -PassThru\n Directory: D:\\TempContent\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-ar--- 13-01-2020 18:19 0 Readonlyfile.txt" }, { "code": null, "e": 2506, "s": 2464, "text": "The below example is for the Hidden file." }, { "code": null, "e": 2586, "s": 2506, "text": "Copy-Item D:\\Temp\\hiddenfile.xlsx -Destination D:\\TempContent\\ -Force -PassThru" }, { "code": null, "e": 2893, "s": 2586, "text": "PS C:\\WINDOWS\\system32> Copy-Item D:\\Temp\\hiddenfile.xlsx -Destination D:\\TempContent\\ -Force -PassThru\n Directory: D:\\TempContent\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a-h-- 13-12-2019 09:52 6182 hiddenfile.xlsx" } ]
Learn Enough Python to be Useful: argparse | by Jeff Hale | Towards Data Science
If you plan to be a software developer with Python, you’ll want to be able to use argparse for your scripting needs. If you’re a data scientist, you’ll likely find yourself needing to port your code from a Jupyter Notebook to a reproducible script. For many newer data scientists this can be a step from a comfortable, happy place into scary land. This guide is designed to make the leap less scary. argparse is the “recommended command-line parsing module in the Python standard library.” It’s what you use to get command line arguments into your program. I couldn’t find a good intro guide for argparse when I needed one, so I wrote this article. Enjoy! The first time I saw argparse in a Python script for a side project I thought, “What is this voodo magic?” And quickly moved the code into a Jupyter Notebook. This move turned out to be suboptimal. 😦 I wanted to be able to run a script rather than have to step through a Jupyter Notebook. A script with argparse would have been much simpler to use and much less work. Unfortunately, I was in a hurry and didn’t find the docs easy to grasp. Since then, I’ve come to understand and enjoy argparse. It’s indispensable. Here’s what you need to know. argparse — parse the arguments. Using argparse is how you let the user of your program provide values for variables at runtime. It’s a means of communication between the writer of a program and the user. That user might be your future self. 😃 Using argparse means the doesn’t need to go into the code and make changes to the script. Giving the user the ability to enter command line arguments provides flexibility. Say you have a directory with videos in it and want to turn those videos into images using the OpenCV library. You could use argparse so the user can enter input and output directories. Here’s what the argparse section of your videos.py file looks like: # videos.pyimport argparseparser = argparse.ArgumentParser(description='Videos to images')parser.add_argument('indir', type=str, help='Input dir for videos')parser.add_argument('outdir', type=str, help='Output dir for image')args = parser.parse_args()print(args.indir) This file imports the argparse library. Then it makes a parser object with a description. Then the variable indir is created using parser.add_argument(). The type of the variable is set to string and a help message is provided. Then the same is done for outdir. Next the args variable is set to the values of the parsed arguments. Now the following command can be run from the command line: python videos.py /videos /images Note that quotes do not need to be placed around the values /videos and /images when you pass them. "/videos" becomes the value for args.indir and "/images" becomes the value for args.outdir. The output printed to the terminal is /videos. We just showed that you can use the args.indir variable anywhere in your program. How cool is that? You’ve now seen the magic of argparse! parser.add_argument('indir', type=str, help='Input dir for videos') created a positional argument. For positional arguments to a Python function, the order matters. The first value passed from the command line becomes the first positional argument. The second value passed becomes the second positional argument. What happens if you exclude these positional arguments and try to run python videos.py? You’ll get an error: videos.py: error: the following arguments are required: indir, outdir. Positional arguments are always required to be passed in the command to run the script. What happens if you run python videos.py --help? You get the helpful information we put into our script to tell you what you need to do. Excellent! help is an example of an optional argument. Note that --help is the only optional argument you get for free, but you can make more. Optional arguments are created just like positional arguments except that they have a '--' double dash at the start of their name (or a'-' single dash and one additional character for the short version). For example, you can create an optional argument with parser.add_argument('-m', '--my_optional'). The following larger example shows how to create and reference an optional argument. Note that we specify the type int for an integer in this example. You could also specify other valid Python variable types. # my_example.pyimport argparseparser = argparse.ArgumentParser(description='My example explanation')parser.add_argument( '--my_optional', default=2, help='provide an integer (default: 2)')my_namespace = parser.parse_args()print(my_namespace.my_optional) Note that the argument specified with '--my_optional' becomes this namespaced variable without the dashes: 'my_namespace.my_optional'. Also note that the optional argument can have a default value. Here we specify a default of 2. Running python my_example.py outputs 2. The optional argument value can be set at run time from the command line like this: python my_example.py--my_optional=3. The program then outputs 3. You can do even more with argparse. For example, you can have arguments gathered into lists with nargs='*’. You can also check for ranges of values with choices. See the argparse docs for all you can do. You can also use argparse with programs running in Docker containers. If you want to pass command line arguments to your scripts when building your image you can do so with RUN. If you want to pass arguments to your script at run time you can do so with CMD or ENTRYPOINT. Learn more about Dockerfiles in my series on Docker: towardsdatascience.com Now you’ve seen the basics of argparse. You’ve seen how to get positional and optional arguments into your programs from the command line. You’ve also seen how to set default optional arguments. If you want to go deeper, check out the official docs. Update Mar. 6, 2019 I should mention that there are a number of packages available to add command line arguments to your program. Readers have suggested several in the comments, the most popular of which I’ve linked to here: click fire docopt Here are a few more suggestions to help you step out of the Jupyter Notebook. Environment variables are useful variables that get set outside a program. Here’s a nice, clear intro. This article from DataCamp blog focuses on the PATH variable. You can convert repos with Jupyter notebooks into Docker Images with Repo2Docker. Will Koehrsen wrote a good guide on the tool here. I plan to write more articles about interacting with the file system and scripting. Follow me to make sure you don’t miss them! 😃 I hope you found this intro useful. If you did, share it on your favorite forums and social media. Data scientists and programmers who don’t know argparse will thank you! I write about data science, cloud computing, and other tech stuff. Follow me and read more here. Thanks for reading!👏
[ { "code": null, "e": 571, "s": 171, "text": "If you plan to be a software developer with Python, you’ll want to be able to use argparse for your scripting needs. If you’re a data scientist, you’ll likely find yourself needing to port your code from a Jupyter Notebook to a reproducible script. For many newer data scientists this can be a step from a comfortable, happy place into scary land. This guide is designed to make the leap less scary." }, { "code": null, "e": 728, "s": 571, "text": "argparse is the “recommended command-line parsing module in the Python standard library.” It’s what you use to get command line arguments into your program." }, { "code": null, "e": 827, "s": 728, "text": "I couldn’t find a good intro guide for argparse when I needed one, so I wrote this article. Enjoy!" }, { "code": null, "e": 1027, "s": 827, "text": "The first time I saw argparse in a Python script for a side project I thought, “What is this voodo magic?” And quickly moved the code into a Jupyter Notebook. This move turned out to be suboptimal. 😦" }, { "code": null, "e": 1267, "s": 1027, "text": "I wanted to be able to run a script rather than have to step through a Jupyter Notebook. A script with argparse would have been much simpler to use and much less work. Unfortunately, I was in a hurry and didn’t find the docs easy to grasp." }, { "code": null, "e": 1343, "s": 1267, "text": "Since then, I’ve come to understand and enjoy argparse. It’s indispensable." }, { "code": null, "e": 1373, "s": 1343, "text": "Here’s what you need to know." }, { "code": null, "e": 1405, "s": 1373, "text": "argparse — parse the arguments." }, { "code": null, "e": 1616, "s": 1405, "text": "Using argparse is how you let the user of your program provide values for variables at runtime. It’s a means of communication between the writer of a program and the user. That user might be your future self. 😃" }, { "code": null, "e": 1788, "s": 1616, "text": "Using argparse means the doesn’t need to go into the code and make changes to the script. Giving the user the ability to enter command line arguments provides flexibility." }, { "code": null, "e": 2042, "s": 1788, "text": "Say you have a directory with videos in it and want to turn those videos into images using the OpenCV library. You could use argparse so the user can enter input and output directories. Here’s what the argparse section of your videos.py file looks like:" }, { "code": null, "e": 2311, "s": 2042, "text": "# videos.pyimport argparseparser = argparse.ArgumentParser(description='Videos to images')parser.add_argument('indir', type=str, help='Input dir for videos')parser.add_argument('outdir', type=str, help='Output dir for image')args = parser.parse_args()print(args.indir)" }, { "code": null, "e": 2642, "s": 2311, "text": "This file imports the argparse library. Then it makes a parser object with a description. Then the variable indir is created using parser.add_argument(). The type of the variable is set to string and a help message is provided. Then the same is done for outdir. Next the args variable is set to the values of the parsed arguments." }, { "code": null, "e": 2702, "s": 2642, "text": "Now the following command can be run from the command line:" }, { "code": null, "e": 2735, "s": 2702, "text": "python videos.py /videos /images" }, { "code": null, "e": 2835, "s": 2735, "text": "Note that quotes do not need to be placed around the values /videos and /images when you pass them." }, { "code": null, "e": 2927, "s": 2835, "text": "\"/videos\" becomes the value for args.indir and \"/images\" becomes the value for args.outdir." }, { "code": null, "e": 2974, "s": 2927, "text": "The output printed to the terminal is /videos." }, { "code": null, "e": 3074, "s": 2974, "text": "We just showed that you can use the args.indir variable anywhere in your program. How cool is that?" }, { "code": null, "e": 3113, "s": 3074, "text": "You’ve now seen the magic of argparse!" }, { "code": null, "e": 3426, "s": 3113, "text": "parser.add_argument('indir', type=str, help='Input dir for videos') created a positional argument. For positional arguments to a Python function, the order matters. The first value passed from the command line becomes the first positional argument. The second value passed becomes the second positional argument." }, { "code": null, "e": 3514, "s": 3426, "text": "What happens if you exclude these positional arguments and try to run python videos.py?" }, { "code": null, "e": 3694, "s": 3514, "text": "You’ll get an error: videos.py: error: the following arguments are required: indir, outdir. Positional arguments are always required to be passed in the command to run the script." }, { "code": null, "e": 3743, "s": 3694, "text": "What happens if you run python videos.py --help?" }, { "code": null, "e": 3831, "s": 3743, "text": "You get the helpful information we put into our script to tell you what you need to do." }, { "code": null, "e": 3974, "s": 3831, "text": "Excellent! help is an example of an optional argument. Note that --help is the only optional argument you get for free, but you can make more." }, { "code": null, "e": 4276, "s": 3974, "text": "Optional arguments are created just like positional arguments except that they have a '--' double dash at the start of their name (or a'-' single dash and one additional character for the short version). For example, you can create an optional argument with parser.add_argument('-m', '--my_optional')." }, { "code": null, "e": 4485, "s": 4276, "text": "The following larger example shows how to create and reference an optional argument. Note that we specify the type int for an integer in this example. You could also specify other valid Python variable types." }, { "code": null, "e": 4748, "s": 4485, "text": "# my_example.pyimport argparseparser = argparse.ArgumentParser(description='My example explanation')parser.add_argument( '--my_optional', default=2, help='provide an integer (default: 2)')my_namespace = parser.parse_args()print(my_namespace.my_optional)" }, { "code": null, "e": 4883, "s": 4748, "text": "Note that the argument specified with '--my_optional' becomes this namespaced variable without the dashes: 'my_namespace.my_optional'." }, { "code": null, "e": 5018, "s": 4883, "text": "Also note that the optional argument can have a default value. Here we specify a default of 2. Running python my_example.py outputs 2." }, { "code": null, "e": 5167, "s": 5018, "text": "The optional argument value can be set at run time from the command line like this: python my_example.py--my_optional=3. The program then outputs 3." }, { "code": null, "e": 5371, "s": 5167, "text": "You can do even more with argparse. For example, you can have arguments gathered into lists with nargs='*’. You can also check for ranges of values with choices. See the argparse docs for all you can do." }, { "code": null, "e": 5697, "s": 5371, "text": "You can also use argparse with programs running in Docker containers. If you want to pass command line arguments to your scripts when building your image you can do so with RUN. If you want to pass arguments to your script at run time you can do so with CMD or ENTRYPOINT. Learn more about Dockerfiles in my series on Docker:" }, { "code": null, "e": 5720, "s": 5697, "text": "towardsdatascience.com" }, { "code": null, "e": 5970, "s": 5720, "text": "Now you’ve seen the basics of argparse. You’ve seen how to get positional and optional arguments into your programs from the command line. You’ve also seen how to set default optional arguments. If you want to go deeper, check out the official docs." }, { "code": null, "e": 6195, "s": 5970, "text": "Update Mar. 6, 2019 I should mention that there are a number of packages available to add command line arguments to your program. Readers have suggested several in the comments, the most popular of which I’ve linked to here:" }, { "code": null, "e": 6201, "s": 6195, "text": "click" }, { "code": null, "e": 6206, "s": 6201, "text": "fire" }, { "code": null, "e": 6213, "s": 6206, "text": "docopt" }, { "code": null, "e": 6291, "s": 6213, "text": "Here are a few more suggestions to help you step out of the Jupyter Notebook." }, { "code": null, "e": 6456, "s": 6291, "text": "Environment variables are useful variables that get set outside a program. Here’s a nice, clear intro. This article from DataCamp blog focuses on the PATH variable." }, { "code": null, "e": 6589, "s": 6456, "text": "You can convert repos with Jupyter notebooks into Docker Images with Repo2Docker. Will Koehrsen wrote a good guide on the tool here." }, { "code": null, "e": 6719, "s": 6589, "text": "I plan to write more articles about interacting with the file system and scripting. Follow me to make sure you don’t miss them! 😃" }, { "code": null, "e": 6890, "s": 6719, "text": "I hope you found this intro useful. If you did, share it on your favorite forums and social media. Data scientists and programmers who don’t know argparse will thank you!" }, { "code": null, "e": 6987, "s": 6890, "text": "I write about data science, cloud computing, and other tech stuff. Follow me and read more here." } ]
Function Wrappers in Python - GeeksforGeeks
22 Jun, 2020 Wrappers around the functions are also knows as decorators which are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it. In Decorators, functions are taken as the argument into another function and then called inside the wrapper function. Syntax: @wrapper def function(n): statements(s) This is also similar to def function(n): statement(s) function = wrapper(function) Let’s see the below examples for better understanding.Example 1: # defining a decorator def hello_decorator(func): # inner1 is a Wrapper function in # which the argument is called # inner function can access the outer local # functions like in this case "func" def inner1(): print("Hello, this is before function execution") # calling the actual function now # inside the wrapper function. func() print("This is after function execution") return inner1 # defining a function, to be called inside wrapper def function_to_be_used(): print("This is inside the function !!") # passing 'function_to_be_used' inside the # decorator to control its behavior function_to_be_used = hello_decorator(function_to_be_used) # calling the function function_to_be_used() Output: Hello, this is before function execution This is inside the function !! This is after function execution Example 2: Let’s define a decorator that count the time taken by the function for execution. import time def timeis(func): '''Decorator that reports the execution time.''' def wrap(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(func.__name__, end-start) return result return wrap @timeisdef countdown(n): '''Counts down''' while n > 0: n -= 1 countdown(5)countdown(1000) Output: countdown 1.6689300537109375e-06 countdown 5.507469177246094e-05 It’s critical to emphasize that decorators generally do not alter the calling signature or return value of function being wrapped. The use of *args and**kwargs is there to make sure that any input arguments can be accepted. The return value of a decorator is almost always the result of calling func(*args, **kwargs), where func is the original unwrapped function. Please refer Decorators in Python for more details. Python Decorators Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python
[ { "code": null, "e": 24053, "s": 24025, "text": "\n22 Jun, 2020" }, { "code": null, "e": 24491, "s": 24053, "text": "Wrappers around the functions are also knows as decorators which are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it. In Decorators, functions are taken as the argument into another function and then called inside the wrapper function." }, { "code": null, "e": 24499, "s": 24491, "text": "Syntax:" }, { "code": null, "e": 24543, "s": 24499, "text": "@wrapper\ndef function(n):\n statements(s)" }, { "code": null, "e": 24567, "s": 24543, "text": "This is also similar to" }, { "code": null, "e": 24631, "s": 24567, "text": "def function(n):\n statement(s)\n\nfunction = wrapper(function)" }, { "code": null, "e": 24696, "s": 24631, "text": "Let’s see the below examples for better understanding.Example 1:" }, { "code": "# defining a decorator def hello_decorator(func): # inner1 is a Wrapper function in # which the argument is called # inner function can access the outer local # functions like in this case \"func\" def inner1(): print(\"Hello, this is before function execution\") # calling the actual function now # inside the wrapper function. func() print(\"This is after function execution\") return inner1 # defining a function, to be called inside wrapper def function_to_be_used(): print(\"This is inside the function !!\") # passing 'function_to_be_used' inside the # decorator to control its behavior function_to_be_used = hello_decorator(function_to_be_used) # calling the function function_to_be_used() ", "e": 25511, "s": 24696, "text": null }, { "code": null, "e": 25519, "s": 25511, "text": "Output:" }, { "code": null, "e": 25624, "s": 25519, "text": "Hello, this is before function execution\nThis is inside the function !!\nThis is after function execution" }, { "code": null, "e": 25717, "s": 25624, "text": "Example 2: Let’s define a decorator that count the time taken by the function for execution." }, { "code": "import time def timeis(func): '''Decorator that reports the execution time.''' def wrap(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(func.__name__, end-start) return result return wrap @timeisdef countdown(n): '''Counts down''' while n > 0: n -= 1 countdown(5)countdown(1000)", "e": 26115, "s": 25717, "text": null }, { "code": null, "e": 26123, "s": 26115, "text": "Output:" }, { "code": null, "e": 26188, "s": 26123, "text": "countdown 1.6689300537109375e-06\ncountdown 5.507469177246094e-05" }, { "code": null, "e": 26553, "s": 26188, "text": "It’s critical to emphasize that decorators generally do not alter the calling signature or return value of function being wrapped. The use of *args and**kwargs is there to make sure that any input arguments can be accepted. The return value of a decorator is almost always the result of calling func(*args, **kwargs), where func is the original unwrapped function." }, { "code": null, "e": 26605, "s": 26553, "text": "Please refer Decorators in Python for more details." }, { "code": null, "e": 26623, "s": 26605, "text": "Python Decorators" }, { "code": null, "e": 26630, "s": 26623, "text": "Python" }, { "code": null, "e": 26728, "s": 26630, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26737, "s": 26728, "text": "Comments" }, { "code": null, "e": 26750, "s": 26737, "text": "Old Comments" }, { "code": null, "e": 26768, "s": 26750, "text": "Python Dictionary" }, { "code": null, "e": 26790, "s": 26768, "text": "Enumerate() in Python" }, { "code": null, "e": 26822, "s": 26790, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26864, "s": 26822, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26890, "s": 26864, "text": "Python String | replace()" }, { "code": null, "e": 26934, "s": 26890, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26959, "s": 26934, "text": "sum() function in Python" }, { "code": null, "e": 26996, "s": 26959, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27052, "s": 26996, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
LAN Technologies | ETHERNET - GeeksforGeeks
24 Mar, 2022 A local Area Network (LAN) is a data communication network connecting various terminals or computers within a building or limited geographical area. The connection among the devices could be wired or wireless. Ethernet, Token Ring and Wireless LAN using IEEE 802.11 are examples of standard LAN technologies. LAN has the following topologies: Star Topology Bus Topology Ring Topology Mesh Topology Hybrid Topology Tree Topology Ethernet:- Ethernet is the most widely used LAN technology, which is defined under IEEE standards 802.3. The reason behind its wide usability is Ethernet is easy to understand, implement, maintain, and allows low-cost network implementation. Also, Ethernet offers flexibility in terms of topologies that are allowed. Ethernet generally uses Bus Topology. Ethernet operates in two layers of the OSI model, Physical Layer, and Data Link Layer. For Ethernet, the protocol data unit is Frame since we mainly deal with DLL. In order to handle collision, the Access control mechanism used in Ethernet is CSMA/CD. Manchester Encoding Technique is used in Ethernet. Since we are talking about IEEE 802.3 standard Ethernet, therefore, 0 is expressed by a high-to-low transition, a 1 by the low-to-high transition. In both Manchester Encoding and Differential Manchester, the Encoding Baud rate is double of bit rate. Advantages of Ethernet: Speed: When compared to a wireless connection, Ethernet provides significantly more speed. Because Ethernet is a one-to-one connection, this is the case. As a result, speeds of up to 10 Gigabits per second (Gbps) or even 100 Gigabits per second (Gbps) are possible. Efficiency: An Ethernet cable, such as Cat6, consumes less electricity, even less than a wifi connection. As a result, these ethernet cables are thought to be the most energy-efficient. Good data transfer quality: Because it is resistant to noise, the information transferred is of high quality. Baud rate = 2* Bit rate Ethernet LANs consist of network nodes and interconnecting media or links. The network nodes can be of two types: Data Terminal Equipment (DTE):- Generally, DTEs are the end devices that convert the user information into signals or reconvert the received signals. DTEs devices are: personal computers, workstations, file servers or print servers also referred to as end stations. These devices are either the source or the destination of data frames. The data terminal equipment may be a single piece of equipment or multiple pieces of equipment that are interconnected and perform all the required functions to allow the user to communicate. A user can interact with DTE or DTE may be a user. Data Communication Equipment (DCE):- DCEs are the intermediate network devices that receive and forward frames across the network. They may be either standalone devices such as repeaters, network switches, routers, or maybe communications interface units such as interface cards and modems. The DCE performs functions such as signal conversion, coding, and maybe a part of the DTE or intermediate equipment. Currently, these data rates are defined for operation over optical fibres and twisted-pair cables: i) Fast Ethernet Fast Ethernet refers to an Ethernet network that can transfer data at a rate of 100 Mbit/s. ii) Gigabit Ethernet Gigabit Ethernet delivers a data rate of 1,000 Mbit/s (1 Gbit/s). iii) 10 Gigabit Ethernet 10 Gigabit Ethernet is the recent generation and delivers a data rate of 10 Gbit/s (10,000 Mbit/s). It is generally used for backbones in high-end applications requiring high data rates. ALOHA The Aloha protocol was designed as part of a project at the University of Hawaii. It provided data transmission between computers on several of the Hawaiian Islands involving packet radio networks. Aloha is a multiple access protocol at the data link layer and proposes how multiple terminals access the medium without interference or collision. There are two different versions of ALOHA: 1. Pure Aloha Pure Aloha is an un-slotted, decentralized, and simple to implement the protocol. In pure ALOHA, the stations simply transmit frames whenever they want data to send. It does not check whether the channel is busy or not before transmitting. In case, two or more stations transmit simultaneously, the collision occurs and frames are destroyed. Whenever any station transmits a frame, it expects acknowledgement from the receiver. If it is not received within a specified time, the station assumes that the frame or acknowledgement has been destroyed. Then, the station waits for a random amount of time and sends the frame again. This randomness helps in avoiding more collisions. This scheme works well in small networks where the load is not much. But in largely loaded networks, this scheme fails poorly. This led to the development of Slotted Aloha. To assure pure aloha: Its throughput and rate of transmission of the frame to be predicted. For that to make some assumptions: i) All the frames should be the same length. ii) Stations can not generate frames while transmitting or trying to transmit frames. iii)The population of stations attempts to transmit (both new frames and old frames that collided) according to a Poisson distribution. Vulnerable Time = 2 * Tt The efficiency of Pure ALOHA: Spure= G * e^-2G where G is number of stations wants to transmit in Tt slot. Maximum Efficiency: Maximum Efficiency will be obtained when G=1/2 (Spure)max = 1/2 * e^-1 = 0.184 Which means, in Pure ALOHA, only about 18.4% of the time is used for successful transmissions. 2. Slotted Aloha This is quite similar to Pure Aloha, differing only in the way transmissions take place. Instead of transmitting right at demand time, the sender waits for some time. In slotted ALOHA, the time of the shared channel is divided into discrete intervals called Slots. The stations are eligible to send a frame only at the beginning of the slot and only one frame per slot is sent. If any station is not able to place the frame onto the channel at the beginning of the slot, it has to wait until the beginning of the next time slot. There is still a possibility of collision if two stations try to send at the beginning of the same time slot. But still, the number of collisions that can possibly take place is reduced by a large margin and the performance becomes much well compared to Pure Aloha. Collision is possible for only the current slot. Therefore, Vulnerable Time is Tt. The efficiency of Slotted ALOHA: Sslotted = G * e^-G Maximum Efficiency: (Sslotted)max = 1 * e^-1 = 1/e = 0.368 Maximum Efficiency, in Slotted ALOHA, is 36.8%. Image Reference: Wikipedia, Technical University of Munich References: https://www.cisco.com/c/en/us/tech/lan-switching/ethernet/index.html https://en.wikipedia.org/wiki/Ethernet This article is contributed by Sheena Kohli and Abhishek Agrawal ayushgangwar easeit tanwarsinghvaibhav 23603vaibhav2021 akashmomale Data Link Layer Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Socket Programming in Python Caesar Cipher in Cryptography UDP Server-Client implementation in C Differences between IPv4 and IPv6 Socket Programming in Java Advanced Encryption Standard (AES) Simple Chat Room using Python Cryptography and its Types nslookup command in Linux with Examples Architecture of Internet of Things (IoT)
[ { "code": null, "e": 36201, "s": 36173, "text": "\n24 Mar, 2022" }, { "code": null, "e": 36546, "s": 36201, "text": "A local Area Network (LAN) is a data communication network connecting various terminals or computers within a building or limited geographical area. The connection among the devices could be wired or wireless. Ethernet, Token Ring and Wireless LAN using IEEE 802.11 are examples of standard LAN technologies. LAN has the following topologies: " }, { "code": null, "e": 36560, "s": 36546, "text": "Star Topology" }, { "code": null, "e": 36573, "s": 36560, "text": "Bus Topology" }, { "code": null, "e": 36587, "s": 36573, "text": "Ring Topology" }, { "code": null, "e": 36601, "s": 36587, "text": "Mesh Topology" }, { "code": null, "e": 36617, "s": 36601, "text": "Hybrid Topology" }, { "code": null, "e": 36631, "s": 36617, "text": "Tree Topology" }, { "code": null, "e": 37291, "s": 36631, "text": "Ethernet:- Ethernet is the most widely used LAN technology, which is defined under IEEE standards 802.3. The reason behind its wide usability is Ethernet is easy to understand, implement, maintain, and allows low-cost network implementation. Also, Ethernet offers flexibility in terms of topologies that are allowed. Ethernet generally uses Bus Topology. Ethernet operates in two layers of the OSI model, Physical Layer, and Data Link Layer. For Ethernet, the protocol data unit is Frame since we mainly deal with DLL. In order to handle collision, the Access control mechanism used in Ethernet is CSMA/CD. Manchester Encoding Technique is used in Ethernet. " }, { "code": null, "e": 37542, "s": 37291, "text": "Since we are talking about IEEE 802.3 standard Ethernet, therefore, 0 is expressed by a high-to-low transition, a 1 by the low-to-high transition. In both Manchester Encoding and Differential Manchester, the Encoding Baud rate is double of bit rate. " }, { "code": null, "e": 37566, "s": 37542, "text": "Advantages of Ethernet:" }, { "code": null, "e": 37832, "s": 37566, "text": "Speed: When compared to a wireless connection, Ethernet provides significantly more speed. Because Ethernet is a one-to-one connection, this is the case. As a result, speeds of up to 10 Gigabits per second (Gbps) or even 100 Gigabits per second (Gbps) are possible." }, { "code": null, "e": 38018, "s": 37832, "text": "Efficiency: An Ethernet cable, such as Cat6, consumes less electricity, even less than a wifi connection. As a result, these ethernet cables are thought to be the most energy-efficient." }, { "code": null, "e": 38129, "s": 38018, "text": "Good data transfer quality: Because it is resistant to noise, the information transferred is of high quality. " }, { "code": null, "e": 38155, "s": 38129, "text": " Baud rate = 2* Bit rate " }, { "code": null, "e": 38850, "s": 38155, "text": "Ethernet LANs consist of network nodes and interconnecting media or links. The network nodes can be of two types: Data Terminal Equipment (DTE):- Generally, DTEs are the end devices that convert the user information into signals or reconvert the received signals. DTEs devices are: personal computers, workstations, file servers or print servers also referred to as end stations. These devices are either the source or the destination of data frames. The data terminal equipment may be a single piece of equipment or multiple pieces of equipment that are interconnected and perform all the required functions to allow the user to communicate. A user can interact with DTE or DTE may be a user. " }, { "code": null, "e": 39259, "s": 38850, "text": "Data Communication Equipment (DCE):- DCEs are the intermediate network devices that receive and forward frames across the network. They may be either standalone devices such as repeaters, network switches, routers, or maybe communications interface units such as interface cards and modems. The DCE performs functions such as signal conversion, coding, and maybe a part of the DTE or intermediate equipment. " }, { "code": null, "e": 39468, "s": 39259, "text": "Currently, these data rates are defined for operation over optical fibres and twisted-pair cables: i) Fast Ethernet Fast Ethernet refers to an Ethernet network that can transfer data at a rate of 100 Mbit/s. " }, { "code": null, "e": 39556, "s": 39468, "text": "ii) Gigabit Ethernet Gigabit Ethernet delivers a data rate of 1,000 Mbit/s (1 Gbit/s). " }, { "code": null, "e": 39769, "s": 39556, "text": "iii) 10 Gigabit Ethernet 10 Gigabit Ethernet is the recent generation and delivers a data rate of 10 Gbit/s (10,000 Mbit/s). It is generally used for backbones in high-end applications requiring high data rates. " }, { "code": null, "e": 40122, "s": 39769, "text": "ALOHA The Aloha protocol was designed as part of a project at the University of Hawaii. It provided data transmission between computers on several of the Hawaiian Islands involving packet radio networks. Aloha is a multiple access protocol at the data link layer and proposes how multiple terminals access the medium without interference or collision. " }, { "code": null, "e": 41427, "s": 40122, "text": "There are two different versions of ALOHA: 1. Pure Aloha Pure Aloha is an un-slotted, decentralized, and simple to implement the protocol. In pure ALOHA, the stations simply transmit frames whenever they want data to send. It does not check whether the channel is busy or not before transmitting. In case, two or more stations transmit simultaneously, the collision occurs and frames are destroyed. Whenever any station transmits a frame, it expects acknowledgement from the receiver. If it is not received within a specified time, the station assumes that the frame or acknowledgement has been destroyed. Then, the station waits for a random amount of time and sends the frame again. This randomness helps in avoiding more collisions. This scheme works well in small networks where the load is not much. But in largely loaded networks, this scheme fails poorly. This led to the development of Slotted Aloha. To assure pure aloha: Its throughput and rate of transmission of the frame to be predicted. For that to make some assumptions: i) All the frames should be the same length. ii) Stations can not generate frames while transmitting or trying to transmit frames. iii)The population of stations attempts to transmit (both new frames and old frames that collided) according to a Poisson distribution. " }, { "code": null, "e": 41456, "s": 41429, "text": " Vulnerable Time = 2 * Tt " }, { "code": null, "e": 41488, "s": 41456, "text": "The efficiency of Pure ALOHA: " }, { "code": null, "e": 41776, "s": 41488, "text": "Spure= G * e^-2G \nwhere G is number of stations wants to transmit in Tt slot. \n\nMaximum Efficiency:\nMaximum Efficiency will be obtained when G=1/2\n\n(Spure)max = 1/2 * e^-1\n = 0.184 \n\nWhich means, in Pure ALOHA, only about 18.4% of the time is used for successful transmissions." }, { "code": null, "e": 42589, "s": 41776, "text": "2. Slotted Aloha This is quite similar to Pure Aloha, differing only in the way transmissions take place. Instead of transmitting right at demand time, the sender waits for some time. In slotted ALOHA, the time of the shared channel is divided into discrete intervals called Slots. The stations are eligible to send a frame only at the beginning of the slot and only one frame per slot is sent. If any station is not able to place the frame onto the channel at the beginning of the slot, it has to wait until the beginning of the next time slot. There is still a possibility of collision if two stations try to send at the beginning of the same time slot. But still, the number of collisions that can possibly take place is reduced by a large margin and the performance becomes much well compared to Pure Aloha. " }, { "code": null, "e": 42675, "s": 42591, "text": "Collision is possible for only the current slot. Therefore, Vulnerable Time is Tt. " }, { "code": null, "e": 42710, "s": 42675, "text": "The efficiency of Slotted ALOHA: " }, { "code": null, "e": 42855, "s": 42710, "text": " Sslotted = G * e^-G\n\nMaximum Efficiency:\n(Sslotted)max = 1 * e^-1 \n = 1/e = 0.368 \nMaximum Efficiency, in Slotted ALOHA, is 36.8%." }, { "code": null, "e": 42915, "s": 42855, "text": "Image Reference: Wikipedia, Technical University of Munich " }, { "code": null, "e": 43036, "s": 42915, "text": "References: https://www.cisco.com/c/en/us/tech/lan-switching/ethernet/index.html https://en.wikipedia.org/wiki/Ethernet " }, { "code": null, "e": 43102, "s": 43036, "text": "This article is contributed by Sheena Kohli and Abhishek Agrawal " }, { "code": null, "e": 43115, "s": 43102, "text": "ayushgangwar" }, { "code": null, "e": 43122, "s": 43115, "text": "easeit" }, { "code": null, "e": 43141, "s": 43122, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 43158, "s": 43141, "text": "23603vaibhav2021" }, { "code": null, "e": 43170, "s": 43158, "text": "akashmomale" }, { "code": null, "e": 43186, "s": 43170, "text": "Data Link Layer" }, { "code": null, "e": 43204, "s": 43186, "text": "Computer Networks" }, { "code": null, "e": 43222, "s": 43204, "text": "Computer Networks" }, { "code": null, "e": 43320, "s": 43222, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43329, "s": 43320, "text": "Comments" }, { "code": null, "e": 43342, "s": 43329, "text": "Old Comments" }, { "code": null, "e": 43371, "s": 43342, "text": "Socket Programming in Python" }, { "code": null, "e": 43401, "s": 43371, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 43439, "s": 43401, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 43473, "s": 43439, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 43500, "s": 43473, "text": "Socket Programming in Java" }, { "code": null, "e": 43535, "s": 43500, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 43565, "s": 43535, "text": "Simple Chat Room using Python" }, { "code": null, "e": 43592, "s": 43565, "text": "Cryptography and its Types" }, { "code": null, "e": 43632, "s": 43592, "text": "nslookup command in Linux with Examples" } ]
Neo4j & DGL — a seamless integration | by Kristof Neys | Towards Data Science
This blog post was co-authored with Clair Sullivan and Mark Needham The release of the Neo4j GDS library version 1.5, and the build-in machine learning models, has now given the Data Scientist that needs to perform a machine learning task on any graph in Neo4j two possible routes to a solution. If time is of the essence and a supported and tested model that works natively is needed, then a simple function call to the GDS library will get the job done. If, however, more flexibility is needed or there are some data constraints then the Data Scientist can deploy external machine learning libraries, in conjunction with the Neo4j Python driver. In these series of articles we will illustrate how different external Machine Learning libraries can be used to complement the existing Neo4j Graph Data Science (GDS) functionality. For this article we have used the Deep Graph Library (DGL) package with TensorFlow as backend and have constructed a Colab notebook with the entire code using the Cora dataset, which can be found here. By way of background, we briefly describe Graph Neural Networks (GNNs), which in its broadest sense can be defined as a class of neural network models suitable for processing graph-structured data. As such, and again in its broadest sense, learning on graphs (i.e. Graph Representation Learning) can be divided into two classes of learning problems; unsupervised and supervised learning (incl. semi-supervised). Unsupervised learning aims at learning low-dimensional Euclidean representations that capture the structure of the input graph, these are generally known as embedding algorithms, and an example of which is the Node2Vec algorithm which can be found in the Neo4j GDS library. The second class of learning tasks also learns an embedding but with the goal of performing some downstream prediction such as node or graph classification or link prediction. Whereas the inputs for the unsupervised learning are typically the entire graph, for the supervised task the inputs are node features and possibly edge features and in addition, the graph structure (all or usually partly) can also be used in training. The general framework for the supervised GNN task is a ‘message passing’ framework that aims to encompass the different types of GNNs. Recent surveys organize the different GNNs in a taxonomy of around 5 GNN architectures, ranging from Recurrent GNNs, Graph Convolutional NNs to Graph Attention Networks etc. Now, the Data Scientist may want to exploit these different architectures since she/he may face issues of having a limited amount of labeled data and therefore can only deploy semi-supervised models, or may want to gain additional insights from the most important features etc. Hence, in those circumstances, the Data Scientist will want to build their own customized model to make node classifications or other downstream applications. Thanks to the Neo4j Python driver any of the GNN packages are available to perform graph machine learning tasks on a Neo4j graph. Indeed, in the past few years, a whole smorgasbord of libraries and tools have been developed, by a recent count the number of open source projects on Graph Neural Networks has reached almost 100! awesomeopensource.com The DGL package is one of the most extensive libraries consisting of the core building blocks to create graphs, several message passing functions, as well as entire Graph Neural Network models, all ready to go. Another advantage of the DGL library is that it works with the most frequently used backend platforms such as TensorFlow, Pytorch, and MXNet. Finally, DGL comes with a data API that provides access to some of the benchmark datasets, one of which is the Cora citation graph, which is pretty much the equivalent of MNIST in graph land... One such GNN that a Data Scientist may want to use could be a Graph Attention Network. This is a semi-supervised learning model that only needs a limited number of known labels, in addition to the node features, to train the model. It does this by computing the hidden representations of each node in the graph by giving “attention” to the neighbors of that specific node. That is, it applies an “attention-based architecture” to perform node classification. The Theory Before we jump into the experiment, we’ll first explain the GNN model we are deploying. Graph ATtention Networks (abbreviated ‘GAT’, such as not to confuse with, Generative Adversarial Networks) were introduced in 2018 by Velickovic et al. as an improvement to existing Graph Convolutional Neural Networks. As the name suggests, the core idea of GATs is to apply an ‘attention mechanism’ based architecture. Attention mechanisms revolutionized neural machine translation, and NLP in general, and have become the de facto’ norm in many sequence-based models. An attention mechanism can broadly be divided into two main categories: ‘general attention’ which quantifies the independence between input and output elements, and ‘self-attention’ which manages and quantifies the independence within input elements. In the GAT model, the role of the attention mechanism is “to compute the hidden representations of each node in the graph by attending over its neighbors” following a self-attention strategy. We will briefly describe the key steps and components of a single ‘graph attention layer’ and refer the interested reader to the paper for a more detailed and mathematical explanation. arxiv.org The narrative of the model can be summarized in 5 steps: The first step is to define the set of node features that provide the input to the model. As we will see, in our example, these are the feature vectors obtained by embedding the text of each document in a 0/1 “bag-of-words” vector of length 1433.As a second step, we apply a linear transformation to each feature vector using a shared weight matrix of learnable parameters.The third step involves performing the self-attention by computing the attention coefficients as follows: we concatenate two linearly transformed node features (linearly transformed in step 1), of the source and destination node, and apply the attention mechanism. This mechanism is nothing more than applying a LeakyReLu nonlinear activation function to the dot product of a learnable weight vector (let’s call it a) with the concatenated node features. As such, the attention mechanism can be viewed as a single feedforward neural network parametrized by a weight vector and the LeakyRelu as the activation function. The attention coefficients can be interpreted as the importance of one node’s features to its neighbors.As a penultimate step, the attention coefficients get normalized by applying a softmax function, which makes the coefficients comparable across different nodes. This will allow the analysis of which attention coefficients have the most impact on the hidden nodes and hence the output. In turn, it allows measuring the ‘entropy’ of the attention distribution.As a final step, the normalized attention coefficients are used to compute a linear combination of the features corresponding to them and produce a hidden representation of each node, after possibly applying a nonlinearity, sigma. The first step is to define the set of node features that provide the input to the model. As we will see, in our example, these are the feature vectors obtained by embedding the text of each document in a 0/1 “bag-of-words” vector of length 1433. As a second step, we apply a linear transformation to each feature vector using a shared weight matrix of learnable parameters. The third step involves performing the self-attention by computing the attention coefficients as follows: we concatenate two linearly transformed node features (linearly transformed in step 1), of the source and destination node, and apply the attention mechanism. This mechanism is nothing more than applying a LeakyReLu nonlinear activation function to the dot product of a learnable weight vector (let’s call it a) with the concatenated node features. As such, the attention mechanism can be viewed as a single feedforward neural network parametrized by a weight vector and the LeakyRelu as the activation function. The attention coefficients can be interpreted as the importance of one node’s features to its neighbors. As a penultimate step, the attention coefficients get normalized by applying a softmax function, which makes the coefficients comparable across different nodes. This will allow the analysis of which attention coefficients have the most impact on the hidden nodes and hence the output. In turn, it allows measuring the ‘entropy’ of the attention distribution. As a final step, the normalized attention coefficients are used to compute a linear combination of the features corresponding to them and produce a hidden representation of each node, after possibly applying a nonlinearity, sigma. A single attention mechanism can be visualised as follows: Single Head or Multi-head? The authors of the GAT paper found that to stabilize the learning process of the self-attention, extending the mechanism to a ‘multi-head attention’ performed better. In a nutshell, a multi-head mechanism simply runs through the dot-product attention multiple times in parallel. Recall from step 3 above that we have the weight vector, a, in the attention coefficient computation. Well, the multi-head attention now produces several of these (3 in the image below) and then concatenates them to produce the hidden representation. In the final layer, however, an averaging is performed. This can be visualized as follows (using 3 heads in green, blue and purple) We will now implement a Graph Attention Network using the Neo4j Python drivers to access the DGL library, perform the machine learning task, write the results back to the native graph in Neo4j, and perform Cypher queries. Dataset The dataset we will be working with is as mentioned the Cora citation dataset, which is also one of the datasets used in the GAT paper, and consists of academic papers in the field of machine learning. These papers are classified into one of the following seven classes: Case_BasedGenetic_AlgorithmsNeural_NetworksProbabilistic_MethodsReinforcement_LearningRule_LearningTheory Case_Based Genetic_Algorithms Neural_Networks Probabilistic_Methods Reinforcement_Learning Rule_Learning Theory The papers were selected in a way such that every paper cites or is cited by at least one other paper. There are 2708 papers in the whole corpus and there are 5429 edges. The Cora dataset forms part of the DGL data API and in order to make the workflow easy to replicate we have also used this version of the Cora set, which we will write as a graph in Neo4j. The only difference with the original Cora dataset is the node labeling, which is index-based in the DGL version. However, there seem to be some duplicates, as DGL does filter them out with 5278 unique edges. Indeed when loading the Cora edges into Neo4j we also end up with 5278 relationships. Hence, the dataset has 5278 relationships, which we have termed as a ‘CITED_BY’ relationship type in Neo4j. We write the Cora graph to Neo4j, using the Python driver, as follows: An excellent reference on how to use the Neo4j Python driver can be found in this article by Clair Sullivan. Feature vectors The text of each paper is analyzed and provides the feature vector as follows: after stemming and removing stopwords as well as words with a frequency of less than 10, we end up with 1433 unique words, which provides the dictionary. This dictionary now allows for the creation of a binary-valued feature vector (i.e. if the word appears in the document the vector entry is a 1, 0 otherwise), also known as a ‘bag-of-words’ representation. Hence, each document, representing a node in our case, has such a feature vector of length 1433. The Task We set the GAT to model a transductive learning task (semi-supervised learning) which is to predict the labels of the nodes but only allowing 20 nodes per class to be used for training, that is 140 out of a total of 2708. The training algorithm however is given the complete set of all nodes’ feature vectors. The trained model, again with only 140 training labels, is validated on 500 nodes and is tested on a set of 1000 nodes. This task can be applied to various real-world applications, for instance product labeling where the feature vectors are derived from the product description or client classifications where the feature vectors could be made up of co-purchases etc. Hyperparameter selection The Colab notebook that accompanies this article can be found here and includes detailed comments per code block. The key points to note are that the model selects 8 attention heads and given the small training set and risk of overfitting, the model uses both L_2 regularizations as well as dropout (at p = 0.6) to reduce this risk. Finally, cross-entropy is used as loss function with ADAM SGD optimizer Running the Graph Attention Model As mentioned earlier, the Deep Graph Library is one of the most extensive and well-documented graph machine learning libraries and has the added advantage of being able to run on either PyTorch, TensorFlow or MXNet. The core of any machine learning model is the layer, which is not different in the DGL library, hence, the dgl.nn package contains the implementations of the most commonly used GNN layers, which of course includes the GAT layer. Finally, the DGL & TensorFlow combination is designed to work entirely using GPU’s. Workflow The code is commented in the Colab notebook, and the workflow is quite straightforward. The data gets loaded into the notebook/model using the DGL data API and comes pre-processed using a mask method. This is a simple boolean vector either exposing or hiding the labels of the relevant train, validation, and test set. The GAT layer is a subclass of the TensorFlow-Keras layer where the arguments need to be determined when instantiating the class. To do this we created a separate function create_model, in addition to a few helper functions for the loss, accuracy, evaluate, early stopping etc. Finally, the train function calls the relevant functions with its arguments determining the hyperparameters, which as listed above, we used the same as the paper. We also made sure to write the predicted labels to a pandas DataFrame such that we can write them back to Neo4j. As for training we selected 500 epochs but include an early stopping where we set the ‘patience’ at 100. The running of the model takes less than 10 seconds and reaches the early stopping trigger after 379 epochs, achieving an impressive accuracy of 82.10%. Thankfully, this is in line with the results achieved in the paper: 83.0% with a variance of 0.7%. Hence, of the 1000 nodes in our test set the Graph Attention Network model managed to label 820 correctly, with only needing around 5% of the labels to train (140 out of 2708), and of course the features of every node. Writing the Predicted labels to Neo4j Now that our joint-venture with DGL has produced the results we needed, it’s time to head back to the mothership. Again, we call onto the Neo4j Python driver to write back the results to our Cora graph in Neo4j. This only takes us 7 lines of code plus the standard Cypher query, as follows: We let the model run predictions on the entire graph, all 2708 nodes, and as can be seen from the Cypher query here above, we wrote the predicted labels to the graph as a node property. We now have the following in Neo4j: ╒══════════════════════════════════════╕│"n" │╞══════════════════════════════════════╡│{"id":0,"label":"Genetic_Algorithms","││Predicted_Label":"Genetic_Algorithms"}│├──────────────────────────────────────┤│{"id":1,"label":"Rule_Learning","Predi││cted_Label":"Rule_Learning"} │├──────────────────────────────────────┤│{"id":2,"label":"Rule_Learning","Predi││cted_Label":"Rule_Learning"} │├──────────────────────────────────────┤│{"id":3,"label":"Case_Based","Predicte││d_Label":"Case_Based"} │├──────────────────────────────────────┤│{"id":4,"label":"Genetic_Algorithms","││Predicted_Label":"Genetic_Algorithms"}│└──────────────────────────────────────┘ And we can now run some Cypher queries, for instance, we can check how many predicted labels are different from the actual ones: Which returned 454 — hence, we have 454 out of 2708 labels that are incorrect, or 16.7%, so indeed 83.3% being correctly predicted, which after stripping out the 140 training labels is exactly the same as the results from the paper. We can also do some more detailed analysis in Neo4j by assigning the command above to an accuracy property, and then compute the accuracy per class of paper, as follows: ╒══════════════════════════════════╤══════════════════╕│"Label" │"Accuracy" │╞══════════════════════════════════╪══════════════════╡│["Theory"] │0.9425837320574163│├──────────────────────────────────┼──────────────────┤│["Probabilistic_Methods"] │0.8986175115207373│├──────────────────────────────────┼──────────────────┤│["Rule_Learning"] │0.8943661971830986│├──────────────────────────────────┼──────────────────┤│["Case_Based"] │0.8062678062678063│├──────────────────────────────────┼──────────────────┤│["Reinforcement_Learning"] │0.738255033557047 │├──────────────────────────────────┼──────────────────┤│["Genetic_Algorithms"] │0.7286063569682152│├──────────────────────────────────┼──────────────────┤│["Neural_Networks"] │0.7111111111111111│└──────────────────────────────────┴──────────────────┘ In this article we have shown that by making use of the Neo4j Python driver a whole range of additional machine learning models can be accessed and complement the existing Neo4j GDS functionality. In future articles we will illustrate how many of the Neo4j GDS algorithms can be used to compute a range of feature vectors which subsequently can be deployed to train a GNN, and again return the results to the native Neo4j graph.
[ { "code": null, "e": 239, "s": 171, "text": "This blog post was co-authored with Clair Sullivan and Mark Needham" }, { "code": null, "e": 467, "s": 239, "text": "The release of the Neo4j GDS library version 1.5, and the build-in machine learning models, has now given the Data Scientist that needs to perform a machine learning task on any graph in Neo4j two possible routes to a solution." }, { "code": null, "e": 819, "s": 467, "text": "If time is of the essence and a supported and tested model that works natively is needed, then a simple function call to the GDS library will get the job done. If, however, more flexibility is needed or there are some data constraints then the Data Scientist can deploy external machine learning libraries, in conjunction with the Neo4j Python driver." }, { "code": null, "e": 1001, "s": 819, "text": "In these series of articles we will illustrate how different external Machine Learning libraries can be used to complement the existing Neo4j Graph Data Science (GDS) functionality." }, { "code": null, "e": 1203, "s": 1001, "text": "For this article we have used the Deep Graph Library (DGL) package with TensorFlow as backend and have constructed a Colab notebook with the entire code using the Cora dataset, which can be found here." }, { "code": null, "e": 2626, "s": 1203, "text": "By way of background, we briefly describe Graph Neural Networks (GNNs), which in its broadest sense can be defined as a class of neural network models suitable for processing graph-structured data. As such, and again in its broadest sense, learning on graphs (i.e. Graph Representation Learning) can be divided into two classes of learning problems; unsupervised and supervised learning (incl. semi-supervised). Unsupervised learning aims at learning low-dimensional Euclidean representations that capture the structure of the input graph, these are generally known as embedding algorithms, and an example of which is the Node2Vec algorithm which can be found in the Neo4j GDS library. The second class of learning tasks also learns an embedding but with the goal of performing some downstream prediction such as node or graph classification or link prediction. Whereas the inputs for the unsupervised learning are typically the entire graph, for the supervised task the inputs are node features and possibly edge features and in addition, the graph structure (all or usually partly) can also be used in training. The general framework for the supervised GNN task is a ‘message passing’ framework that aims to encompass the different types of GNNs. Recent surveys organize the different GNNs in a taxonomy of around 5 GNN architectures, ranging from Recurrent GNNs, Graph Convolutional NNs to Graph Attention Networks etc." }, { "code": null, "e": 3063, "s": 2626, "text": "Now, the Data Scientist may want to exploit these different architectures since she/he may face issues of having a limited amount of labeled data and therefore can only deploy semi-supervised models, or may want to gain additional insights from the most important features etc. Hence, in those circumstances, the Data Scientist will want to build their own customized model to make node classifications or other downstream applications." }, { "code": null, "e": 3390, "s": 3063, "text": "Thanks to the Neo4j Python driver any of the GNN packages are available to perform graph machine learning tasks on a Neo4j graph. Indeed, in the past few years, a whole smorgasbord of libraries and tools have been developed, by a recent count the number of open source projects on Graph Neural Networks has reached almost 100!" }, { "code": null, "e": 3412, "s": 3390, "text": "awesomeopensource.com" }, { "code": null, "e": 3959, "s": 3412, "text": "The DGL package is one of the most extensive libraries consisting of the core building blocks to create graphs, several message passing functions, as well as entire Graph Neural Network models, all ready to go. Another advantage of the DGL library is that it works with the most frequently used backend platforms such as TensorFlow, Pytorch, and MXNet. Finally, DGL comes with a data API that provides access to some of the benchmark datasets, one of which is the Cora citation graph, which is pretty much the equivalent of MNIST in graph land..." }, { "code": null, "e": 4418, "s": 3959, "text": "One such GNN that a Data Scientist may want to use could be a Graph Attention Network. This is a semi-supervised learning model that only needs a limited number of known labels, in addition to the node features, to train the model. It does this by computing the hidden representations of each node in the graph by giving “attention” to the neighbors of that specific node. That is, it applies an “attention-based architecture” to perform node classification." }, { "code": null, "e": 4429, "s": 4418, "text": "The Theory" }, { "code": null, "e": 4837, "s": 4429, "text": "Before we jump into the experiment, we’ll first explain the GNN model we are deploying. Graph ATtention Networks (abbreviated ‘GAT’, such as not to confuse with, Generative Adversarial Networks) were introduced in 2018 by Velickovic et al. as an improvement to existing Graph Convolutional Neural Networks. As the name suggests, the core idea of GATs is to apply an ‘attention mechanism’ based architecture." }, { "code": null, "e": 5430, "s": 4837, "text": "Attention mechanisms revolutionized neural machine translation, and NLP in general, and have become the de facto’ norm in many sequence-based models. An attention mechanism can broadly be divided into two main categories: ‘general attention’ which quantifies the independence between input and output elements, and ‘self-attention’ which manages and quantifies the independence within input elements. In the GAT model, the role of the attention mechanism is “to compute the hidden representations of each node in the graph by attending over its neighbors” following a self-attention strategy." }, { "code": null, "e": 5615, "s": 5430, "text": "We will briefly describe the key steps and components of a single ‘graph attention layer’ and refer the interested reader to the paper for a more detailed and mathematical explanation." }, { "code": null, "e": 5625, "s": 5615, "text": "arxiv.org" }, { "code": null, "e": 5682, "s": 5625, "text": "The narrative of the model can be summarized in 5 steps:" }, { "code": null, "e": 7367, "s": 5682, "text": "The first step is to define the set of node features that provide the input to the model. As we will see, in our example, these are the feature vectors obtained by embedding the text of each document in a 0/1 “bag-of-words” vector of length 1433.As a second step, we apply a linear transformation to each feature vector using a shared weight matrix of learnable parameters.The third step involves performing the self-attention by computing the attention coefficients as follows: we concatenate two linearly transformed node features (linearly transformed in step 1), of the source and destination node, and apply the attention mechanism. This mechanism is nothing more than applying a LeakyReLu nonlinear activation function to the dot product of a learnable weight vector (let’s call it a) with the concatenated node features. As such, the attention mechanism can be viewed as a single feedforward neural network parametrized by a weight vector and the LeakyRelu as the activation function. The attention coefficients can be interpreted as the importance of one node’s features to its neighbors.As a penultimate step, the attention coefficients get normalized by applying a softmax function, which makes the coefficients comparable across different nodes. This will allow the analysis of which attention coefficients have the most impact on the hidden nodes and hence the output. In turn, it allows measuring the ‘entropy’ of the attention distribution.As a final step, the normalized attention coefficients are used to compute a linear combination of the features corresponding to them and produce a hidden representation of each node, after possibly applying a nonlinearity, sigma." }, { "code": null, "e": 7614, "s": 7367, "text": "The first step is to define the set of node features that provide the input to the model. As we will see, in our example, these are the feature vectors obtained by embedding the text of each document in a 0/1 “bag-of-words” vector of length 1433." }, { "code": null, "e": 7742, "s": 7614, "text": "As a second step, we apply a linear transformation to each feature vector using a shared weight matrix of learnable parameters." }, { "code": null, "e": 8466, "s": 7742, "text": "The third step involves performing the self-attention by computing the attention coefficients as follows: we concatenate two linearly transformed node features (linearly transformed in step 1), of the source and destination node, and apply the attention mechanism. This mechanism is nothing more than applying a LeakyReLu nonlinear activation function to the dot product of a learnable weight vector (let’s call it a) with the concatenated node features. As such, the attention mechanism can be viewed as a single feedforward neural network parametrized by a weight vector and the LeakyRelu as the activation function. The attention coefficients can be interpreted as the importance of one node’s features to its neighbors." }, { "code": null, "e": 8825, "s": 8466, "text": "As a penultimate step, the attention coefficients get normalized by applying a softmax function, which makes the coefficients comparable across different nodes. This will allow the analysis of which attention coefficients have the most impact on the hidden nodes and hence the output. In turn, it allows measuring the ‘entropy’ of the attention distribution." }, { "code": null, "e": 9056, "s": 8825, "text": "As a final step, the normalized attention coefficients are used to compute a linear combination of the features corresponding to them and produce a hidden representation of each node, after possibly applying a nonlinearity, sigma." }, { "code": null, "e": 9115, "s": 9056, "text": "A single attention mechanism can be visualised as follows:" }, { "code": null, "e": 9142, "s": 9115, "text": "Single Head or Multi-head?" }, { "code": null, "e": 9728, "s": 9142, "text": "The authors of the GAT paper found that to stabilize the learning process of the self-attention, extending the mechanism to a ‘multi-head attention’ performed better. In a nutshell, a multi-head mechanism simply runs through the dot-product attention multiple times in parallel. Recall from step 3 above that we have the weight vector, a, in the attention coefficient computation. Well, the multi-head attention now produces several of these (3 in the image below) and then concatenates them to produce the hidden representation. In the final layer, however, an averaging is performed." }, { "code": null, "e": 9804, "s": 9728, "text": "This can be visualized as follows (using 3 heads in green, blue and purple)" }, { "code": null, "e": 10026, "s": 9804, "text": "We will now implement a Graph Attention Network using the Neo4j Python drivers to access the DGL library, perform the machine learning task, write the results back to the native graph in Neo4j, and perform Cypher queries." }, { "code": null, "e": 10034, "s": 10026, "text": "Dataset" }, { "code": null, "e": 10305, "s": 10034, "text": "The dataset we will be working with is as mentioned the Cora citation dataset, which is also one of the datasets used in the GAT paper, and consists of academic papers in the field of machine learning. These papers are classified into one of the following seven classes:" }, { "code": null, "e": 10411, "s": 10305, "text": "Case_BasedGenetic_AlgorithmsNeural_NetworksProbabilistic_MethodsReinforcement_LearningRule_LearningTheory" }, { "code": null, "e": 10422, "s": 10411, "text": "Case_Based" }, { "code": null, "e": 10441, "s": 10422, "text": "Genetic_Algorithms" }, { "code": null, "e": 10457, "s": 10441, "text": "Neural_Networks" }, { "code": null, "e": 10479, "s": 10457, "text": "Probabilistic_Methods" }, { "code": null, "e": 10502, "s": 10479, "text": "Reinforcement_Learning" }, { "code": null, "e": 10516, "s": 10502, "text": "Rule_Learning" }, { "code": null, "e": 10523, "s": 10516, "text": "Theory" }, { "code": null, "e": 10694, "s": 10523, "text": "The papers were selected in a way such that every paper cites or is cited by at least one other paper. There are 2708 papers in the whole corpus and there are 5429 edges." }, { "code": null, "e": 10997, "s": 10694, "text": "The Cora dataset forms part of the DGL data API and in order to make the workflow easy to replicate we have also used this version of the Cora set, which we will write as a graph in Neo4j. The only difference with the original Cora dataset is the node labeling, which is index-based in the DGL version." }, { "code": null, "e": 11357, "s": 10997, "text": "However, there seem to be some duplicates, as DGL does filter them out with 5278 unique edges. Indeed when loading the Cora edges into Neo4j we also end up with 5278 relationships. Hence, the dataset has 5278 relationships, which we have termed as a ‘CITED_BY’ relationship type in Neo4j. We write the Cora graph to Neo4j, using the Python driver, as follows:" }, { "code": null, "e": 11466, "s": 11357, "text": "An excellent reference on how to use the Neo4j Python driver can be found in this article by Clair Sullivan." }, { "code": null, "e": 11482, "s": 11466, "text": "Feature vectors" }, { "code": null, "e": 12018, "s": 11482, "text": "The text of each paper is analyzed and provides the feature vector as follows: after stemming and removing stopwords as well as words with a frequency of less than 10, we end up with 1433 unique words, which provides the dictionary. This dictionary now allows for the creation of a binary-valued feature vector (i.e. if the word appears in the document the vector entry is a 1, 0 otherwise), also known as a ‘bag-of-words’ representation. Hence, each document, representing a node in our case, has such a feature vector of length 1433." }, { "code": null, "e": 12027, "s": 12018, "text": "The Task" }, { "code": null, "e": 12705, "s": 12027, "text": "We set the GAT to model a transductive learning task (semi-supervised learning) which is to predict the labels of the nodes but only allowing 20 nodes per class to be used for training, that is 140 out of a total of 2708. The training algorithm however is given the complete set of all nodes’ feature vectors. The trained model, again with only 140 training labels, is validated on 500 nodes and is tested on a set of 1000 nodes. This task can be applied to various real-world applications, for instance product labeling where the feature vectors are derived from the product description or client classifications where the feature vectors could be made up of co-purchases etc." }, { "code": null, "e": 12730, "s": 12705, "text": "Hyperparameter selection" }, { "code": null, "e": 13135, "s": 12730, "text": "The Colab notebook that accompanies this article can be found here and includes detailed comments per code block. The key points to note are that the model selects 8 attention heads and given the small training set and risk of overfitting, the model uses both L_2 regularizations as well as dropout (at p = 0.6) to reduce this risk. Finally, cross-entropy is used as loss function with ADAM SGD optimizer" }, { "code": null, "e": 13169, "s": 13135, "text": "Running the Graph Attention Model" }, { "code": null, "e": 13385, "s": 13169, "text": "As mentioned earlier, the Deep Graph Library is one of the most extensive and well-documented graph machine learning libraries and has the added advantage of being able to run on either PyTorch, TensorFlow or MXNet." }, { "code": null, "e": 13698, "s": 13385, "text": "The core of any machine learning model is the layer, which is not different in the DGL library, hence, the dgl.nn package contains the implementations of the most commonly used GNN layers, which of course includes the GAT layer. Finally, the DGL & TensorFlow combination is designed to work entirely using GPU’s." }, { "code": null, "e": 13707, "s": 13698, "text": "Workflow" }, { "code": null, "e": 13795, "s": 13707, "text": "The code is commented in the Colab notebook, and the workflow is quite straightforward." }, { "code": null, "e": 14304, "s": 13795, "text": "The data gets loaded into the notebook/model using the DGL data API and comes pre-processed using a mask method. This is a simple boolean vector either exposing or hiding the labels of the relevant train, validation, and test set. The GAT layer is a subclass of the TensorFlow-Keras layer where the arguments need to be determined when instantiating the class. To do this we created a separate function create_model, in addition to a few helper functions for the loss, accuracy, evaluate, early stopping etc." }, { "code": null, "e": 14467, "s": 14304, "text": "Finally, the train function calls the relevant functions with its arguments determining the hyperparameters, which as listed above, we used the same as the paper." }, { "code": null, "e": 14580, "s": 14467, "text": "We also made sure to write the predicted labels to a pandas DataFrame such that we can write them back to Neo4j." }, { "code": null, "e": 14685, "s": 14580, "text": "As for training we selected 500 epochs but include an early stopping where we set the ‘patience’ at 100." }, { "code": null, "e": 14838, "s": 14685, "text": "The running of the model takes less than 10 seconds and reaches the early stopping trigger after 379 epochs, achieving an impressive accuracy of 82.10%." }, { "code": null, "e": 14937, "s": 14838, "text": "Thankfully, this is in line with the results achieved in the paper: 83.0% with a variance of 0.7%." }, { "code": null, "e": 15156, "s": 14937, "text": "Hence, of the 1000 nodes in our test set the Graph Attention Network model managed to label 820 correctly, with only needing around 5% of the labels to train (140 out of 2708), and of course the features of every node." }, { "code": null, "e": 15194, "s": 15156, "text": "Writing the Predicted labels to Neo4j" }, { "code": null, "e": 15485, "s": 15194, "text": "Now that our joint-venture with DGL has produced the results we needed, it’s time to head back to the mothership. Again, we call onto the Neo4j Python driver to write back the results to our Cora graph in Neo4j. This only takes us 7 lines of code plus the standard Cypher query, as follows:" }, { "code": null, "e": 15671, "s": 15485, "text": "We let the model run predictions on the entire graph, all 2708 nodes, and as can be seen from the Cypher query here above, we wrote the predicted labels to the graph as a node property." }, { "code": null, "e": 15707, "s": 15671, "text": "We now have the following in Neo4j:" }, { "code": null, "e": 16428, "s": 15707, "text": "╒══════════════════════════════════════╕│\"n\" │╞══════════════════════════════════════╡│{\"id\":0,\"label\":\"Genetic_Algorithms\",\"││Predicted_Label\":\"Genetic_Algorithms\"}│├──────────────────────────────────────┤│{\"id\":1,\"label\":\"Rule_Learning\",\"Predi││cted_Label\":\"Rule_Learning\"} │├──────────────────────────────────────┤│{\"id\":2,\"label\":\"Rule_Learning\",\"Predi││cted_Label\":\"Rule_Learning\"} │├──────────────────────────────────────┤│{\"id\":3,\"label\":\"Case_Based\",\"Predicte││d_Label\":\"Case_Based\"} │├──────────────────────────────────────┤│{\"id\":4,\"label\":\"Genetic_Algorithms\",\"││Predicted_Label\":\"Genetic_Algorithms\"}│└──────────────────────────────────────┘" }, { "code": null, "e": 16557, "s": 16428, "text": "And we can now run some Cypher queries, for instance, we can check how many predicted labels are different from the actual ones:" }, { "code": null, "e": 16790, "s": 16557, "text": "Which returned 454 — hence, we have 454 out of 2708 labels that are incorrect, or 16.7%, so indeed 83.3% being correctly predicted, which after stripping out the 140 training labels is exactly the same as the results from the paper." }, { "code": null, "e": 16960, "s": 16790, "text": "We can also do some more detailed analysis in Neo4j by assigning the command above to an accuracy property, and then compute the accuracy per class of paper, as follows:" }, { "code": null, "e": 17896, "s": 16960, "text": "╒══════════════════════════════════╤══════════════════╕│\"Label\" │\"Accuracy\" │╞══════════════════════════════════╪══════════════════╡│[\"Theory\"] │0.9425837320574163│├──────────────────────────────────┼──────────────────┤│[\"Probabilistic_Methods\"] │0.8986175115207373│├──────────────────────────────────┼──────────────────┤│[\"Rule_Learning\"] │0.8943661971830986│├──────────────────────────────────┼──────────────────┤│[\"Case_Based\"] │0.8062678062678063│├──────────────────────────────────┼──────────────────┤│[\"Reinforcement_Learning\"] │0.738255033557047 │├──────────────────────────────────┼──────────────────┤│[\"Genetic_Algorithms\"] │0.7286063569682152│├──────────────────────────────────┼──────────────────┤│[\"Neural_Networks\"] │0.7111111111111111│└──────────────────────────────────┴──────────────────┘" }, { "code": null, "e": 18093, "s": 17896, "text": "In this article we have shown that by making use of the Neo4j Python driver a whole range of additional machine learning models can be accessed and complement the existing Neo4j GDS functionality." } ]
Exercise Classification with Machine Learning (Part I) | by Trevor Phillips | Towards Data Science
In this two-part post we’re taking a deep dive into a specific problem: classifying videos of people performing various exercises. The first post will focus on a more algorithmic approach using k-Nearest Neighbors to classify an unknown video, and in the second post, we’ll look at an exclusively machine learning (ML) approach. Code for everything we’re going to cover can be found on this GitHub repository. The algorithmic approach (Part I) is written in Swift and is available as a CocoaPod. The ML approach (Part II) is written in Python/TensorFlow and can be found as part of the GitHub repository. We want to build a system which takes as input a video of a person performing an exercise and outputs a class label which describes the video. Ideally, the video can be of any length, with any frame rate, and from any camera angle. A subset of class labels might be something as follows: back squats — correct form back squats — incorrect form push-ups — correct form push-ups — incorrect form And so on... How to build such a system? One of the trickiest parts is that we need to identify relationships between frames — that is, relationships between the position of the person at each frame. This means we’re dealing with data structures in the time domain, which we’ll call timeseries. Given some “unknown” timeseries which has been constructed from an input video, we want to assign a label to the timeseries according to the exercise we predict. I mentioned that we will construct the timeseries from an input video, but how do we do that? Let’s assume that each video contains footage of a single person performing some type of exercise. My strategy was to: Standardize the length of each videoDetermine the person’s “pose” using 14 key body points, for each frameCreate a timeseries data structure representing change in pose over timeFilter out noise in the data Standardize the length of each video Determine the person’s “pose” using 14 key body points, for each frame Create a timeseries data structure representing change in pose over time Filter out noise in the data It’s not realistic to process a 5-minute video, so to enforce some consistency in our data, we’ll standardize the length of each video. I did this by sub-sampling a 5-second clip from the middle of each video, under the assumption that whatever is happening in the middle is “representative” of the entire video. For videos under 5 seconds, we use the whole thing. Given a frame (image) of the sub-clip, we want to determine the person’s pose in the image. It is already possible to estimate body points (called pose estimation), for example using the project OpenPose. I took a pre-trained convolutional neural net (CNN) from here and used it to estimate pose for each video frame. With this ML model, we get an (x, y) coordinate for each of 14 body parts along with a confidence level in [0, 1] for the accuracy of each body part’s location. You can see implementation details on the GitHub repo. Now everything is in place to construct a timeseries from a video. To put it together, we simply concatenate pose data for each video frame. The resulting timeseries has 4 dimensions: Time: indexed by the video frame Body part: 14 body parts in total x-position: x-coordinate of a body part, normalized from [0, 1] y-position: y-coordinate of a body part, normalized from [0, 1] Since there are 14 body parts and an (x, y) coordinate for each, we can visualize the timeseries data structure as 28 waves (14 x2 = 28) which change over time. The (x, y) coordinates are normalized by dividing each body part position by the width or height of the frame, respectively. The lower-left corner of the frame acts as our coordinate system’s origin. At this point, we have a timeseries, but the noise it contains may lead to inaccurate predictions when we try to classify and assign a class label. To smooth noisy data, I used a filter called LOESS (Locally Weighted Scatterplot Smoothing). The general idea is that for each “raw” data point, we derive a better estimate by taking a weighted average of neighboring points. Neighbors which are closer to the point we’re considering will have a higher weight and thus more effect on the average. The nice thing about LOESS (as compared to, for example, a Kalman filter) is that there is only one parameter to consider. This parameter controls how much influence neighboring points have on the weighted average. The bigger it is, the more influence neighbors have and therefore the smoother the resulting curve. Here’s an example of our timeseries data before and after LOESS filtering: Now that we have a method to pre-process an input video into usable data, we need to analyze the resulting timeseries and classify videos. Analysis can be done in many ways, but in this post, we’re going to focus on an algorithm called k-Nearest Neighbors. Basically, we’ll compare the unknown timeseries with a lot of known timeseries, and find the closest match (k=1). Comparison is done using a distance function, which we’ll talk about later. Once we find the nearest neighbor of our unknown video, we predict that the unknown video has the same class label as the known item, since they are closest according to our distance function. Finding the distance between points in 2 dimensions is easy: dist = sqrt( (x2 — x1)^2 + (y2 — y1)^2 ) But what about the distance between two waves? Or the distance between two timeseries? Not so easy... To make it more complicated, imagine the following scenario: We have a “known” labeled timeseries from a video of a person doing push-ups. He does 1 push-up every 2 seconds and begins doing them 1 second into the video. Now we want to label an “unknown” timeseries from a video of someone else doing push-ups. He does 1 push-up every 3 seconds and begins doing them 2 seconds into the video. Even though these timeseries are from the same exercise (push-ups), there are two problems which will emerge when we try to compare the “unknown” timeseries with the “known” timeseries: differing frequency and differing phase shift. To help solve the problems of differing frequency and phase shift, we’re going to employ an algorithm called Dynamic Time Warping (DTW). This is a non-linear alignment strategy using dynamic programming. As with many dynamic programming algorithms, in DTW we fill up a matrix where each cell’s value is a function relative to the neighboring cells. Let’s say we’re comparing timeseries s of length M against timeseries q of length N. Each row of our matrix corresponds to a point in time for s, and each column corresponds to a point in time for q. Thus the matrix is MxN. The cost of a cell at row m (0 <= m < M) and column n (0 <= n < N) is as follows: cost[m, n] = distance(s[m], q[n]) + min(cost[m-1, n], cost[m, n-1], cost[m-1, n-1]) Think of s[m] as the pose of the person in the unknown video at time m and q[n] as the pose of the person in the known video at time n. The distance distance(s[m], q[n]) between them is the sum of the 2D distance between each body part coordinate. I also played around with a weighted sum of the distance between each body part, assigning more weight to body parts which are relevant for particular exercises. For example, feet are not relevant when analyzing squats (because they don’t move) so they are weighted less. But for jumping, feet move a lot and are weighted more. This technique improved the algorithm’s accuracy a little bit. Once we fill up the DTW cost matrix, the last cell we compute is effectively the smallest “distance” between two timeseries. It’s possible to improve the efficiency of DTW by using something called a “warping window.” In short, this means we don’t compute the entire cost matrix but rather a smaller diagonal section of the matrix. If you’re interested in learning more, check out the paper Fast Time Series Classification Using Numerosity Reduction. Now we’ve built a system which takes an unknown video as input, converts it to a timeseries, and compares it with timeseries from the set of labeled videos using DTW. The label of the closest-matching known timeseries will be used to classify the unknown video. To evaluate the system, I used a dataset of ~100 videos and 3 exercises: bodyweight squats, pull-ups, and push-ups. The exercise in each video was performed either correctly or incorrectly (with improper technique). Videos were recorded from the front, side, and back of the person. For side angles, I generated a second video by flipping the original across the y-axis. 80% of the videos were used as “labeled” data and the remaining 20% withheld for testing the algorithm’s accuracy. Test results show that the algorithm is very good at distinguishing between exercises (90–100% accuracy) but not so good at classifying variations within an exercise (correct vs. incorrect technique). These variations can be subtle and hard to track, and the maximum accuracy I could achieve in this respect was ~65%. A major disadvantage to the k-Nearest Neighbors algorithm is that the inference time — that is, the time to classify an unknown video — grows proportionally with the size of the labeled data set, since we compare an unknown timeseries with every labeled item. In Part II, we’re going to explore an end-to-end approach using a ML model to classify videos, thereby making the inference time constant. The main GitHub repository with video processing and DTW OpenPose Pose estimation on iOS Locally Weighted Scatterplot Smoothing (LOESS) Dynamic Time Warping (DTW) DTW “warping window”
[ { "code": null, "e": 303, "s": 172, "text": "In this two-part post we’re taking a deep dive into a specific problem: classifying videos of people performing various exercises." }, { "code": null, "e": 501, "s": 303, "text": "The first post will focus on a more algorithmic approach using k-Nearest Neighbors to classify an unknown video, and in the second post, we’ll look at an exclusively machine learning (ML) approach." }, { "code": null, "e": 777, "s": 501, "text": "Code for everything we’re going to cover can be found on this GitHub repository. The algorithmic approach (Part I) is written in Swift and is available as a CocoaPod. The ML approach (Part II) is written in Python/TensorFlow and can be found as part of the GitHub repository." }, { "code": null, "e": 1065, "s": 777, "text": "We want to build a system which takes as input a video of a person performing an exercise and outputs a class label which describes the video. Ideally, the video can be of any length, with any frame rate, and from any camera angle. A subset of class labels might be something as follows:" }, { "code": null, "e": 1092, "s": 1065, "text": "back squats — correct form" }, { "code": null, "e": 1121, "s": 1092, "text": "back squats — incorrect form" }, { "code": null, "e": 1145, "s": 1121, "text": "push-ups — correct form" }, { "code": null, "e": 1171, "s": 1145, "text": "push-ups — incorrect form" }, { "code": null, "e": 1184, "s": 1171, "text": "And so on..." }, { "code": null, "e": 1466, "s": 1184, "text": "How to build such a system? One of the trickiest parts is that we need to identify relationships between frames — that is, relationships between the position of the person at each frame. This means we’re dealing with data structures in the time domain, which we’ll call timeseries." }, { "code": null, "e": 1628, "s": 1466, "text": "Given some “unknown” timeseries which has been constructed from an input video, we want to assign a label to the timeseries according to the exercise we predict." }, { "code": null, "e": 1841, "s": 1628, "text": "I mentioned that we will construct the timeseries from an input video, but how do we do that? Let’s assume that each video contains footage of a single person performing some type of exercise. My strategy was to:" }, { "code": null, "e": 2048, "s": 1841, "text": "Standardize the length of each videoDetermine the person’s “pose” using 14 key body points, for each frameCreate a timeseries data structure representing change in pose over timeFilter out noise in the data" }, { "code": null, "e": 2085, "s": 2048, "text": "Standardize the length of each video" }, { "code": null, "e": 2156, "s": 2085, "text": "Determine the person’s “pose” using 14 key body points, for each frame" }, { "code": null, "e": 2229, "s": 2156, "text": "Create a timeseries data structure representing change in pose over time" }, { "code": null, "e": 2258, "s": 2229, "text": "Filter out noise in the data" }, { "code": null, "e": 2571, "s": 2258, "text": "It’s not realistic to process a 5-minute video, so to enforce some consistency in our data, we’ll standardize the length of each video. I did this by sub-sampling a 5-second clip from the middle of each video, under the assumption that whatever is happening in the middle is “representative” of the entire video." }, { "code": null, "e": 2623, "s": 2571, "text": "For videos under 5 seconds, we use the whole thing." }, { "code": null, "e": 2828, "s": 2623, "text": "Given a frame (image) of the sub-clip, we want to determine the person’s pose in the image. It is already possible to estimate body points (called pose estimation), for example using the project OpenPose." }, { "code": null, "e": 3157, "s": 2828, "text": "I took a pre-trained convolutional neural net (CNN) from here and used it to estimate pose for each video frame. With this ML model, we get an (x, y) coordinate for each of 14 body parts along with a confidence level in [0, 1] for the accuracy of each body part’s location. You can see implementation details on the GitHub repo." }, { "code": null, "e": 3341, "s": 3157, "text": "Now everything is in place to construct a timeseries from a video. To put it together, we simply concatenate pose data for each video frame. The resulting timeseries has 4 dimensions:" }, { "code": null, "e": 3374, "s": 3341, "text": "Time: indexed by the video frame" }, { "code": null, "e": 3408, "s": 3374, "text": "Body part: 14 body parts in total" }, { "code": null, "e": 3472, "s": 3408, "text": "x-position: x-coordinate of a body part, normalized from [0, 1]" }, { "code": null, "e": 3536, "s": 3472, "text": "y-position: y-coordinate of a body part, normalized from [0, 1]" }, { "code": null, "e": 3697, "s": 3536, "text": "Since there are 14 body parts and an (x, y) coordinate for each, we can visualize the timeseries data structure as 28 waves (14 x2 = 28) which change over time." }, { "code": null, "e": 3897, "s": 3697, "text": "The (x, y) coordinates are normalized by dividing each body part position by the width or height of the frame, respectively. The lower-left corner of the frame acts as our coordinate system’s origin." }, { "code": null, "e": 4138, "s": 3897, "text": "At this point, we have a timeseries, but the noise it contains may lead to inaccurate predictions when we try to classify and assign a class label. To smooth noisy data, I used a filter called LOESS (Locally Weighted Scatterplot Smoothing)." }, { "code": null, "e": 4391, "s": 4138, "text": "The general idea is that for each “raw” data point, we derive a better estimate by taking a weighted average of neighboring points. Neighbors which are closer to the point we’re considering will have a higher weight and thus more effect on the average." }, { "code": null, "e": 4706, "s": 4391, "text": "The nice thing about LOESS (as compared to, for example, a Kalman filter) is that there is only one parameter to consider. This parameter controls how much influence neighboring points have on the weighted average. The bigger it is, the more influence neighbors have and therefore the smoother the resulting curve." }, { "code": null, "e": 4781, "s": 4706, "text": "Here’s an example of our timeseries data before and after LOESS filtering:" }, { "code": null, "e": 4920, "s": 4781, "text": "Now that we have a method to pre-process an input video into usable data, we need to analyze the resulting timeseries and classify videos." }, { "code": null, "e": 5228, "s": 4920, "text": "Analysis can be done in many ways, but in this post, we’re going to focus on an algorithm called k-Nearest Neighbors. Basically, we’ll compare the unknown timeseries with a lot of known timeseries, and find the closest match (k=1). Comparison is done using a distance function, which we’ll talk about later." }, { "code": null, "e": 5421, "s": 5228, "text": "Once we find the nearest neighbor of our unknown video, we predict that the unknown video has the same class label as the known item, since they are closest according to our distance function." }, { "code": null, "e": 5482, "s": 5421, "text": "Finding the distance between points in 2 dimensions is easy:" }, { "code": null, "e": 5523, "s": 5482, "text": "dist = sqrt( (x2 — x1)^2 + (y2 — y1)^2 )" }, { "code": null, "e": 5625, "s": 5523, "text": "But what about the distance between two waves? Or the distance between two timeseries? Not so easy..." }, { "code": null, "e": 5686, "s": 5625, "text": "To make it more complicated, imagine the following scenario:" }, { "code": null, "e": 6017, "s": 5686, "text": "We have a “known” labeled timeseries from a video of a person doing push-ups. He does 1 push-up every 2 seconds and begins doing them 1 second into the video. Now we want to label an “unknown” timeseries from a video of someone else doing push-ups. He does 1 push-up every 3 seconds and begins doing them 2 seconds into the video." }, { "code": null, "e": 6250, "s": 6017, "text": "Even though these timeseries are from the same exercise (push-ups), there are two problems which will emerge when we try to compare the “unknown” timeseries with the “known” timeseries: differing frequency and differing phase shift." }, { "code": null, "e": 6454, "s": 6250, "text": "To help solve the problems of differing frequency and phase shift, we’re going to employ an algorithm called Dynamic Time Warping (DTW). This is a non-linear alignment strategy using dynamic programming." }, { "code": null, "e": 6599, "s": 6454, "text": "As with many dynamic programming algorithms, in DTW we fill up a matrix where each cell’s value is a function relative to the neighboring cells." }, { "code": null, "e": 6905, "s": 6599, "text": "Let’s say we’re comparing timeseries s of length M against timeseries q of length N. Each row of our matrix corresponds to a point in time for s, and each column corresponds to a point in time for q. Thus the matrix is MxN. The cost of a cell at row m (0 <= m < M) and column n (0 <= n < N) is as follows:" }, { "code": null, "e": 6996, "s": 6905, "text": "cost[m, n] = distance(s[m], q[n]) + min(cost[m-1, n], cost[m, n-1], cost[m-1, n-1])" }, { "code": null, "e": 7244, "s": 6996, "text": "Think of s[m] as the pose of the person in the unknown video at time m and q[n] as the pose of the person in the known video at time n. The distance distance(s[m], q[n]) between them is the sum of the 2D distance between each body part coordinate." }, { "code": null, "e": 7635, "s": 7244, "text": "I also played around with a weighted sum of the distance between each body part, assigning more weight to body parts which are relevant for particular exercises. For example, feet are not relevant when analyzing squats (because they don’t move) so they are weighted less. But for jumping, feet move a lot and are weighted more. This technique improved the algorithm’s accuracy a little bit." }, { "code": null, "e": 7760, "s": 7635, "text": "Once we fill up the DTW cost matrix, the last cell we compute is effectively the smallest “distance” between two timeseries." }, { "code": null, "e": 8086, "s": 7760, "text": "It’s possible to improve the efficiency of DTW by using something called a “warping window.” In short, this means we don’t compute the entire cost matrix but rather a smaller diagonal section of the matrix. If you’re interested in learning more, check out the paper Fast Time Series Classification Using Numerosity Reduction." }, { "code": null, "e": 8348, "s": 8086, "text": "Now we’ve built a system which takes an unknown video as input, converts it to a timeseries, and compares it with timeseries from the set of labeled videos using DTW. The label of the closest-matching known timeseries will be used to classify the unknown video." }, { "code": null, "e": 8834, "s": 8348, "text": "To evaluate the system, I used a dataset of ~100 videos and 3 exercises: bodyweight squats, pull-ups, and push-ups. The exercise in each video was performed either correctly or incorrectly (with improper technique). Videos were recorded from the front, side, and back of the person. For side angles, I generated a second video by flipping the original across the y-axis. 80% of the videos were used as “labeled” data and the remaining 20% withheld for testing the algorithm’s accuracy." }, { "code": null, "e": 9152, "s": 8834, "text": "Test results show that the algorithm is very good at distinguishing between exercises (90–100% accuracy) but not so good at classifying variations within an exercise (correct vs. incorrect technique). These variations can be subtle and hard to track, and the maximum accuracy I could achieve in this respect was ~65%." }, { "code": null, "e": 9412, "s": 9152, "text": "A major disadvantage to the k-Nearest Neighbors algorithm is that the inference time — that is, the time to classify an unknown video — grows proportionally with the size of the labeled data set, since we compare an unknown timeseries with every labeled item." }, { "code": null, "e": 9551, "s": 9412, "text": "In Part II, we’re going to explore an end-to-end approach using a ML model to classify videos, thereby making the inference time constant." }, { "code": null, "e": 9608, "s": 9551, "text": "The main GitHub repository with video processing and DTW" }, { "code": null, "e": 9617, "s": 9608, "text": "OpenPose" }, { "code": null, "e": 9640, "s": 9617, "text": "Pose estimation on iOS" }, { "code": null, "e": 9687, "s": 9640, "text": "Locally Weighted Scatterplot Smoothing (LOESS)" }, { "code": null, "e": 9714, "s": 9687, "text": "Dynamic Time Warping (DTW)" } ]
strupr() function in c - GeeksforGeeks
28 Sep, 2018 The strupr( ) function is used to converts a given string to uppercase. Syntax: char *strupr(char *str); Parameter: str: This represents the given string which we want to convert into uppercase. Returns: It returns the modified string obtained after converting the characters of the given string str to uppercase. Below programs illustrate the strupr() function in C: Example 1:- // c program to demonstrate// example of strupr() function.#include<stdio.h>#include<string.h> int main(){ char str[ ] = "geeksforgeeks is the best"; //converting the given string into uppercase. printf("%s\n", strupr (str)); return 0;} Output: GEEKSFORGEEKS IS THE BEST Example 2:- // c program to demonstrate// example of strupr() function. #include<stdio.h>#include <string.h> int main(){ char str[] = "CompuTer ScienCe PoRTAl fOr geeKS"; printf("Given string is: %s\n", str); printf("\nstring after converting to the uppercase is: %s", strupr(str)); return 0;} Output: Given string is: CompuTer ScienCe PoRTAl fOr geeKS string after converting to the uppercase is: COMPUTER SCIENCE PORTAL FOR GEEKS Note : This is a non-standard function that works only with older versions of Microsoft C. C-String C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Multidimensional Arrays in C / C++ rand() and srand() in C/C++ fork() in C Core Dump (Segmentation fault) in C/C++ Left Shift and Right Shift Operators in C/C++ Command line arguments in C/C++ Different methods to reverse a string in C/C++ Substring in C++ Function Pointer in C TCP Server-Client implementation in C
[ { "code": null, "e": 24599, "s": 24571, "text": "\n28 Sep, 2018" }, { "code": null, "e": 24671, "s": 24599, "text": "The strupr( ) function is used to converts a given string to uppercase." }, { "code": null, "e": 24679, "s": 24671, "text": "Syntax:" }, { "code": null, "e": 24705, "s": 24679, "text": "char *strupr(char *str);\n" }, { "code": null, "e": 24716, "s": 24705, "text": "Parameter:" }, { "code": null, "e": 24795, "s": 24716, "text": "str: This represents the given string which we want to convert into uppercase." }, { "code": null, "e": 24914, "s": 24795, "text": "Returns: It returns the modified string obtained after converting the characters of the given string str to uppercase." }, { "code": null, "e": 24968, "s": 24914, "text": "Below programs illustrate the strupr() function in C:" }, { "code": null, "e": 24980, "s": 24968, "text": "Example 1:-" }, { "code": "// c program to demonstrate// example of strupr() function.#include<stdio.h>#include<string.h> int main(){ char str[ ] = \"geeksforgeeks is the best\"; //converting the given string into uppercase. printf(\"%s\\n\", strupr (str)); return 0;}", "e": 25231, "s": 24980, "text": null }, { "code": null, "e": 25239, "s": 25231, "text": "Output:" }, { "code": null, "e": 25266, "s": 25239, "text": "GEEKSFORGEEKS IS THE BEST\n" }, { "code": null, "e": 25278, "s": 25266, "text": "Example 2:-" }, { "code": "// c program to demonstrate// example of strupr() function. #include<stdio.h>#include <string.h> int main(){ char str[] = \"CompuTer ScienCe PoRTAl fOr geeKS\"; printf(\"Given string is: %s\\n\", str); printf(\"\\nstring after converting to the uppercase is: %s\", strupr(str)); return 0;}", "e": 25570, "s": 25278, "text": null }, { "code": null, "e": 25578, "s": 25570, "text": "Output:" }, { "code": null, "e": 25710, "s": 25578, "text": "Given string is: CompuTer ScienCe PoRTAl fOr geeKS\n\nstring after converting to the uppercase is: COMPUTER SCIENCE PORTAL FOR GEEKS\n" }, { "code": null, "e": 25801, "s": 25710, "text": "Note : This is a non-standard function that works only with older versions of Microsoft C." }, { "code": null, "e": 25810, "s": 25801, "text": "C-String" }, { "code": null, "e": 25821, "s": 25810, "text": "C Language" }, { "code": null, "e": 25919, "s": 25821, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25928, "s": 25919, "text": "Comments" }, { "code": null, "e": 25941, "s": 25928, "text": "Old Comments" }, { "code": null, "e": 25976, "s": 25941, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 26004, "s": 25976, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 26016, "s": 26004, "text": "fork() in C" }, { "code": null, "e": 26056, "s": 26016, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 26102, "s": 26056, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 26134, "s": 26102, "text": "Command line arguments in C/C++" }, { "code": null, "e": 26181, "s": 26134, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 26198, "s": 26181, "text": "Substring in C++" }, { "code": null, "e": 26220, "s": 26198, "text": "Function Pointer in C" } ]
Lexicographic rank of a string using STL - GeeksforGeeks
12 Apr, 2019 You are given a string, find its rank among all its permutations sorted lexicographically. Examples: Input : str[] = "acb" Output : Rank = 2 Input : str[] = "string" Output : Rank = 598 Input : str[] = "cba" Output : Rank = 6 We have already discussed solutions to find Lexicographic rank of string In this post, we use the STL function “next_permutation ()” to generate all possible permutations of the given string and, as it gives us permutations in lexicographic order, we will put an iterator to find the rank of each string. While iterating when Our permuted string becomes identical to the original input string, we break from the loop and the iterator value for the last iteration is our required result. // C++ program to print rank of // string using next_permute()#include <bits/stdc++.h>using namespace std; // Function to print rank of string// using next_permute()int findRank(string str){ // store original string string orgStr = str; // Sort the string in lexicographically // ascending order sort(str.begin(), str.end()); // Keep iterating until // we reach equality condition long int i = 1; do { // check for nth iteration if (str == orgStr) break; i++; } while (next_permutation(str.begin(), str.end())); // return iterator value return i;} // Driver codeint main(){ string str = "GEEKS"; cout << findRank(str); return 0;} Output: 25 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 contribute.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. Akanksha_Rai number-theory STL Combinatorial Strings number-theory Strings Combinatorial STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ways to sum to N using Natural Numbers up to K with repetitions allowed Generate all possible combinations of K numbers that sums to N Combinations with repetitions Generate all possible combinations of at most X characters from a given array Given number of matches played, find number of teams in tournament Write a program to reverse an array or string Reverse a string in Java C++ Data Types Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 26721, "s": 26693, "text": "\n12 Apr, 2019" }, { "code": null, "e": 26812, "s": 26721, "text": "You are given a string, find its rank among all its permutations sorted lexicographically." }, { "code": null, "e": 26822, "s": 26812, "text": "Examples:" }, { "code": null, "e": 26950, "s": 26822, "text": "Input : str[] = \"acb\"\nOutput : Rank = 2\n\nInput : str[] = \"string\"\nOutput : Rank = 598\n\nInput : str[] = \"cba\"\nOutput : Rank = 6\n" }, { "code": null, "e": 27023, "s": 26950, "text": "We have already discussed solutions to find Lexicographic rank of string" }, { "code": null, "e": 27437, "s": 27023, "text": "In this post, we use the STL function “next_permutation ()” to generate all possible permutations of the given string and, as it gives us permutations in lexicographic order, we will put an iterator to find the rank of each string. While iterating when Our permuted string becomes identical to the original input string, we break from the loop and the iterator value for the last iteration is our required result." }, { "code": "// C++ program to print rank of // string using next_permute()#include <bits/stdc++.h>using namespace std; // Function to print rank of string// using next_permute()int findRank(string str){ // store original string string orgStr = str; // Sort the string in lexicographically // ascending order sort(str.begin(), str.end()); // Keep iterating until // we reach equality condition long int i = 1; do { // check for nth iteration if (str == orgStr) break; i++; } while (next_permutation(str.begin(), str.end())); // return iterator value return i;} // Driver codeint main(){ string str = \"GEEKS\"; cout << findRank(str); return 0;}", "e": 28159, "s": 27437, "text": null }, { "code": null, "e": 28167, "s": 28159, "text": "Output:" }, { "code": null, "e": 28171, "s": 28167, "text": "25\n" }, { "code": null, "e": 28486, "s": 28171, "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 contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 28611, "s": 28486, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28624, "s": 28611, "text": "Akanksha_Rai" }, { "code": null, "e": 28638, "s": 28624, "text": "number-theory" }, { "code": null, "e": 28642, "s": 28638, "text": "STL" }, { "code": null, "e": 28656, "s": 28642, "text": "Combinatorial" }, { "code": null, "e": 28664, "s": 28656, "text": "Strings" }, { "code": null, "e": 28678, "s": 28664, "text": "number-theory" }, { "code": null, "e": 28686, "s": 28678, "text": "Strings" }, { "code": null, "e": 28700, "s": 28686, "text": "Combinatorial" }, { "code": null, "e": 28704, "s": 28700, "text": "STL" }, { "code": null, "e": 28802, "s": 28704, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28874, "s": 28802, "text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed" }, { "code": null, "e": 28937, "s": 28874, "text": "Generate all possible combinations of K numbers that sums to N" }, { "code": null, "e": 28967, "s": 28937, "text": "Combinations with repetitions" }, { "code": null, "e": 29045, "s": 28967, "text": "Generate all possible combinations of at most X characters from a given array" }, { "code": null, "e": 29112, "s": 29045, "text": "Given number of matches played, find number of teams in tournament" }, { "code": null, "e": 29158, "s": 29112, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 29183, "s": 29158, "text": "Reverse a string in Java" }, { "code": null, "e": 29198, "s": 29183, "text": "C++ Data Types" }, { "code": null, "e": 29232, "s": 29198, "text": "Longest Common Subsequence | DP-4" } ]
GATE | GATE CS 2010 | Question 65 - GeeksforGeeks
27 Jul, 2021 Which of the following statements are true? I. Shortest remaining time first scheduling may cause starvation II. Preemptive scheduling may cause starvation III. Round robin is better than FCFS in terms of response time (A) I only(B) I and III only(C) II and III only(D) I, II and IIIAnswer: (D)Explanation: I) Shortest remaining time first scheduling is a pre-emptive version of shortest job scheduling. In SRTF, job with the shortest CPU burst will be scheduled first. Because of this process, It may cause starvation as shorter processes may keep coming and a long CPU burst process never gets CPU. II) Pre-emptive just means a process before completing its execution is stopped and other process can start execution. The stopped process can later come back and continue from where it was stopped. In pre-emptive scheduling, suppose process P1 is executing in CPU and after some time process P2 with high priority then P1 will arrive in ready queue then p1 is pre-empted and p2 will brought into CPU for execution. In this way if process which is arriving in ready queue is of higher priority then p1, then p1 is always pre-empted and it may possible that it suffer from starvation. III) round robin will give better response time then FCFS ,in FCFS when process is executing ,it executed up to its complete burst time, but in round robin it will execute up to time quantum. So Round Robin Scheduling improves response time as all processes get CPU after a specified time. So, I,II,III are true which is option (D). Reference:https://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/5_CPU_Scheduling.htmlhttps://www.geeksforgeeks.org/operating-systems-set-7/ This solution is contributed by Nitika Bansal Watch GeeksforGeeks Video Explanation : YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersCPU Scheduling GATE Previous Year Questions with Viomesh SinghWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0024:21 / 39:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=y1BbjvO_xog" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2010 GATE-GATE CS 2010 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": 25627, "s": 25599, "text": "\n27 Jul, 2021" }, { "code": null, "e": 25671, "s": 25627, "text": "Which of the following statements are true?" }, { "code": null, "e": 25846, "s": 25671, "text": "I. Shortest remaining time first scheduling may cause starvation\nII. Preemptive scheduling may cause starvation\nIII. Round robin is better than FCFS in terms of response time" }, { "code": null, "e": 26228, "s": 25846, "text": "(A) I only(B) I and III only(C) II and III only(D) I, II and IIIAnswer: (D)Explanation: I) Shortest remaining time first scheduling is a pre-emptive version of shortest job scheduling. In SRTF, job with the shortest CPU burst will be scheduled first. Because of this process, It may cause starvation as shorter processes may keep coming and a long CPU burst process never gets CPU." }, { "code": null, "e": 26812, "s": 26228, "text": "II) Pre-emptive just means a process before completing its execution is stopped and other process can start execution. The stopped process can later come back and continue from where it was stopped. In pre-emptive scheduling, suppose process P1 is executing in CPU and after some time process P2 with high priority then P1 will arrive in ready queue then p1 is pre-empted and p2 will brought into CPU for execution. In this way if process which is arriving in ready queue is of higher priority then p1, then p1 is always pre-empted and it may possible that it suffer from starvation." }, { "code": null, "e": 27102, "s": 26812, "text": "III) round robin will give better response time then FCFS ,in FCFS when process is executing ,it executed up to its complete burst time, but in round robin it will execute up to time quantum. So Round Robin Scheduling improves response time as all processes get CPU after a specified time." }, { "code": null, "e": 27145, "s": 27102, "text": "So, I,II,III are true which is option (D)." }, { "code": null, "e": 27290, "s": 27145, "text": "Reference:https://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/5_CPU_Scheduling.htmlhttps://www.geeksforgeeks.org/operating-systems-set-7/" }, { "code": null, "e": 27336, "s": 27290, "text": "This solution is contributed by Nitika Bansal" }, { "code": null, "e": 27376, "s": 27336, "text": "Watch GeeksforGeeks Video Explanation :" }, { "code": null, "e": 28267, "s": 27376, "text": "YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersCPU Scheduling GATE Previous Year Questions with Viomesh SinghWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0024:21 / 39:01•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=y1BbjvO_xog\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 28280, "s": 28267, "text": "GATE-CS-2010" }, { "code": null, "e": 28298, "s": 28280, "text": "GATE-GATE CS 2010" }, { "code": null, "e": 28303, "s": 28298, "text": "GATE" }, { "code": null, "e": 28401, "s": 28303, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28435, "s": 28401, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 28469, "s": 28435, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 28503, "s": 28469, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 28536, "s": 28503, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 28572, "s": 28536, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 28606, "s": 28572, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 28642, "s": 28606, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 28676, "s": 28642, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 28710, "s": 28676, "text": "GATE | GATE-CS-2009 | Question 38" } ]
map upper_bound() function in C++ STL - GeeksforGeeks
03 Jun, 2020 The map::upper_bound() is a built-in function in C++ STL which returns an iterator pointing to the immediate next element just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator returned points to the number of elements in the map container as key and element=0. Syntax: map_name.upper_bound(key) Parameters: This function accepts a single mandatory parameter key which specifies the element whose upper_bound is returned. Return Value: The function returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then returned iterator points to map_name.end(). Note that end() is a special iterator that does not store address of a valid member of a map. Below is the implementation of the above approach: // C++ function for illustration// map::upper_bound() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 12, 30 }); mp.insert({ 11, 10 }); mp.insert({ 15, 50 }); mp.insert({ 14, 40 }); // when 11 is present auto it = mp.upper_bound(11); cout << "The upper bound of key 11 is "; cout << (*it).first << " " << (*it).second << endl; // when 13 is not present it = mp.upper_bound(13); cout << "The upper bound of key 13 is "; cout << (*it).first << " " << (*it).second << endl; // when 17 is exceeds the maximum key, so size // of mp is returned as key and value as 0. it = mp.upper_bound(17); cout << "The upper bound of key 17 is "; cout << (*it).first << " " << (*it).second; return 0;} The upper bound of key 11 is 12 30 The upper bound of key 13 is 14 40 The upper bound of key 17 is 4 0 devsinghindra CPP-Functions cpp-map STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Bitwise Operators in C/C++ Virtual Function in C++ Constructors in C++ Templates in C++ with Examples Operator Overloading in C++ Socket Programming in C/C++ vector erase() and clear() in C++ Object Oriented Programming in C++
[ { "code": null, "e": 25762, "s": 25734, "text": "\n03 Jun, 2020" }, { "code": null, "e": 26085, "s": 25762, "text": "The map::upper_bound() is a built-in function in C++ STL which returns an iterator pointing to the immediate next element just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator returned points to the number of elements in the map container as key and element=0." }, { "code": null, "e": 26093, "s": 26085, "text": "Syntax:" }, { "code": null, "e": 26119, "s": 26093, "text": "map_name.upper_bound(key)" }, { "code": null, "e": 26245, "s": 26119, "text": "Parameters: This function accepts a single mandatory parameter key which specifies the element whose upper_bound is returned." }, { "code": null, "e": 26581, "s": 26245, "text": "Return Value: The function returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then returned iterator points to map_name.end(). Note that end() is a special iterator that does not store address of a valid member of a map." }, { "code": null, "e": 26632, "s": 26581, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ function for illustration// map::upper_bound() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 12, 30 }); mp.insert({ 11, 10 }); mp.insert({ 15, 50 }); mp.insert({ 14, 40 }); // when 11 is present auto it = mp.upper_bound(11); cout << \"The upper bound of key 11 is \"; cout << (*it).first << \" \" << (*it).second << endl; // when 13 is not present it = mp.upper_bound(13); cout << \"The upper bound of key 13 is \"; cout << (*it).first << \" \" << (*it).second << endl; // when 17 is exceeds the maximum key, so size // of mp is returned as key and value as 0. it = mp.upper_bound(17); cout << \"The upper bound of key 17 is \"; cout << (*it).first << \" \" << (*it).second; return 0;}", "e": 27497, "s": 26632, "text": null }, { "code": null, "e": 27601, "s": 27497, "text": "The upper bound of key 11 is 12 30\nThe upper bound of key 13 is 14 40\nThe upper bound of key 17 is 4 0\n" }, { "code": null, "e": 27615, "s": 27601, "text": "devsinghindra" }, { "code": null, "e": 27629, "s": 27615, "text": "CPP-Functions" }, { "code": null, "e": 27637, "s": 27629, "text": "cpp-map" }, { "code": null, "e": 27641, "s": 27637, "text": "STL" }, { "code": null, "e": 27645, "s": 27641, "text": "C++" }, { "code": null, "e": 27649, "s": 27645, "text": "STL" }, { "code": null, "e": 27653, "s": 27649, "text": "CPP" }, { "code": null, "e": 27751, "s": 27653, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27770, "s": 27751, "text": "Inheritance in C++" }, { "code": null, "e": 27794, "s": 27770, "text": "C++ Classes and Objects" }, { "code": null, "e": 27821, "s": 27794, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 27845, "s": 27821, "text": "Virtual Function in C++" }, { "code": null, "e": 27865, "s": 27845, "text": "Constructors in C++" }, { "code": null, "e": 27896, "s": 27865, "text": "Templates in C++ with Examples" }, { "code": null, "e": 27924, "s": 27896, "text": "Operator Overloading in C++" }, { "code": null, "e": 27952, "s": 27924, "text": "Socket Programming in C/C++" }, { "code": null, "e": 27986, "s": 27952, "text": "vector erase() and clear() in C++" } ]
Maximize count of array elements required to obtain given sum - GeeksforGeeks
23 Jan, 2022 Given an integer V and an array arr[] consisting of N integers, the task is to find the maximum number of array elements that can be selected from array arr[] to obtain the sum V. Each array element can be chosen any number of times. If the sum cannot be obtained, print -1. Examples: Input: arr[] = {25, 10, 5}, V = 30Output: 6Explanation:To obtain sum 30, select arr[2] (= 5), 6 times.Therefore, the count is 6. Input: arr[] = {9, 6, 4, 3}, V = 11Output: 3Explanation:To obtain sum 11, possible combinations is : 4,4,3Therefore, the count is 3 Naive Approach: The simplest approach is to recursively find the maximum number of array elements to generate the sum V using array elements from indices 0 to j before finding the maximum number of elements required to generate V using elements from indices 0 to i where j < i < N. After completing the above steps, print the count of array elements required to obtain the given sum V. Time Complexity: O(VN)Auxiliary Space: O(N) Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming. Follow the below steps to solve the problem: Initialize an array table[] of size V + 1 where table[i] will store the optimal solution to obtain sum i. Initialize table[] with -1 and table[0] with 0 as 0 array elements are required to obtain the value 0. For each value from i = 0 to V, calculate the maximum number of elements from the array required by the following DP transition: table[i] = Max(table[i – arr[j]], table[i]), Where table[i-arr[j]]!=-1 where 1 ≤ i ≤ V and 0 ≤ j ≤ N After completing the above steps, print the value of the table[V] which is the required answer. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++14 program for the above approach#include <bits/stdc++.h>using namespace std; // Function that count the maximum// number of elements to obtain sum Vint maxCount(vector<int> arr, int m, int V){ // Stores the maximum number of // elements required to obtain V vector<int> table(V + 1); // Base Case table[0] = 0; // Initialize all table values // as Infinite for (int i = 1; i <= V; i++) table[i] = -1; // Find the max arr required // for all values from 1 to V for (int i = 1; i <= V; i++) { // Go through all arr // smaller than i for (int j = 0; j < m; j++) { // If current coin value // is less than i if (arr[j] <= i) { int sub_res = table[i - arr[j]]; // Update table[i] if (sub_res != -1 && sub_res + 1 > table[i]) table[i] = sub_res + 1; } } } // Return the final count return table[V];} // Driver Codeint main(){ // Given array vector<int> arr = { 25, 10, 5 }; int m = arr.size(); // Given sum V int V = 30; // Function call cout << (maxCount(arr, m, V)); return 0;} // This code is contributed by mohit kumar 29 // Java program for the above approachimport java.io.*; class GFG { // Function that count the maximum // number of elements to obtain sum V static int maxCount(int arr[], int m, int V) { // Stores the maximum number of // elements required to obtain V int table[] = new int[V + 1]; // Base Case table[0] = 0; // Initialize all table values // as Infinite for (int i = 1; i <= V; i++) table[i] = -1; // Find the max arr required // for all values from 1 to V for (int i = 1; i <= V; i++) { // Go through all arr // smaller than i for (int j = 0; j < m; j++) { // If current coin value // is less than i if (arr[j] <= i) { int sub_res = table[i - arr[j]]; // Update table[i] if (sub_res != -1 && sub_res + 1 > table[i]) table[i] = sub_res + 1; } } } // Return the final count return table[V]; } // Driver Code public static void main(String[] args) { // Given array int arr[] = { 25, 10, 5 }; int m = arr.length; // Given sum V int V = 30; // Function Call System.out.println(maxCount(arr, m, V)); }} # Python program for the# above approach # Function that count# the maximum number of# elements to obtain sum Vdef maxCount(arr, m, V): ''' You can assume array elements as domination which are provided to you in infinite quantity just like in coin change problem. I made a small change in logic on coin change problem (minimum number of coins required). There we use to take min(table[i-arr[j]]+1,table[i]), here min is changed with max function. Dry run: assume : target = 10, arr = [2,3,5] table 0 1 2 3 4 5 6 7 8 9 10 0 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 taking first domination = 2 table 0 1 2 3 4 5 6 7 8 9 10 0 -1 1 -1 2 -1 3 -1 4 -1 5 taking second domination = 3 table 0 1 2 3 4 5 6 7 8 9 10 0 -1 1 1 2 -1 3 -1 4 3 5 here for i = 6 we have max(table[i-dom]+1,table[i]) hence => max(table[6-3]+1,table[6]) => max(2,3) => 3 taking third domination = 5 table 0 1 2 3 4 5 6 7 8 9 10 0 -1 1 1 2 1 3 -1 4 3 5 Hence total 5 coins are required (2,2,2,2,2) ''' # Stores the maximum # number of elements # required to obtain V table = [0 for i in range(V+1)] # Base Case table[0] = 0 # Initialize all table # values as Infinite for i in range(1, V + 1, 1): table[i] = -1 # Find the max arr required # for all values from 1 to V for i in range(1, V + 1, 1): # Go through all arr # smaller than i for j in range(0, m, 1): # If current coin value # is less than i if (arr[j] <= i): sub_res = table[i - arr[j]] # Update table[i] if (sub_res != -1 and sub_res + 1 > table[i]): table[i] = sub_res + 1 # Return the final count return table[V] # Driver Codeif __name__ == '__main__': # Given array arr = [25, 10, 5] m = len(arr) # Given sum V V = 30 # Function Call print(f'Maximum number of array elements required : {maxCount(arr, m, V)}') # This code is contributed by Aaryaman Sharma // C# program for the// above approachusing System;class GFG{ // Function that count the// maximum number of elements// to obtain sum Vstatic int maxCount(int[] arr, int m, int V){ // Stores the maximum number of // elements required to obtain V int[] table = new int[V + 1]; // Base Case table[0] = 0; // Initialize all table // values as Infinite for (int i = 1; i <= V; i++) table[i] = -1; // Find the max arr required // for all values from 1 to V for (int i = 1; i <= V; i++) { // Go through all arr // smaller than i for (int j = 0; j < m; j++) { // If current coin value // is less than i if (arr[j] <= i) { int sub_res = table[i - arr[j]]; // Update table[i] if (sub_res != -1 && sub_res + 1 > table[i]) table[i] = sub_res + 1; } } } // Return the final count return table[V];} // Driver codestatic void Main(){ // Given array int[] arr = {25, 10, 5}; int m = arr.Length; // Given sum V int V = 30; // Function Call Console.WriteLine(maxCount(arr, m, V));}} // This code is contributed by divyeshrabadiya07 <script> // Javascript program for the above approach // Function that count the maximum // number of elements to obtain sum V function maxCount(arr, m, V) { // Stores the maximum number of // elements required to obtain V let table = []; // Base Case table[0] = 0; // Initialize all table values // as Infinite for (let i = 1; i <= V; i++) table[i] = -1; // Find the max arr required // for all values from 1 to V for (let i = 1; i <= V; i++) { // Go through all arr // smaller than i for (let j = 0; j < m; j++) { // If current coin value // is less than i if (arr[j] <= i) { let sub_res = table[i - arr[j]]; // Update table[i] if (sub_res != -1 && sub_res + 1 > table[i]) table[i] = sub_res + 1; } } } // Return the final count return table[V]; } // Driver Code // Given array let arr = [ 25, 10, 5 ]; let m = arr.length; // Given sum V let V = 30; // Function Call document.write(maxCount(arr, m, V)); </script> 6 Time Complexity: O(N * V)Auxiliary Space: O(N) mohit kumar 29 divyeshrabadiya07 29AjayKumar aaryamansharma chinmoy1997pal anikakapoor sagartomar9927 germanshephered48 dp-coin-change Arrays Dynamic Programming Recursion Arrays Dynamic Programming Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Count pairs with given sum Window Sliding Technique Reversal algorithm for array rotation Next Greater Element 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 26067, "s": 26039, "text": "\n23 Jan, 2022" }, { "code": null, "e": 26342, "s": 26067, "text": "Given an integer V and an array arr[] consisting of N integers, the task is to find the maximum number of array elements that can be selected from array arr[] to obtain the sum V. Each array element can be chosen any number of times. If the sum cannot be obtained, print -1." }, { "code": null, "e": 26352, "s": 26342, "text": "Examples:" }, { "code": null, "e": 26481, "s": 26352, "text": "Input: arr[] = {25, 10, 5}, V = 30Output: 6Explanation:To obtain sum 30, select arr[2] (= 5), 6 times.Therefore, the count is 6." }, { "code": null, "e": 26613, "s": 26481, "text": "Input: arr[] = {9, 6, 4, 3}, V = 11Output: 3Explanation:To obtain sum 11, possible combinations is : 4,4,3Therefore, the count is 3" }, { "code": null, "e": 27000, "s": 26613, "text": "Naive Approach: The simplest approach is to recursively find the maximum number of array elements to generate the sum V using array elements from indices 0 to j before finding the maximum number of elements required to generate V using elements from indices 0 to i where j < i < N. After completing the above steps, print the count of array elements required to obtain the given sum V. " }, { "code": null, "e": 27044, "s": 27000, "text": "Time Complexity: O(VN)Auxiliary Space: O(N)" }, { "code": null, "e": 27181, "s": 27044, "text": "Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming. Follow the below steps to solve the problem:" }, { "code": null, "e": 27287, "s": 27181, "text": "Initialize an array table[] of size V + 1 where table[i] will store the optimal solution to obtain sum i." }, { "code": null, "e": 27390, "s": 27287, "text": "Initialize table[] with -1 and table[0] with 0 as 0 array elements are required to obtain the value 0." }, { "code": null, "e": 27519, "s": 27390, "text": "For each value from i = 0 to V, calculate the maximum number of elements from the array required by the following DP transition:" }, { "code": null, "e": 27620, "s": 27519, "text": "table[i] = Max(table[i – arr[j]], table[i]), Where table[i-arr[j]]!=-1 where 1 ≤ i ≤ V and 0 ≤ j ≤ N" }, { "code": null, "e": 27716, "s": 27620, "text": "After completing the above steps, print the value of the table[V] which is the required answer." }, { "code": null, "e": 27767, "s": 27716, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27773, "s": 27767, "text": "C++14" }, { "code": null, "e": 27778, "s": 27773, "text": "Java" }, { "code": null, "e": 27786, "s": 27778, "text": "Python3" }, { "code": null, "e": 27789, "s": 27786, "text": "C#" }, { "code": null, "e": 27800, "s": 27789, "text": "Javascript" }, { "code": "// C++14 program for the above approach#include <bits/stdc++.h>using namespace std; // Function that count the maximum// number of elements to obtain sum Vint maxCount(vector<int> arr, int m, int V){ // Stores the maximum number of // elements required to obtain V vector<int> table(V + 1); // Base Case table[0] = 0; // Initialize all table values // as Infinite for (int i = 1; i <= V; i++) table[i] = -1; // Find the max arr required // for all values from 1 to V for (int i = 1; i <= V; i++) { // Go through all arr // smaller than i for (int j = 0; j < m; j++) { // If current coin value // is less than i if (arr[j] <= i) { int sub_res = table[i - arr[j]]; // Update table[i] if (sub_res != -1 && sub_res + 1 > table[i]) table[i] = sub_res + 1; } } } // Return the final count return table[V];} // Driver Codeint main(){ // Given array vector<int> arr = { 25, 10, 5 }; int m = arr.size(); // Given sum V int V = 30; // Function call cout << (maxCount(arr, m, V)); return 0;} // This code is contributed by mohit kumar 29", "e": 29048, "s": 27800, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG { // Function that count the maximum // number of elements to obtain sum V static int maxCount(int arr[], int m, int V) { // Stores the maximum number of // elements required to obtain V int table[] = new int[V + 1]; // Base Case table[0] = 0; // Initialize all table values // as Infinite for (int i = 1; i <= V; i++) table[i] = -1; // Find the max arr required // for all values from 1 to V for (int i = 1; i <= V; i++) { // Go through all arr // smaller than i for (int j = 0; j < m; j++) { // If current coin value // is less than i if (arr[j] <= i) { int sub_res = table[i - arr[j]]; // Update table[i] if (sub_res != -1 && sub_res + 1 > table[i]) table[i] = sub_res + 1; } } } // Return the final count return table[V]; } // Driver Code public static void main(String[] args) { // Given array int arr[] = { 25, 10, 5 }; int m = arr.length; // Given sum V int V = 30; // Function Call System.out.println(maxCount(arr, m, V)); }}", "e": 30452, "s": 29048, "text": null }, { "code": "# Python program for the# above approach # Function that count# the maximum number of# elements to obtain sum Vdef maxCount(arr, m, V): ''' You can assume array elements as domination which are provided to you in infinite quantity just like in coin change problem. I made a small change in logic on coin change problem (minimum number of coins required). There we use to take min(table[i-arr[j]]+1,table[i]), here min is changed with max function. Dry run: assume : target = 10, arr = [2,3,5] table 0 1 2 3 4 5 6 7 8 9 10 0 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 taking first domination = 2 table 0 1 2 3 4 5 6 7 8 9 10 0 -1 1 -1 2 -1 3 -1 4 -1 5 taking second domination = 3 table 0 1 2 3 4 5 6 7 8 9 10 0 -1 1 1 2 -1 3 -1 4 3 5 here for i = 6 we have max(table[i-dom]+1,table[i]) hence => max(table[6-3]+1,table[6]) => max(2,3) => 3 taking third domination = 5 table 0 1 2 3 4 5 6 7 8 9 10 0 -1 1 1 2 1 3 -1 4 3 5 Hence total 5 coins are required (2,2,2,2,2) ''' # Stores the maximum # number of elements # required to obtain V table = [0 for i in range(V+1)] # Base Case table[0] = 0 # Initialize all table # values as Infinite for i in range(1, V + 1, 1): table[i] = -1 # Find the max arr required # for all values from 1 to V for i in range(1, V + 1, 1): # Go through all arr # smaller than i for j in range(0, m, 1): # If current coin value # is less than i if (arr[j] <= i): sub_res = table[i - arr[j]] # Update table[i] if (sub_res != -1 and sub_res + 1 > table[i]): table[i] = sub_res + 1 # Return the final count return table[V] # Driver Codeif __name__ == '__main__': # Given array arr = [25, 10, 5] m = len(arr) # Given sum V V = 30 # Function Call print(f'Maximum number of array elements required : {maxCount(arr, m, V)}') # This code is contributed by Aaryaman Sharma", "e": 32740, "s": 30452, "text": null }, { "code": "// C# program for the// above approachusing System;class GFG{ // Function that count the// maximum number of elements// to obtain sum Vstatic int maxCount(int[] arr, int m, int V){ // Stores the maximum number of // elements required to obtain V int[] table = new int[V + 1]; // Base Case table[0] = 0; // Initialize all table // values as Infinite for (int i = 1; i <= V; i++) table[i] = -1; // Find the max arr required // for all values from 1 to V for (int i = 1; i <= V; i++) { // Go through all arr // smaller than i for (int j = 0; j < m; j++) { // If current coin value // is less than i if (arr[j] <= i) { int sub_res = table[i - arr[j]]; // Update table[i] if (sub_res != -1 && sub_res + 1 > table[i]) table[i] = sub_res + 1; } } } // Return the final count return table[V];} // Driver codestatic void Main(){ // Given array int[] arr = {25, 10, 5}; int m = arr.Length; // Given sum V int V = 30; // Function Call Console.WriteLine(maxCount(arr, m, V));}} // This code is contributed by divyeshrabadiya07", "e": 33923, "s": 32740, "text": null }, { "code": "<script> // Javascript program for the above approach // Function that count the maximum // number of elements to obtain sum V function maxCount(arr, m, V) { // Stores the maximum number of // elements required to obtain V let table = []; // Base Case table[0] = 0; // Initialize all table values // as Infinite for (let i = 1; i <= V; i++) table[i] = -1; // Find the max arr required // for all values from 1 to V for (let i = 1; i <= V; i++) { // Go through all arr // smaller than i for (let j = 0; j < m; j++) { // If current coin value // is less than i if (arr[j] <= i) { let sub_res = table[i - arr[j]]; // Update table[i] if (sub_res != -1 && sub_res + 1 > table[i]) table[i] = sub_res + 1; } } } // Return the final count return table[V]; } // Driver Code // Given array let arr = [ 25, 10, 5 ]; let m = arr.length; // Given sum V let V = 30; // Function Call document.write(maxCount(arr, m, V)); </script>", "e": 35242, "s": 33923, "text": null }, { "code": null, "e": 35244, "s": 35242, "text": "6" }, { "code": null, "e": 35291, "s": 35244, "text": "Time Complexity: O(N * V)Auxiliary Space: O(N)" }, { "code": null, "e": 35306, "s": 35291, "text": "mohit kumar 29" }, { "code": null, "e": 35324, "s": 35306, "text": "divyeshrabadiya07" }, { "code": null, "e": 35336, "s": 35324, "text": "29AjayKumar" }, { "code": null, "e": 35351, "s": 35336, "text": "aaryamansharma" }, { "code": null, "e": 35366, "s": 35351, "text": "chinmoy1997pal" }, { "code": null, "e": 35378, "s": 35366, "text": "anikakapoor" }, { "code": null, "e": 35393, "s": 35378, "text": "sagartomar9927" }, { "code": null, "e": 35411, "s": 35393, "text": "germanshephered48" }, { "code": null, "e": 35426, "s": 35411, "text": "dp-coin-change" }, { "code": null, "e": 35433, "s": 35426, "text": "Arrays" }, { "code": null, "e": 35453, "s": 35433, "text": "Dynamic Programming" }, { "code": null, "e": 35463, "s": 35453, "text": "Recursion" }, { "code": null, "e": 35470, "s": 35463, "text": "Arrays" }, { "code": null, "e": 35490, "s": 35470, "text": "Dynamic Programming" }, { "code": null, "e": 35500, "s": 35490, "text": "Recursion" }, { "code": null, "e": 35598, "s": 35500, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35629, "s": 35598, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 35656, "s": 35629, "text": "Count pairs with given sum" }, { "code": null, "e": 35681, "s": 35656, "text": "Window Sliding Technique" }, { "code": null, "e": 35719, "s": 35681, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 35740, "s": 35719, "text": "Next Greater Element" }, { "code": null, "e": 35769, "s": 35740, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 35799, "s": 35769, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35833, "s": 35799, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 35864, "s": 35833, "text": "Bellman–Ford Algorithm | DP-23" } ]
Python - XML to JSON - GeeksforGeeks
14 Aug, 2021 A JSON file is a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which is a standard data interchange format. It is primarily used for transmitting data between a web application and a server.A JSON object contains data in the form of a key/value pair. The keys are strings and the values are the JSON types. Keys and values are separated by a colon. Each entry (key/value pair) is separated by a comma. JSON files are lightweight, text-based, human-readable, and can be edited using a text editor.Note: For more information, refer to Working With JSON Data in PythonXML is a markup language which is designed to store data. It is case sensitive. XML offers you to define markup elements and generate customized markup language. The basic unit in the XML is known as an element. The XML language has no predefined tags. It simplifies data sharing, data transport, platform changes, data availability Extension of an XML file is .xmlNote: For more information, refer to XML | BasicsBoth JSON and XML file format are used for transferring data between client and server. However, they both serve the same purpose though differ in their on way. To handle the JSON file format, Python provides a module named json.STEP 1: install xmltodict module using pip or any other python package manager pip install xmltodict STEP 2: import json module using the keyword import import json STEP 3: Read the xml file here, “data_dict” is the variable in which we have loaded our XML data after converting it to dictionary datatype. with open("xml_file.xml") as xml_file: data_dict = xmltodict.parse(xml_file.read()) STEP 4: Close the XML file xml_file.close() STEP 5: Convert the xml_data into a dictionary and store it in a variable JSON object are surrounded by curly braces { }. They are written in key and value pairs. json.loads() takes in a string and returns a json object. json.dumps() takes in a json object and returns a string. We use xml_data as input string and generate python object, so we use json.dumps() json_data = json.dumps(data_dict) Here, json_data is the variable used to store the generated object.STEP 6: Write the json_data to output file with open("data.json", "w") as json_file: json_file.write(json_data) STEP 7: Close the output file json_file.close() Example:XML File: Python3 # Program to convert an xml# file to json file # import json module and xmltodict# module provided by pythonimport jsonimport xmltodict # open the input xml file and read# data in form of python dictionary# using xmltodict modulewith open("test.xml") as xml_file: data_dict = xmltodict.parse(xml_file.read()) xml_file.close() # generate the object using json.dumps() # corresponding to json data json_data = json.dumps(data_dict) # Write the json data to output # json file with open("data.json", "w") as json_file: json_file.write(json_data) json_file.close() Output: gulshankumarar231 Python-json Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary 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 Convert integer to string in Python
[ { "code": null, "e": 25746, "s": 25718, "text": "\n14 Aug, 2021" }, { "code": null, "e": 26938, "s": 25746, "text": "A JSON file is a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which is a standard data interchange format. It is primarily used for transmitting data between a web application and a server.A JSON object contains data in the form of a key/value pair. The keys are strings and the values are the JSON types. Keys and values are separated by a colon. Each entry (key/value pair) is separated by a comma. JSON files are lightweight, text-based, human-readable, and can be edited using a text editor.Note: For more information, refer to Working With JSON Data in PythonXML is a markup language which is designed to store data. It is case sensitive. XML offers you to define markup elements and generate customized markup language. The basic unit in the XML is known as an element. The XML language has no predefined tags. It simplifies data sharing, data transport, platform changes, data availability Extension of an XML file is .xmlNote: For more information, refer to XML | BasicsBoth JSON and XML file format are used for transferring data between client and server. However, they both serve the same purpose though differ in their on way. " }, { "code": null, "e": 27091, "s": 26942, "text": "To handle the JSON file format, Python provides a module named json.STEP 1: install xmltodict module using pip or any other python package manager " }, { "code": null, "e": 27113, "s": 27091, "text": "pip install xmltodict" }, { "code": null, "e": 27167, "s": 27113, "text": "STEP 2: import json module using the keyword import " }, { "code": null, "e": 27179, "s": 27167, "text": "import json" }, { "code": null, "e": 27322, "s": 27179, "text": "STEP 3: Read the xml file here, “data_dict” is the variable in which we have loaded our XML data after converting it to dictionary datatype. " }, { "code": null, "e": 27410, "s": 27322, "text": "with open(\"xml_file.xml\") as xml_file:\n data_dict = xmltodict.parse(xml_file.read())" }, { "code": null, "e": 27439, "s": 27410, "text": "STEP 4: Close the XML file " }, { "code": null, "e": 27456, "s": 27439, "text": "xml_file.close()" }, { "code": null, "e": 27820, "s": 27456, "text": "STEP 5: Convert the xml_data into a dictionary and store it in a variable JSON object are surrounded by curly braces { }. They are written in key and value pairs. json.loads() takes in a string and returns a json object. json.dumps() takes in a json object and returns a string. We use xml_data as input string and generate python object, so we use json.dumps() " }, { "code": null, "e": 27854, "s": 27820, "text": "json_data = json.dumps(data_dict)" }, { "code": null, "e": 27966, "s": 27854, "text": "Here, json_data is the variable used to store the generated object.STEP 6: Write the json_data to output file " }, { "code": null, "e": 28043, "s": 27966, "text": "with open(\"data.json\", \"w\") as json_file:\n json_file.write(json_data)" }, { "code": null, "e": 28075, "s": 28043, "text": "STEP 7: Close the output file " }, { "code": null, "e": 28093, "s": 28075, "text": "json_file.close()" }, { "code": null, "e": 28112, "s": 28093, "text": "Example:XML File: " }, { "code": null, "e": 28122, "s": 28114, "text": "Python3" }, { "code": "# Program to convert an xml# file to json file # import json module and xmltodict# module provided by pythonimport jsonimport xmltodict # open the input xml file and read# data in form of python dictionary# using xmltodict modulewith open(\"test.xml\") as xml_file: data_dict = xmltodict.parse(xml_file.read()) xml_file.close() # generate the object using json.dumps() # corresponding to json data json_data = json.dumps(data_dict) # Write the json data to output # json file with open(\"data.json\", \"w\") as json_file: json_file.write(json_data) json_file.close()", "e": 28742, "s": 28122, "text": null }, { "code": null, "e": 28751, "s": 28742, "text": "Output: " }, { "code": null, "e": 28771, "s": 28753, "text": "gulshankumarar231" }, { "code": null, "e": 28783, "s": 28771, "text": "Python-json" }, { "code": null, "e": 28790, "s": 28783, "text": "Python" }, { "code": null, "e": 28888, "s": 28790, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28906, "s": 28888, "text": "Python Dictionary" }, { "code": null, "e": 28938, "s": 28906, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28960, "s": 28938, "text": "Enumerate() in Python" }, { "code": null, "e": 29002, "s": 28960, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29032, "s": 29002, "text": "Iterate over a list in Python" }, { "code": null, "e": 29058, "s": 29032, "text": "Python String | replace()" }, { "code": null, "e": 29087, "s": 29058, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29131, "s": 29087, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29168, "s": 29131, "text": "Create a Pandas DataFrame from Lists" } ]
Full Adder using Verilog HDL - GeeksforGeeks
13 Sep, 2021 In this article, we will discuss the overview part of Full Adder using Verilog HDL. And the objective to understand the concept and will implement using Verilog HDL code for Full Adder. Let’s discuss it one by one. Prerequisite – Full Adder in Digital Logic Problem Statement : Write a Verilog HDL to design a Full Adder. Let’s discuss it step by step as follows. Step-1 :Concept – Full Adder is a digital combinational Circuit which is having three input a, b and cin and two output sum and cout. Below Truth Table is drawn to show the functionality of the Full Adder. Figure shows the block diagram of design requirements : Full Adder Step-2 :Truth Table – Step-3 :Verilog HDL code for Full Adder (Design Part) – // Code your design : Full Adder module full_add(a,b,cin,sum,cout); input a,b,cin; output sum,cout; wire x,y,z; // instantiate building blocks of full adder half_add h1(.a(a),.b(b),.s(x),.c(y)); half_add h2(.a(x),.b(cin),.s(sum),.c(z)); or o1(cout,y,z); endmodule : full_add // code your half adder design module half_add(a,b,s,c); input a,b; output s,c; // gate level design of half adder xor x1(s,a,b); and a1(c,a,b); endmodule :half_add Step-4 :Test bench – // Code your testbench here module full_add_tb; reg a,b,cin; wire sum,cout; // instantiate the DUT block full_add f1(.a(a),.b(b),.cin(cin),.sum(sum),.cout(cout)); // this particular line is added to dump the file on online simulator initial begin $dumpfile("full_tb.vcd");$dumpvars(); end // insert all the inputs initial begin a=1'b1; #4; a=1'b0;#10 $stop();end initial begin b=1'b1; forever #2 b=~b;end initial begin cin=1'b1;forever #1 cin=~cin; #10 $stop();end // monitor all the input and output ports at times // when any of the input changes its state initial begin $monitor(" time=%0d A=%b B=%b Cin=%b Sum=%b Cout=%b",$time,a,b,cin,sum,cout);end endmodule : full_add_tb Step-5 :Expected Output – time=0 A=1 B=1 Cin=1 Sum=1 Cout=1 time=1 A=1 B=1 Cin=0 Sum=0 Cout=1 time=2 A=1 B=0 Cin=1 Sum=0 Cout=1 time=3 A=1 B=0 Cin=0 Sum=1 Cout=0 time=4 A=0 B=1 Cin=1 Sum=0 Cout=1 time=5 A=0 B=1 Cin=0 Sum=1 Cout=0 time=6 A=0 B=0 Cin=1 Sum=1 Cout=0 time=7 A=0 B=0 Cin=0 Sum=0 Cout=0 time=8 A=0 B=1 Cin=1 Sum=0 Cout=1 time=9 A=0 B=1 Cin=0 Sum=1 Cout=0 time=10 A=0 B=0 Cin=1 Sum=1 Cout=0 time=11 A=0 B=0 Cin=0 Sum=0 Cout=0 time=12 A=0 B=1 Cin=1 Sum=0 Cout=1 time=13 A=0 B=1 Cin=0 Sum=1 Cout=0 Digital Electronics & Logic Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to memory and memory units Analog to Digital Conversion Latches in Digital Logic Introduction of Sequential Circuits Restoring Division Algorithm For Unsigned Integer Ring Counter in Digital Logic Transmission Impairment in Data Communication Synchronous 3 bit Up/Down counter Differences between Synchronous and Asynchronous Counter Counter Design using verilog HDL
[ { "code": null, "e": 25706, "s": 25678, "text": "\n13 Sep, 2021" }, { "code": null, "e": 25921, "s": 25706, "text": "In this article, we will discuss the overview part of Full Adder using Verilog HDL. And the objective to understand the concept and will implement using Verilog HDL code for Full Adder. Let’s discuss it one by one." }, { "code": null, "e": 25964, "s": 25921, "text": "Prerequisite – Full Adder in Digital Logic" }, { "code": null, "e": 26070, "s": 25964, "text": "Problem Statement : Write a Verilog HDL to design a Full Adder. Let’s discuss it step by step as follows." }, { "code": null, "e": 26277, "s": 26070, "text": "Step-1 :Concept – Full Adder is a digital combinational Circuit which is having three input a, b and cin and two output sum and cout. Below Truth Table is drawn to show the functionality of the Full Adder." }, { "code": null, "e": 26344, "s": 26277, "text": "Figure shows the block diagram of design requirements : Full Adder" }, { "code": null, "e": 26366, "s": 26344, "text": "Step-2 :Truth Table –" }, { "code": null, "e": 26422, "s": 26366, "text": "Step-3 :Verilog HDL code for Full Adder (Design Part) –" }, { "code": null, "e": 26904, "s": 26422, "text": "// Code your design : Full Adder\nmodule full_add(a,b,cin,sum,cout);\n input a,b,cin;\n output sum,cout;\n wire x,y,z;\n \n// instantiate building blocks of full adder \n half_add h1(.a(a),.b(b),.s(x),.c(y));\n half_add h2(.a(x),.b(cin),.s(sum),.c(z));\n or o1(cout,y,z);\nendmodule : full_add\n\n// code your half adder design \nmodule half_add(a,b,s,c); \n input a,b;\n output s,c;\n \n// gate level design of half adder \n xor x1(s,a,b);\n and a1(c,a,b);\nendmodule :half_add" }, { "code": null, "e": 26925, "s": 26904, "text": "Step-4 :Test bench –" }, { "code": null, "e": 27658, "s": 26925, "text": "// Code your testbench here\nmodule full_add_tb;\n reg a,b,cin;\n wire sum,cout;\n \n// instantiate the DUT block \n full_add f1(.a(a),.b(b),.cin(cin),.sum(sum),.cout(cout));\n \n// this particular line is added to dump the file on online simulator\n initial begin $dumpfile(\"full_tb.vcd\");$dumpvars(); end\n\n// insert all the inputs \n initial begin a=1'b1; #4; a=1'b0;#10 $stop();end\n initial begin b=1'b1; forever #2 b=~b;end\n initial begin cin=1'b1;forever #1 cin=~cin; #10 $stop();end\n\n// monitor all the input and output ports at times \n// when any of the input changes its state\n\n initial begin $monitor(\" time=%0d A=%b B=%b \n Cin=%b Sum=%b Cout=%b\",$time,a,b,cin,sum,cout);end\n endmodule : full_add_tb" }, { "code": null, "e": 27684, "s": 27658, "text": "Step-5 :Expected Output –" }, { "code": null, "e": 28164, "s": 27684, "text": "time=0 A=1 B=1 Cin=1 Sum=1 Cout=1\ntime=1 A=1 B=1 Cin=0 Sum=0 Cout=1\ntime=2 A=1 B=0 Cin=1 Sum=0 Cout=1\ntime=3 A=1 B=0 Cin=0 Sum=1 Cout=0\ntime=4 A=0 B=1 Cin=1 Sum=0 Cout=1\ntime=5 A=0 B=1 Cin=0 Sum=1 Cout=0\ntime=6 A=0 B=0 Cin=1 Sum=1 Cout=0\ntime=7 A=0 B=0 Cin=0 Sum=0 Cout=0\ntime=8 A=0 B=1 Cin=1 Sum=0 Cout=1\ntime=9 A=0 B=1 Cin=0 Sum=1 Cout=0\ntime=10 A=0 B=0 Cin=1 Sum=1 Cout=0\ntime=11 A=0 B=0 Cin=0 Sum=0 Cout=0\ntime=12 A=0 B=1 Cin=1 Sum=0 Cout=1\ntime=13 A=0 B=1 Cin=0 Sum=1 Cout=0" }, { "code": null, "e": 28199, "s": 28164, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 28297, "s": 28199, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28337, "s": 28297, "text": "Introduction to memory and memory units" }, { "code": null, "e": 28366, "s": 28337, "text": "Analog to Digital Conversion" }, { "code": null, "e": 28391, "s": 28366, "text": "Latches in Digital Logic" }, { "code": null, "e": 28427, "s": 28391, "text": "Introduction of Sequential Circuits" }, { "code": null, "e": 28477, "s": 28427, "text": "Restoring Division Algorithm For Unsigned Integer" }, { "code": null, "e": 28507, "s": 28477, "text": "Ring Counter in Digital Logic" }, { "code": null, "e": 28553, "s": 28507, "text": "Transmission Impairment in Data Communication" }, { "code": null, "e": 28587, "s": 28553, "text": "Synchronous 3 bit Up/Down counter" }, { "code": null, "e": 28644, "s": 28587, "text": "Differences between Synchronous and Asynchronous Counter" } ]
jQuery | event.relatedTarget Property with Example - GeeksforGeeks
12 Feb, 2019 The event.relatedTarget is an inbuilt property in jQuery that is used to find which element is being entered or gets exit on mouse movement.Syntax: event.relatedTarget Parameter: It does not accept any parameter because it is a property not a function.Return Value: It returns which element being entered or exited on mouse movement. jQuery code to show the working of event.relatedTarget property: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> <!-- jQuery code to show working of this property --> $(document).ready(function() { $("div, p").mouseenter(function(event) { $("#d2").html("Pointer at : " + event.relatedTarget.nodeName); }); }); </script> <style> #d1 { height: 100px; width: 50%; padding: 10px; border: 2px solid green; } #d2 { height: 20px; width: 50%; padding: 10px; margin-top: 10px; border: 2px solid green; } </style></head> <body> <!-- this is outer div element --> <div id="d1"> <!-- this is inner div element --> <div>This is a div element </div> <!-- this is paragraph element --> <p style="background-color:lightgreen">This is a paragraph</p> </div> <div id="d2" /></body> </html> Output:Before mouse pointer is moved over the div element- After mouse pointer is moved over the div element- jQuery-Events JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 26002, "s": 25974, "text": "\n12 Feb, 2019" }, { "code": null, "e": 26150, "s": 26002, "text": "The event.relatedTarget is an inbuilt property in jQuery that is used to find which element is being entered or gets exit on mouse movement.Syntax:" }, { "code": null, "e": 26171, "s": 26150, "text": "event.relatedTarget\n" }, { "code": null, "e": 26337, "s": 26171, "text": "Parameter: It does not accept any parameter because it is a property not a function.Return Value: It returns which element being entered or exited on mouse movement." }, { "code": null, "e": 26402, "s": 26337, "text": "jQuery code to show the working of event.relatedTarget property:" }, { "code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> <!-- jQuery code to show working of this property --> $(document).ready(function() { $(\"div, p\").mouseenter(function(event) { $(\"#d2\").html(\"Pointer at : \" + event.relatedTarget.nodeName); }); }); </script> <style> #d1 { height: 100px; width: 50%; padding: 10px; border: 2px solid green; } #d2 { height: 20px; width: 50%; padding: 10px; margin-top: 10px; border: 2px solid green; } </style></head> <body> <!-- this is outer div element --> <div id=\"d1\"> <!-- this is inner div element --> <div>This is a div element </div> <!-- this is paragraph element --> <p style=\"background-color:lightgreen\">This is a paragraph</p> </div> <div id=\"d2\" /></body> </html>", "e": 27434, "s": 26402, "text": null }, { "code": null, "e": 27493, "s": 27434, "text": "Output:Before mouse pointer is moved over the div element-" }, { "code": null, "e": 27544, "s": 27493, "text": "After mouse pointer is moved over the div element-" }, { "code": null, "e": 27558, "s": 27544, "text": "jQuery-Events" }, { "code": null, "e": 27569, "s": 27558, "text": "JavaScript" }, { "code": null, "e": 27576, "s": 27569, "text": "JQuery" }, { "code": null, "e": 27674, "s": 27576, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27714, "s": 27674, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27759, "s": 27714, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27820, "s": 27759, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27892, "s": 27820, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27944, "s": 27892, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 27990, "s": 27944, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 28019, "s": 27990, "text": "Form validation using jQuery" }, { "code": null, "e": 28082, "s": 28019, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 28159, "s": 28082, "text": "How to change the background color after clicking the button in JavaScript ?" } ]