<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>Gaurav Vichare</title>
	<atom:link href="http://gauravvichare.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://gauravvichare.com</link>
	<description></description>
	<lastBuildDate>Wed, 14 Jun 2017 09:57:49 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.6.8</generator>
<site xmlns="com-wordpress:feed-additions:1">45922509</site>	<item>
		<title>How to assign python variable to Javascript variable in web2py</title>
		<link>http://gauravvichare.com/how-to-assign-python-variable-to-javascript-variable-in-web2py/</link>
					<comments>http://gauravvichare.com/how-to-assign-python-variable-to-javascript-variable-in-web2py/#respond</comments>
		
		<dc:creator><![CDATA[Gaurav Vichare]]></dc:creator>
		<pubDate>Thu, 15 Dec 2016 04:20:42 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[web2py]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">http://gauravvichare.com/?p=321</guid>

					<description><![CDATA[<p>You might be using following statement to assign python variable to javascript variable on older versions of web2py (&#60;2.9.11), may be because of this question on stackoverflow: http://stackoverflow.com/questions/31216574/how-to-pass-data-from-python-to-javascript-in-web2py [crayon-634c80e948ae8056481404/] Above statement was working on web2py 2.9.11 and before because of behavioral bug in web2py, which got fixed in web2py 2.9.11. Now [crayon-634c80e948af3550855563-i/]  sets [crayon-634c80e948af6734039098-i/] . So because of above line, [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/how-to-assign-python-variable-to-javascript-variable-in-web2py/">How to assign python variable to Javascript variable in web2py</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>You might be using following statement to assign python variable to javascript variable on older versions of web2py (&lt;2.9.11), may be because of this question on stackoverflow: <a href="http://stackoverflow.com/questions/31216574/how-to-pass-data-from-python-to-javascript-in-web2py">http://stackoverflow.com/questions/31216574/how-to-pass-data-from-python-to-javascript-in-web2py</a></p><pre class="crayon-plain-tag">var javascript_array =  {{=XML(response.json(array))}}</pre><p>Above statement was working on web2py 2.9.11 and before because of <span style="font-family: arial, helvetica, sans-serif;">behavioral bug in web2py, which got fixed in web2py 2.9.11. N</span>ow 
			<span id="crayon-634c80e948af3550855563" class="crayon-syntax crayon-syntax-inline  crayon-theme-github crayon-theme-github-inline crayon-font-monospace" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important;"><span class="crayon-pre crayon-code" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-i">response</span><span class="crayon-sy">.</span><span class="crayon-e">json</span><span class="crayon-sy">(</span><span class="crayon-sy">)</span></span></span>  sets 
			<span id="crayon-634c80e948af6734039098" class="crayon-syntax crayon-syntax-inline  crayon-theme-github crayon-theme-github-inline crayon-font-monospace" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important;"><span class="crayon-pre crayon-code" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-i">content</span>-<span class="crayon-i">type</span><span class="crayon-h"> </span>=<span class="crayon-h"> </span><span class="crayon-i">application</span>/<span class="crayon-i">json</span></span></span> . So because of above line, on web2py &gt;2.9.11 html code is displayed in browser instead of rendering it as html.</p>
<p><strong>Correct way:</strong></p>
<p>First convert python variable to json in controller and then pass it to view. And in view, use XML() to assign it to javascript variable so that it is not escaped</p>
<p>Controller</p><pre class="crayon-plain-tag">from gluon.serializers import json

def index():
    array = [1, 2, 3, 4, 5]
    dictionary = dict(id=1, name='foo')
    return dict(array=json(array), dictionary=json(dictionary))</pre><p>View</p><pre class="crayon-plain-tag">&lt;script&gt;
    var js_array = {{=XML(array)}};
    var js_dictionary = {{=XML(dictionary)}};
&lt;/script&gt;</pre><p>Other solution is use <a href="http://web2py.readthedocs.io/en/latest/html.html#gluon.html.ASSIGNJS">ASSIGNJS</a> html helper</p>
<p>Controller</p><pre class="crayon-plain-tag">def index():
    array = [1, 2, 3, 4, 5]
    dictionary = dict(id=1, name='foo')
    return dict(array=array, dictionary=dictionary)</pre><p>View</p><pre class="crayon-plain-tag">&lt;script&gt;
    {{=ASSIGNJS(js_array = array)}}
    {{=ASSIGNJS(js_dictionary = dictionary)}}
&lt;/script&gt;</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/how-to-assign-python-variable-to-javascript-variable-in-web2py/">How to assign python variable to Javascript variable in web2py</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>http://gauravvichare.com/how-to-assign-python-variable-to-javascript-variable-in-web2py/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">321</post-id>	</item>
		<item>
		<title>How to change admin app url in web2py?</title>
		<link>http://gauravvichare.com/how-to-change-admin-app-url-in-web2py/</link>
					<comments>http://gauravvichare.com/how-to-change-admin-app-url-in-web2py/#comments</comments>
		
		<dc:creator><![CDATA[Gaurav Vichare]]></dc:creator>
		<pubDate>Wed, 07 Dec 2016 05:29:04 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[web2py]]></category>
		<guid isPermaLink="false">http://gauravvichare.com/?p=307</guid>

					<description><![CDATA[<p>test <b>gaurav</b></p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/how-to-change-admin-app-url-in-web2py/">How to change admin app url in web2py?</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>This question was asked here <a href="http://stackoverflow.com/questions/12466932/how-to-rename-admin-to-other-url-in-web2py">How to rename “/admin” to other URL in web2py?</a></p>
<p>For all the web2py applications, web2py admin url is same, i. e. <a href="http://www.example.com/admin">www.example.com/admin</a> or <a href="http://127.0.0.1:8000/admin">127.0.0.1:8000/admin</a>. One should prevent access to admin interface  to public or external users. Admin url should be changed from /admin to /some-other-url which is difficult to guess. admin is just another app like welcome or example app, so changing appliacation name will change url to it.</p>
<p>For example to change 
			<span id="crayon-634c80e94935c074620674" class="crayon-syntax crayon-syntax-inline  crayon-theme-github crayon-theme-github-inline crayon-font-monospace" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important;"><span class="crayon-pre crayon-code" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-i">admin</span></span></span>  to 
			<span id="crayon-634c80e949362054954923" class="crayon-syntax crayon-syntax-inline  crayon-theme-github crayon-theme-github-inline crayon-font-monospace" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important;"><span class="crayon-pre crayon-code" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-i">w2p</span>-<span class="crayon-i">adm2in</span></span></span>  do following steps</p>
<p><strong>1. Rename admin folder with w2p-adm2in</strong><br />
On linux</p><pre class="crayon-plain-tag">cd web2py/applications
mv admin w2p-adm2in</pre><p>On Windows</p><pre class="crayon-plain-tag">cd web2py/applications
rename admin w2p-adm2in</pre><p>If you are in local environment, you can also do it using your file explorer</p>
<p><strong>2. Fix broken links</strong><br />
Due to changes done in Step 1, links to admin app are broken. Links to admin app needs to be replaced with links to w2p-adm2in.</p>
<p>In app_name/controllers/appadmin.py<br />
Update response.menu, change it to following</p><pre class="crayon-plain-tag">response.menu = [[T('design'), False, URL('w2p-adm2in', 'default', 'design',
                  args=[request.application])], [T('db'), False,
                  URL('index')], [T('state'), False,
                  URL('state')], [T('cache'), False,
                  URL('ccache')]]</pre><p><strong> 3. Instead of admin app, check user is logged in to w2p-adm2in app</strong><br />
while accessing appadmin, by default controller app_name/controllers/appadmin.py checks whether user is logged in to admin app or not, if not then it redirects to admin app(admin app login page), now it should check whether user is logged in to w2p-adm2in app and if not it should redirect to w2p-adm2in. To acheive this, pass 
			<span id="crayon-634c80e949368646539377" class="crayon-syntax crayon-syntax-inline  crayon-theme-github crayon-theme-github-inline crayon-font-monospace" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important;"><span class="crayon-pre crayon-code" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-i">other_application</span>=<span class="crayon-s">'w2p-adm2in'</span></span></span>  as parameter to method 
			<span id="crayon-634c80e94936a500491342" class="crayon-syntax crayon-syntax-inline  crayon-theme-github crayon-theme-github-inline crayon-font-monospace" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important;"><span class="crayon-pre crayon-code" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-i">gluon</span><span class="crayon-sy">.</span><span class="crayon-i">fileutils</span><span class="crayon-sy">.</span><span class="crayon-e">check_credentials</span><span class="crayon-sy">(</span><span class="crayon-sy">)</span></span></span></p>
<p>After step 2 and step 3, diff file of app_name/controllers/appadmin.py will look like following</p><pre class="crayon-plain-tag">if not (gluon.fileutils.check_credentials(request) or auth.has_membership(manager_role)):
         raise HTTP(403, "Not authorized")
     menu = False
-elif (request.application == 'admin' and not session.authorized) or \
- (request.application != 'admin' and not gluon.fileutils.check_credentials(request)):
-    redirect(URL('admin', 'default', 'index',
+elif (request.application == 'w2p-adm2in' and not session.authorized) or \
+ (request.application != 'w2p-adm2in' and not gluon.fileutils.check_credentials(request, other_application='w2p-adm2in')):
+    redirect(URL('w2p-adm2in', 'default', 'index',
                  vars=dict(send=URL(args=request.args, vars=request.vars))))

ignore_rw = True
response.view = 'appadmin.html'
if menu:
- response.menu = [[T('design'), False, URL('admin', 'default', 'design',
+ response.menu = [[T('design'), False, URL('w2p-adm2in', 'default', 'design',
                    args=[request.application])], [T('db'), False,
                    URL('index')], [T('state'), False,
                    URL('state')], [T('cache'), False,
                    URL('ccache')]]</pre><p><strong>4. Change links to error page (tickets)</strong><br />
By default links to error is /<span style="color: #ff0000;">admin</span>/default/ticket/[ticket_id], Now it should be /<span style="color: #008000;">w2p-adm2in</span>/default/ticket/[ticket_id]<br />
So add/replace/append following lines to web2py/routes.py</p><pre class="crayon-plain-tag">error_message = '&lt;html&gt;&lt;body&gt;&lt;h1&gt;{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97}s&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;'
error_message_ticket = '&lt;html&gt;&lt;body&gt;&lt;h1&gt;Internal error&lt;/h1&gt;Ticket issued: &lt;a href="/w2p-adm2in/default/ticket/{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97}(ticket)s" target="_blank"&gt;{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97}(ticket)s&lt;/a&gt;&lt;/body&gt;&lt;/html&gt;'</pre><p>If routes.py file does not exist in web2py folder then create it containing above lines.</p>
<p>&nbsp;</p>
<p>If you more changes that needs to be done, please comment below.</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/how-to-change-admin-app-url-in-web2py/">How to change admin app url in web2py?</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>http://gauravvichare.com/how-to-change-admin-app-url-in-web2py/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">307</post-id>	</item>
		<item>
		<title>How to do file validation in web2py and write custom validator to validate files?</title>
		<link>http://gauravvichare.com/how-to-do-file-validation-in-web2py-and-write-custom-validator-to-validate-files/</link>
					<comments>http://gauravvichare.com/how-to-do-file-validation-in-web2py-and-write-custom-validator-to-validate-files/#respond</comments>
		
		<dc:creator><![CDATA[Gaurav Vichare]]></dc:creator>
		<pubDate>Fri, 11 Nov 2016 10:31:36 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[upload]]></category>
		<category><![CDATA[validator]]></category>
		<category><![CDATA[web2py]]></category>
		<guid isPermaLink="false">http://gauravvichare.com/?p=289</guid>

					<description><![CDATA[<p>In this article, I will explain built in validator [crayon-634c80e949a4e507907160-i/]  and [crayon-634c80e949a53713242767-i/], also a custom validator. It is important to validate file uploaded on server to restrict malicious files like .py .php, .exe bat etc. Web2py provides 2 validators to validate files, [crayon-634c80e949a55194528149-i/]  and [crayon-634c80e949a56112171673-i/] . IS_IMAGE It checks whether uploaded file is of type image and [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/how-to-do-file-validation-in-web2py-and-write-custom-validator-to-validate-files/">How to do file validation in web2py and write custom validator to validate files?</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this article, I will explain built in validator 
			<span id="crayon-634c80e949a4e507907160" class="crayon-syntax crayon-syntax-inline  crayon-theme-github crayon-theme-github-inline crayon-font-monospace" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important;"><span class="crayon-pre crayon-code" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-i">IS_IMAGE</span></span></span>  and 
			<span id="crayon-634c80e949a53713242767" class="crayon-syntax crayon-syntax-inline  crayon-theme-github crayon-theme-github-inline crayon-font-monospace" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important;"><span class="crayon-pre crayon-code" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-i">IS_UPLOAD_FILENAME</span></span></span>, also a custom validator.<br />
It is important to validate file uploaded on server to restrict malicious files like .py .php, .exe bat etc.<br />
Web2py provides 2 validators to validate files, 
			<span id="crayon-634c80e949a55194528149" class="crayon-syntax crayon-syntax-inline  crayon-theme-github crayon-theme-github-inline crayon-font-monospace" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important;"><span class="crayon-pre crayon-code" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-i">IS_IMAGE</span></span></span>  and 
			<span id="crayon-634c80e949a56112171673" class="crayon-syntax crayon-syntax-inline  crayon-theme-github crayon-theme-github-inline crayon-font-monospace" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important;"><span class="crayon-pre crayon-code" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-i">IS_UPLOAD_FILENAME</span></span></span> .</p>
<ol>
<li><strong>IS_IMAGE</strong></li>
</ol>
<p style="padding-left: 30px;">It checks whether uploaded file is of type image and file is in any of supported image formats</p>
<p style="padding-left: 30px;">Following statement Checks if uploaded file is either png or bmp</p>
<p></p><pre class="crayon-plain-tag">requires = IS_IMAGE(extensions=('png', 'bmp'))</pre><p></p>
<p style="padding-left: 30px;">2. <strong>IS_UPLOAD_FILENAME</strong></p>
<p style="padding-left: 30px;">It checks whether uploaded file meets the given rules for filename and extension.</p>
<p style="padding-left: 30px;">You can provide regular expressions in filename and extension parameters.<br />
If filename or extension doesn&#8217;t match the expression/criteria then it shows error in form.<br />
You can provide your own error message using argument error_message</p>
<p style="padding-left: 30px;">Example:</p>
<p style="padding-left: 30px;">If you want to allow all files starting with word &#8216;log&#8217; and having extension &#8220;txt&#8221;:</p>
<p></p><pre class="crayon-plain-tag">requires = IS_UPLOAD_FILENAME(filename='^log', extension='txt')</pre><p>Like IS_IMAGE validator we can not pass list of valid extensions to IS_UPLOAD_FILENAME validator.<br />
But we can achieve this using regular expression or by writing our own validator</p>
<ol>
<li><strong>Using regular expression:</strong></li>
</ol>
<p></p><pre class="crayon-plain-tag">requires=IS_UPLOAD_FILENAME(extension='^(pdf|docx|doc|xls)$')</pre><p></p>
<p style="padding-left: 30px;">The above expression will allow all the files having extension pdf, docx, doc or xls.</p>
<p style="padding-left: 30px;"><span style="color: #993366;">^</span> Matches the start of string</p>
<p style="padding-left: 30px;"><span style="color: #993366;">$</span> Matches end of the string</p>
<p style="padding-left: 30px;"><span style="color: #993366;">(pdf|docx|doc|xls)</span> match any value from group pdf, docx, doc and xls</p>
<p style="padding-left: 30px;">Read more about <a href="https://docs.python.org/2/library/re.html">Regular Expression</a></p>
<p style="padding-left: 30px;">2. <strong>Using custom validator:</strong></p>
<p style="padding-left: 30px;">Following validator checks whether uploaded file has extension from the valid extension list provided through argument extensions. It will also show error for empty file.</p>
<p></p><pre class="crayon-plain-tag">import os

class IS_ALLOWED_FILE_TYPE(object):
    """
    Checks if file uploaded through file input has valid extension

    Args:
        extensions: iterable containing allowed *lowercase* file extensions
        error_message:

    Examples:
        Check if uploaded file is pdf or docx:

        INPUT(_type='file', _name='name',
              requires=IS_ALLOWED_FILE_TYPE(extensions=['pdf', 'docx']))

        db.table.field.requires = IS_ALLOWED_FILE_TYPE(extensions=['pdf', 'docx'],
            error_message='File is not pdf or docx'))
    """
    def __init__(self, extensions=[], error_message="File type not supported"):
        self.extensions = extensions
        self.error_message = error_message

    def __call__(self, value):
        error = None
        try:
            filename = value.filename
        except:
            return (value, self.error_message)

        _, file_extension = os.path.splitext(filename)
        if file_extension.replace('.', '').lower() not in self.extensions:
            error = self.error_message
        return (value, error)</pre><p>Usage:</p><pre class="crayon-plain-tag">db.define_table('person',
                Field('name'),
                Field('template', 'upload',
                      requires=IS_ALLOWED_FILE_TYPE(extensions=['pdf' 'docx', 'doc'])))</pre><p>Advantage of custom validator is you can add and modify restriction as per your need</p>
<p>If you are facing any issues regarding above post please comment below</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/how-to-do-file-validation-in-web2py-and-write-custom-validator-to-validate-files/">How to do file validation in web2py and write custom validator to validate files?</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>http://gauravvichare.com/how-to-do-file-validation-in-web2py-and-write-custom-validator-to-validate-files/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">289</post-id>	</item>
		<item>
		<title>How to write custom download controller in web2py?</title>
		<link>http://gauravvichare.com/write-custom-download-controller-web2py/</link>
					<comments>http://gauravvichare.com/write-custom-download-controller-web2py/#respond</comments>
		
		<dc:creator><![CDATA[Gaurav Vichare]]></dc:creator>
		<pubDate>Fri, 22 Apr 2016 12:06:38 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[web2py]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">http://gauravvichare.com/?p=264</guid>

					<description><![CDATA[<p>Suppose we have employee table with resume as uplaod field. And we want to download file on the basis of employee id. Download  url is like [crayon-634c80e949cc9694641978-i/] or [crayon-634c80e949ccd641111356-i/] example: www.example.com/default/custom_download/1 Consider following employee schema: [crayon-634c80e949ccf570462478/] Then custom download controller will be: [crayon-634c80e949cd0305612189/] If you have any queries related to this code, please comment below.</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/write-custom-download-controller-web2py/">How to write custom download controller in web2py?</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Suppose we have employee table with resume as uplaod field. And we want to download file on the basis of employee id.<br />
Download  url is like 
			<span id="crayon-634c80e949cc9694641978" class="crayon-syntax crayon-syntax-inline  crayon-theme-github crayon-theme-github-inline crayon-font-monospace" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important;"><span class="crayon-pre crayon-code" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-i">app_name</span>/<span class="crayon-i">custom_download</span>/<span class="crayon-i">employee_id</span></span></span><br />
or 
			<span id="crayon-634c80e949ccd641111356" class="crayon-syntax crayon-syntax-inline  crayon-theme-github crayon-theme-github-inline crayon-font-monospace" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important;"><span class="crayon-pre crayon-code" style="font-size: 12px !important; line-height: 15px !important;font-size: 12px !important; -moz-tab-size:4; -o-tab-size:4; -webkit-tab-size:4; tab-size:4;"><span class="crayon-h">&lt;</span><span class="crayon-i">a</span><span class="crayon-h"> </span><span class="crayon-i">href</span>=<span class="crayon-s">"{{=URL('default', 'custom_download', args = employee_id)}}"</span><span class="crayon-h"> </span><span class="crayon-i">download</span><span class="crayon-h">&gt;</span></span></span></p>
<p>example: www.example.com/default/custom_download/1</p>
<p>Consider following employee schema:</p><pre class="crayon-plain-tag">db.define_table('employee',
                Field('name', 'string', required=True),
                Field('email', string, required=True),
                Field('address', 'text', required=True),
                Field('resume', 'upload', required=True))</pre><p>Then custom download controller will be:</p><pre class="crayon-plain-tag">def custom_download(): 
    employee_id = request.args(0) 
    emp_record = db(db.employee.id == employee_id).select().first()
    download_file = emp_record.resume

    # Name of file is table_name.field.XXXXX.ext, so retrieve original file name
    org_file_name, file_stream = db.employee.resume.retrieve(download_file)

    file_header = "attachment; filename=" + org_file_name
    response.headers['ContentType'] = "application/octet-stream"
    response.headers['Content-Disposition'] = file_header
    return response.stream(file_stream)</pre><p>If you have any queries related to this code, please comment below.</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/write-custom-download-controller-web2py/">How to write custom download controller in web2py?</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>http://gauravvichare.com/write-custom-download-controller-web2py/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">264</post-id>	</item>
		<item>
		<title>How to password protect PDF file using Python?</title>
		<link>http://gauravvichare.com/how-to-password-protect-pdf-file-using-python/</link>
					<comments>http://gauravvichare.com/how-to-password-protect-pdf-file-using-python/#comments</comments>
		
		<dc:creator><![CDATA[Gaurav Vichare]]></dc:creator>
		<pubDate>Mon, 31 Aug 2015 04:33:51 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[File Handling]]></category>
		<category><![CDATA[PyPDF2]]></category>
		<guid isPermaLink="false">http://gauravvichare.com/?p=245</guid>

					<description><![CDATA[<p>We will use python library PyPDF2 to set password to pdf file. To install PyPDF2: [crayon-634c80e949eca397104430/] We are using encrypt function of PyPDF2. encrypt(user_password, owner_password=None, use_128bit=True) user_password  – The “user password” allows opening and reading the PDF file with the restrictions . owner_password – The “owner password”  have no restrictions. By default, the owner password is [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/how-to-password-protect-pdf-file-using-python/">How to password protect PDF file using Python?</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>We will use python library <a href="https://github.com/mstamy2/PyPDF2" target="_blank">PyPDF2</a> to set password to pdf file.</p>
<p>To install PyPDF2:</p><pre class="crayon-plain-tag">sudo pip install pypdf2</pre><p>We are using encrypt function of PyPDF2.</p>
<p><code class="descname">encrypt</code><span class="sig-paren">(</span><em>user_password</em>, <em>owner_password=None</em>, <em>use_128bit=True</em><span class="sig-paren">)</span></p>
<ul>
<li><em>user_password</em>  – The “user password” allows opening and reading the PDF file with the restrictions .</li>
<li><em>owner_password</em> – The “owner password”  have no restrictions. By default, the owner password is the same as the user password.</li>
<li><em>use_128bit</em>  – Decides which encryption to use128bit or 40bit.</li>
</ul>
<p></p><pre class="crayon-plain-tag">import PyPDF2
import os
import argparse


def set_password(input_file, user_pass, owner_pass):
    """
    Function creates new temporary pdf file with same content,
    assigns given password to pdf and rename it with original file.
    """
    # temporary output file with name same as input file but prepended
    # by "temp_", inside same direcory as input file.
    path, filename = os.path.split(input_file)
    output_file = os.path.join(path, "temp_" + filename)

    output = PyPDF2.PdfFileWriter()

    input_stream = PyPDF2.PdfFileReader(open(input_file, "rb"))

    for i in range(0, input_stream.getNumPages()):
        output.addPage(input_stream.getPage(i))

    outputStream = open(output_file, "wb")

    # Set user and owner password to pdf file
    output.encrypt(user_pass, owner_pass, use_128bit=True)
    output.write(outputStream)
    outputStream.close()

    # Rename temporary output file with original filename, this
    # will automatically delete temporary file
    os.rename(output_file, input_file)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--input_pdf', required=True,
                        help='Input pdf file')
    parser.add_argument('-p', '--user_password', required=True,
                        help='output CSV file')
    parser.add_argument('-o', '--owner_password', default=None,
                        help='Owner Password')
    args = parser.parse_args()
    set_password(args.input_pdf, args.user_password, args.owner_password)

if __name__ == "__main__":
    main()</pre><p>If you have any queries, please comment!</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/how-to-password-protect-pdf-file-using-python/">How to password protect PDF file using Python?</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>http://gauravvichare.com/how-to-password-protect-pdf-file-using-python/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">245</post-id>	</item>
		<item>
		<title>Memory profiling in Python using memory_profiler</title>
		<link>http://gauravvichare.com/memory-profiling-in-python-using-memory_profiler/</link>
					<comments>http://gauravvichare.com/memory-profiling-in-python-using-memory_profiler/#respond</comments>
		
		<dc:creator><![CDATA[Gaurav Vichare]]></dc:creator>
		<pubDate>Tue, 04 Aug 2015 06:20:49 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">http://gauravvichare.com/?p=234</guid>

					<description><![CDATA[<p>To install memory_profiler: [crayon-634c80e94a458791526164/] Profile function/script: Add following line in script to import memory profiler: [crayon-634c80e94a45d440933162/] Decorate the function you would like to profile with @profile Example: [crayon-634c80e94a45e079857583/] Run python script to get memory usage line by line. [crayon-634c80e94a460910506827/] Another method to profile function is , decorate function with @profile and then run script using [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/memory-profiling-in-python-using-memory_profiler/">Memory profiling in Python using memory_profiler</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>To install memory_profiler:</p><pre class="crayon-plain-tag">sudo easy_install -U memory_profiler</pre><p></p>
<ol>
<ol>
<li><strong>Profile function/script:</strong><br />
Add following line in script to import memory profiler:<br />
<pre class="crayon-plain-tag">from memory_profiler import profile</pre><br />
Decorate the function you would like to profile with <strong>@profile</strong><br />
Example:<br />
<pre class="crayon-plain-tag">#test.py
from memory_profiler import profile

@profile
def test_func():
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    addition = 0

    for num in numbers:
        addition += num

    return addition

if __name__ == '__main__':
    test_func()</pre><br />
Run python script to get memory usage line by line.<br />
<pre class="crayon-plain-tag">python test.py</pre><br />
Another method to profile function is , decorate function with @profile and then run script using following command:<br />
<pre class="crayon-plain-tag">python -m memory_profiler test.py</pre><br />
<strong>2. Profile web2py application/(External scripts):</strong><br />
Start webpy server using following command :<br />
<pre class="crayon-plain-tag">mprof run python web2py.py -p 8000 -a g0987</pre><br />
Now open application from browser and open page you want to profile. Then stop web2py server. To view result run command &#8216;mprof plot&#8217;. But to plot result you need package &#8216;matplotlib&#8217;.<br />
To install matplotlib, first install required packages for matplotlib:<br />
<pre class="crayon-plain-tag">sudo apt-get build-dep python-matplotlib</pre><br />
Now install matplotlib:<br />
<pre class="crayon-plain-tag">sudo pip install matplotlib</pre><br />
Now run following command to get memory profile graph (Memory Usage vs Time):<br />
<pre class="crayon-plain-tag">mprof plot</pre><br />
The available commands for <cite>mprof </cite>:</p>
<ul>
<li><tt>mprof run</tt>: running an executable, recording memory usage</li>
<li><tt>mprof plot</tt>: plotting one the recorded memory usage (by default, the last one)</li>
<li><tt>mprof list</tt>: listing all recorded memory usage files.</li>
<li><tt>mprof clean</tt>: delete recorded memory usage files.</li>
<li><tt>mprof rm </tt>: delete particular  memory usage file.</li>
</ul>
</li>
</ol>
</ol>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/memory-profiling-in-python-using-memory_profiler/">Memory profiling in Python using memory_profiler</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>http://gauravvichare.com/memory-profiling-in-python-using-memory_profiler/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">234</post-id>	</item>
		<item>
		<title>Time profiling in python using cProfile</title>
		<link>http://gauravvichare.com/time-profiling-in-python-using-cprofile/</link>
					<comments>http://gauravvichare.com/time-profiling-in-python-using-cprofile/#respond</comments>
		
		<dc:creator><![CDATA[Gaurav Vichare]]></dc:creator>
		<pubDate>Tue, 30 Jun 2015 04:04:07 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">http://gauravvichare.com/?p=209</guid>

					<description><![CDATA[<p>In this article we will cover following points:  Profile single function Profile complete python script How to read .prof file Profile web2py application To install cprofile on ubuntu use following command: [crayon-634c80e94a696612137846/] 1) Profile single function To profile function, import cProfile [crayon-634c80e94a69b343606379/] Then call function using cProfile.run() [crayon-634c80e94a69d677887150/] This will write profiling data in test.profile [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/time-profiling-in-python-using-cprofile/">Time profiling in python using cProfile</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this article we will cover following points:</p>
<ol>
<li> Profile single function</li>
<li>Profile complete python script</li>
<li>How to read <em>.prof</em> file</li>
<li>Profile web2py application</li>
</ol>
<p>To install cprofile on ubuntu use following command:</p><pre class="crayon-plain-tag">sudo pip install cprofilev</pre><p><strong>1) Profile single function</strong></p>
<p>To profile function, import cProfile</p><pre class="crayon-plain-tag">import cProfile</pre><p>Then call function using cProfile.run()</p><pre class="crayon-plain-tag">cProfile.run('test()', 'test.profile')</pre><p>This will write profiling data in <em>test.profile</em> .</p>
<p>Example:</p><pre class="crayon-plain-tag">import cProfile

def test_func():
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    addition = 0

    for num in numbers:
        addition += num

    return addition

if __name__ == '__main__':
    cProfile.run('test_func()', 'test.profile')</pre><p>Later in this post we will see how to read <em>.profile</em> file</p>
<p><strong>2) Profile python script</strong></p>
<p>Run python script using following command :</p><pre class="crayon-plain-tag">python -m cProfile -o test.profile test.py</pre><p>This will profile complete script and write profiling data in <em>test.profile</em>.</p>
<p><strong>3) How to read .profile file?</strong></p>
<p>Using pstats module:</p>
<p>.profile file is in binary format. So to examine data from .profile file use the interactive mode of the pstats module by running it as a script with the profile data file as argument.</p><pre class="crayon-plain-tag">python -m pstats test.profile</pre><p>Now you will go in interactive profile statistics browser.</p><pre class="crayon-plain-tag">Welcome to the profile statistics browser.
test.profile{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97}</pre><p>Now use <em>stats</em> command to display stats</p><pre class="crayon-plain-tag">Welcome to the profile statistics browser.
test.profile{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97} stats</pre><p>You can sort stats using following sort keys:<br />
cumulative &#8212; cumulative time<br />
module &#8212; file name<br />
ncalls &#8212; call count<br />
pcalls &#8212; primitive call count<br />
file &#8212; file name<br />
line &#8212; line number<br />
name &#8212; function name<br />
calls &#8212; call count<br />
stdname &#8212; standard name<br />
nfl &#8212; name/file/line<br />
filename &#8212; file name<br />
cumtime &#8212; cumulative time<br />
time &#8212; internal time<br />
tottime &#8212; internal time</p>
<p>For example:</p><pre class="crayon-plain-tag">Welcome to the profile statistics browser.
test.profile{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97} stats tottime</pre><p>Above command will sort records using tottime ( internal time)</p>
<p>To show particular number of records use command &#8220;stats count&#8221;</p>
<p>For example:</p><pre class="crayon-plain-tag">Welcome to the profile statistics browser.
test.profile{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97} stats 10</pre><p>This will show only 10 records.</p>
<p>Other method to read .profile file is using command &#8220;cprofilev -f test_func.profile&#8221;</p><pre class="crayon-plain-tag">cprofilev -f test_func.profile</pre><p>Run above command in terminal and view stats in browser on http://127.0.0.1:4000</p>
<p>Advantage of this method is you can easily sort records ,just by one click on column name.</p>
<p><strong>4. Profile web2py application</strong></p>
<p>Create a empty text file in a directory and then pass this text file as argument to web2py. All profiling data will be stored in this file.<br />
For example :<br />
Create lcm.txt in &#8216;/home/gaurav/temp/lcm/&#8221; directory. Now run web2py server using following command with command line argument -F (profiler filename)</p><pre class="crayon-plain-tag">python web2py.py -p 8000 -a g0987 -F /home/gaurav/temp/lcm/lcm.txt</pre><p></p>
<blockquote><p><em>Note: For some web2py version , we have to provide directory using -f (not -F) option and data will be written in that directory in the form of .profile files. We can read these files using above mentioned methods.</em></p></blockquote>
<p>Now open application from browser and open pages you want to profile.Then stop web2py server. This will write profiling data to lcm.txt. Data in text file will be in readable format , no need of pstats module to read data.</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/time-profiling-in-python-using-cprofile/">Time profiling in python using cProfile</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>http://gauravvichare.com/time-profiling-in-python-using-cprofile/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">209</post-id>	</item>
		<item>
		<title>How to measure performance of code ? &#8211; Basic methods</title>
		<link>http://gauravvichare.com/how-to-measure-performance-of-code-basic-methods/</link>
					<comments>http://gauravvichare.com/how-to-measure-performance-of-code-basic-methods/#respond</comments>
		
		<dc:creator><![CDATA[Gaurav Vichare]]></dc:creator>
		<pubDate>Fri, 19 Jun 2015 04:47:20 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">http://gauravvichare.com/?p=223</guid>

					<description><![CDATA[<p>In this article, we will cover some very basic methods to calculate performance of script. In next article we will cover advance tool like cProfile and memory_profiler. What is profiling? Profiling is program analysis that measures, for example, the space (memory) or time complexity of a program, the usage of particular instructions, or the frequency [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/how-to-measure-performance-of-code-basic-methods/">How to measure performance of code ? &#8211; Basic methods</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this article, we will cover some very basic methods to calculate performance of script. In next article we will cover advance tool like cProfile and memory_profiler.</p>
<p>What is profiling?</p>
<ul>
<li>Profiling is program analysis that measures, for example, the space (memory) or time complexity of a program, the usage of particular instructions, or the frequency and duration of function calls.</li>
<li>Profiling or performance measurement is main tool for code optimization.</li>
<li>There are two types of profiling : Time profiling and Memory profiling</li>
<li>We should also consider memory leaks to optimize code.</li>
</ul>
<p><strong>1) Date</strong></p>
<p>Run script by running date command before and after script to find time when script started execution and when it completed.</p><pre class="crayon-plain-tag">date; python test.py; date</pre><p>This prints time before running script and again print time when execution is complete. So we can find execution time by subtracting end time from start time.</p>
<p><strong>2) time</strong></p>
<p>Unix time command is helpful to figure out how much time command, shell script or python program takes for execution.<br />
Usage:</p><pre class="crayon-plain-tag">time python test.py</pre><p>output:</p><pre class="crayon-plain-tag">python test.py  0.02s user 0.02s system 15{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97} cpu 0.301 total</pre><p></p>
<ul>
<li>User : CPU time spent in user-mode (outside the kernel)</li>
<li>System : CPU time spent in the kernel</li>
<li>CPU : Percent of CPU this job got</li>
<li>Total : elapsed time, start to end</li>
</ul>
<p>Why user + system ≠ total ?<br />
<em>total</em> represents actual elapsed time, while <em>user</em> and <em>sys</em> values represent CPU execution time.</p>
<p><strong>3) /usr/bin/time</strong></p>
<p><em>/usr/bin/time</em> gives more detailed output than &#8216;<em>time</em>&#8216;.<br />
Usage:</p><pre class="crayon-plain-tag">/usr/bin/time -v test.py</pre><p>Output:</p><pre class="crayon-plain-tag">/usr/bin/time: cannot run pycrypto.py: No such file or directory
Command exited with non-zero status 127
	Command being timed: "pycrypto.py"
	User time (seconds): 0.00
	System time (seconds): 0.00
	Percent of CPU this job got: ?{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97}
	Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00
	Average shared text size (kbytes): 0
	Average unshared data size (kbytes): 0
	Average stack size (kbytes): 0
	Average total size (kbytes): 0
	Maximum resident set size (kbytes): 344
	Average resident set size (kbytes): 0
	Major (requiring I/O) page faults: 0
	Minor (reclaiming a frame) page faults: 72
	Voluntary context switches: 1
	Involuntary context switches: 0
	Swaps: 0
	File system inputs: 0
	File system outputs: 0
	Socket messages sent: 0
	Socket messages received: 0
	Signals delivered: 0
	Page size (bytes): 4096
	Exit status: 127</pre><p>What is difference between usr/bin/time and time ?<br />
<em>time</em> is built in unix command and <em>usr/bin/time</em> is GNU time</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/how-to-measure-performance-of-code-basic-methods/">How to measure performance of code ? &#8211; Basic methods</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>http://gauravvichare.com/how-to-measure-performance-of-code-basic-methods/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">223</post-id>	</item>
		<item>
		<title>Size Contest (SPOJ Challenge problem 378)</title>
		<link>http://gauravvichare.com/sizecon/</link>
					<comments>http://gauravvichare.com/sizecon/#respond</comments>
		
		<dc:creator><![CDATA[Gaurav Vichare]]></dc:creator>
		<pubDate>Fri, 29 Nov 2013 19:41:40 +0000</pubDate>
				<category><![CDATA[C language]]></category>
		<guid isPermaLink="false">http://gauravvichare.com/?p=201</guid>

					<description><![CDATA[<p>Given the set of integers, find the sum of all positive integers in it. Solutions can be sent in any language supported by SPOJ except Whitespace. Input t – number of test cases [t &#60; 1000] On each of next t lines given a integer N [-1000 &#60;= N &#60;= 1000] Output One integer equals to sum of all [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/sizecon/">Size Contest (SPOJ Challenge problem 378)</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Given the set of integers, find the sum of all positive integers in it. <b>Solutions can be sent in any language supported by SPOJ except <i>Whitespace</i>.</b></p>
<h3>Input</h3>
<p><i>t</i> – number of test cases [<i>t</i> &lt; 1000]<br />
On each of next t lines given a integer N [-1000 &lt;= N &lt;= 1000]</p>
<h3>Output</h3>
<p>One integer equals to sum of all positive integers.</p>
<h3>Score</h3>
<p>Score equals to size of source code of your program except symbols with ASCII code &lt;= 32.</p>
<h3>Example</h3>
<p></p><pre class="crayon-plain-tag">&lt;b&gt;Input:&lt;/b&gt;
4
5
-5
6
-1
&lt;b&gt;Output:&lt;/b&gt;
11</pre><p>C Program :</p><pre class="crayon-plain-tag">#include&lt;stdio.h&gt;
int main()
{
   unsigned long sum=0;

   short n,a,i;
   scanf("{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97}hu",&amp;n);
   for(i=0;i&lt;n;i++)
   {
       scanf("{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97}hu",&amp;a);
       if(a&gt;0)
       sum+=a;
   }
printf("\n{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97}lu",sum);
   return 0;
}</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/sizecon/">Size Contest (SPOJ Challenge problem 378)</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>http://gauravvichare.com/sizecon/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">201</post-id>	</item>
		<item>
		<title>Factorial  (SPOJ problem 11)</title>
		<link>http://gauravvichare.com/factorial/</link>
					<comments>http://gauravvichare.com/factorial/#comments</comments>
		
		<dc:creator><![CDATA[Gaurav Vichare]]></dc:creator>
		<pubDate>Fri, 11 Oct 2013 06:52:57 +0000</pubDate>
				<category><![CDATA[C language]]></category>
		<guid isPermaLink="false">http://gauravvichare.com/?p=194</guid>

					<description><![CDATA[<p>View problem on SPOJ The most important part of a GSM network is so called Base Transceiver Station (BTS). These transceivers form the areas called cells (this term gave the name to the cellular phone) and every phone connects to the BTS with the strongest signal (in a little simplified view). Of course, BTSes need some attention and technicians need to [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/factorial/">Factorial  (SPOJ problem 11)</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><a href="http://www.spoj.com/problems/FCTRL/" target="_blank">View problem on SPOJ</a></p>
<p>The most important part of a GSM network is so called <em>Base Transceiver Station</em> (<em>BTS</em>). These transceivers form the areas called <em>cells</em> (this term gave the name to the cellular phone) and every phone connects to the BTS with the strongest signal (in a little simplified view). Of course, BTSes need some attention and technicians need to check their function periodically.</p>
<p>ACM technicians faced a very interesting problem recently. Given a set of BTSes to visit, they needed to find the shortest path to visit all of the given points and return back to the central company building. Programmers have spent several months studying this problem but with no results. They were unable to find the solution fast enough. After a long time, one of the programmers found this problem in a conference article. Unfortunately, he found that the problem is so called &#8220;Travelling Salesman Problem&#8221; and it is very hard to solve. If we have <var>N</var> BTSes to be visited, we can visit them in any order, giving us <var>N</var>! possibilities to examine. The function expressing that number is called factorial and can be computed as a product 1.2.3.4&#8230;.<var>N</var>. The number is very high even for a relatively small <var>N</var>.</p>
<p>The programmers understood they had no chance to solve the problem. But because they have already received the research grant from the government, they needed to continue with their studies and produce at least <em>some</em> results. So they started to study behaviour of the factorial function.</p>
<p>For example, they defined the function <var>Z</var>. For any positive integer <var>N</var>, <var>Z</var>(<var>N</var>) is the number of zeros at the end of the decimal form of number <var>N</var>!. They noticed that this function never decreases. If we have two numbers<var>N</var><sub>1</sub>&lt;<var>N</var><sub>2</sub>, then <var>Z</var>(<var>N</var><sub>1</sub>) &lt;= <var>Z</var>(<var>N</var><sub>2</sub>). It is because we can never &#8220;lose&#8221; any trailing zero by multiplying by any positive number. We can only get new and new zeros. The function <var>Z</var> is very interesting, so we need a computer program that can determine its value efficiently.</p>
<h3>Input</h3>
<p>There is a single positive integer <var>T</var> on the first line of input (equal to about 100000). It stands for the number of numbers to follow. Then there are <var>T</var> lines, each containing exactly one positive integer number <var>N</var>, 1 &lt;= <var>N</var>&lt;= 1000000000.</p>
<h3>Output</h3>
<p>For every number <var>N</var>, output a single line containing the single non-negative integer <var>Z</var>(<var>N</var>).</p>
<h3>Example</h3>
<p>Sample Input:</p>
<p>6<br />
3<br />
60<br />
100<br />
1024<br />
23456<br />
8735373<br />
Sample Output:</p>
<p>0<br />
14<br />
24<br />
253<br />
5861<br />
2183837</p>
<p><tt> Program:</tt></p><pre class="crayon-plain-tag">#include&lt;stdio.h&gt;

int main()
{
  int t;
  long long n,sum;

  scanf("{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97}d",&amp;t);
  while(t--)
  {    sum=0;
      scanf("{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97}lld",&amp;n);
      while(n)
      {
          n=n/5;
          sum+=n;
       }
      printf("{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97}lld\n",sum);
   }
return 0;
}</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="http://gauravvichare.com/factorial/">Factorial  (SPOJ problem 11)</a> appeared first on <a rel="nofollow" href="http://gauravvichare.com">Gaurav Vichare</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>http://gauravvichare.com/factorial/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">194</post-id>	</item>
	</channel>
</rss>
