Wednesday, June 28, 2017

How To: Create Thumbnail Image From Base64 Encoded String using Python 3

In this tutorial we 'll create thumbnail image from base64 encoded string received from client/user using python 3.
Our purpose is to create a thumbnail image for each image saved by client/user so that we can send back thumbnail images instead large size images while sending bulk data over the internet.

We are receiving image in form of base64 encoded string, We 'll apply following steps on it for complete result.

1). Decode string using base64 technique.
2). Create temporary image from decoded string.
3). Create thumbnail from this temporary image.
4). Encode thumbnail using base64 technique, so that we can save thumbnail as well in our database.
5). Remove both newly created temporary image and its thumbnail after saving to database.

1). Decode string using base64 technique.

# UserImage holds base64 encoded string. 
TmpUserImage = UserImage.replace("data:image/jpeg;base64,", "") 
ImgDataDecoded = base64.b64decode(TmpUserImage)

2). Create temporary image from decoded string.

# Using uuid for unique file name.
TmpUUID = str(uuid.uuid4()) 
# File name
FileName = TmpUUID + '_image.jpeg' 
# Thumbnail name
FileNameThumb = TmpUUID + '_image_80x80.jpeg' 
# Writing to file.
with open(FileName, 'wb') as f: 
   f.write(ImgDataDecoded)

3). Create thumbnail from this temporary image.

image = Image.open(FileName) 
size = (80, 80) 
thumb = ImageOps.fit(image, size, Image.ANTIALIAS) 
thumb.save(FileNameThumb)

4). Encode thumbnail using base64 technique, so that we can save thumbnail as well in our database.

with open(FileNameThumb, "rb") as thmbn: 
    TmpStr = base64.b64encode(thmbn.read()) 
TmpStr = "data:image/jpeg;base64," + str(TmpStr)[2:-1] 
# Encode to utf-8 before saving to database 
# (don't forget to decode after fetching from database).
TmpStr = bytes(TmpStr,"utf-8")
# Now save TmpStr to database.

5). Remove both newly created temporary image and its thumbnail after saving to database.

if os.path.isfile(FileName): 
    os.remove(FileName) 
if os.path.isfile(FileNameThumb): 
    os.remove(FileNameThumb)

Don't forget to include following libraries.

# For Thumbnail 
from PIL import Image, ImageOps 
import base64, uuid, os

This is all, you have done it. Please ask in comment if there is any confusion. Happy Coding -:)

Sunday, May 28, 2017

How To: Set and Get Cursor Position in Textbox using JQuery

In this tutorial, we 'll learn how to set and get cursor position in text box using jquery.
1). Open notepad, and paste following html code in it.

<html>
<head>
 <title>Home</title>
</head>
<body>
 <input id="first_name" type="text" value="webdesignpluscode" />
 <input onclick="SetPosition();" type="button" value="Set Position" />
 <input onclick="GetPosition();" type="button" value="Get Position" />
</body>
</html>

2). Click File then Save As... in notepad menu. Save As dialogue will open
3). Enter "home.html" in File name:
4). Select All Files in Save as type:
5). Click Save. Notepad file will be saved as html page.
6). Now open this html page in edit mode.
7). Add following online JQuery library reference inside <head> tag.

<script src="https://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>

You can download and add to project locally.

8). Now add java script block inside <head> tag and copy following code there.


<script type="text/javascript">

// Set Cursor Position
 $.fn.setCursorPosition = function (position)
{
 this.each(function (index, elem) {
 if (elem.setSelectionRange) {
 elem.setSelectionRange(position, position);
 }
 else if (elem.createTextRange) {
 var range = elem.createTextRange();
 range.collapse(true);
 range.moveEnd('character', position);
 range.moveStart('character', position);
 range.select();
 }
 });
 return this;
 };

 // Get cursor position
 $.fn.getCursorPosition = function ()
{
 var el = $(this).get(0);
 var position = 0;
 if ('selectionStart' in el) {
 position = el.selectionStart;
 }
 else if ('selection' in document) {
 el.focus();
 var Sel = document.selection.createRange();
 var SelLength = document.selection.createRange().text.length;
 Sel.moveStart('character', -el.value.length);
 position = Sel.text.length - SelLength; }
 return position;
 };

 function SetPosition() {
 $("#first_name").setCursorPosition(5);
 $("#first_name").focus();
 }

 function GetPosition() {
 alert($("#first_name").getCursorPosition());
 $("#first_name").focus();
 }
 </script>

Complete code can be downloaded from this git repository.

This is all. You have done. Save file, and view it in any browser.

Sunday, March 26, 2017

Python Part5: Set and exception handling Try except finally

Set

  • Unordered collection of unique, immutable objects. 
  • Literals: 
    • delimited by { and } 
  • Single comma separated items. 
    • >>> p = {1, 2, 3, 4} 
    • >>> p 
    • {1, 2, 3, 4} 
  • Empty { } makes a dict, so for empty set use the set() constructor. 
    • >>> e = set() 
    • >>> e 
    • set()
  • Set() constructor accepts: 
    • Iterable series of values. 
      • >>> s = set([1, 2, 3, 4]) 
      • >>> s 
      • {1, 2, 3, 4} 
  • Duplicates are discarded. 
    • >>> t = [1, 2, 3, 1, 4] 
    • >>> set(t) 
    • {1, 2, 3, 4} 
  • Often used specifically to remove duplicates – not order preserving. 
  • Order is arbitrary. 
    • >>> for x in {1, 2, 4, 8, 32} 
    • print(x)
  • Use in and not in operators. 
    • >>> q = {2, 9, 6, 4} 
    • >>> 3 in q 
    • False 
    • >>> 3 not in q 
    • True 
  • Add(item) inserts a single element. 
    • >>> k = {2, 4} 
    • >>> k 
    • {2, 4} 
    • >>> k.add(8) 
    • >>> k 
    • {2, 4, 8}
  • Duplicates are silently ignored. 
    • >>> k.add(8) 
    • >>> k 
    • {1, 2, 8} 
  • For multiple elements use update(items) passing any iterable series. 
    • >>> k.update([9, 10]) 
    • >>> k 
    • {1, 2, 8, 9, 10} 
  • Remove(item) requires that item is present, otherwise raises KeyError. 
    • >>> k.remove(9) 
    • >>> k 
    • {1, 2, 8, 10}
  • Discard(item) always succeeds. 
    • >>> k.discard(9) 
  • Copy set using S.copy() method. 
    • >>> j = k.copy() 
  • Use constructor. Set(s) 
    • >>> m = set(j) 
  • Copies are shallows. 
  • S1.union(s2) method. 
    • Union is commutative.
  • s.intersection(t) method 
    • Intersection is commutative. 
  • s.difference(t) method. 
    • Difference is non-commutative. 
  • s.symmetric_difference(t) method 
    • Symmetric difference is commutative. 
  • s.issubset(t) method 
  • s.issuperset(t) method. 
  • s.isdisjoint(t)

Handle exceptions. Try … except … finally

  • try: 
    • x = 5 
  • except: 
    • message = str(sys.exc_info()[1]) 
    • x = -1 
  • finally: 
    • # final-block 
    •  x = 0

Python Part4: For loop, argument passing and Tuple

For loop

  • items = [a, b, c, d] 
  • for item in items: 
    •  print(item) 
  •  for i in range(5) 
    •  print(i)

Argument passing

  • Function with arguments.
  • def modify(k) 
    •  k.append(13) 
    •  print(k) 
  • m = [6, 7, 8, 9] 
  • modify(m) 
  • Default arguments.
  • def DisplayMessage(m='nothing') 
    • print(m) 
  • message = 'Welcome to python' 
  • DisplayMessage(Message) 
  • DisplayMessage()

Tuple

  • Heterogeneous immutable collection. 
  • Delimited by parentheses.
    • For example t = ("norway", 4.953, 3) 
  • Items separated by commas.
  • Element access with square brackets and zero-based index. T[index] 
    • >>> t[0] 
    • 'Norway'
  • len(t) for number of elements. 
    • >>> len(t) 
    • 3
  • Iteration with for loop. 
    • for item in t: 
    • print(item) 
      • Norway 
      • 4.953 
  • Concatenation with + operator. 
    • t + (338186.0, 2659) 
    • ('Norway', 4.953, 3, 338186.0, 2659) 
  • Reputation with * operator. 
    • t * 3 
    • ('Norway', 4.953, 3, 'Norway', 4.953, 3, 'Norway', 4.953, 3)
  • Tuple can contain any kind of object. 
  • Nested tuples.
    • A = ((245, 446), (90, 456)) 
  • Chain square-brackets indexing to access inner elements. 
    • A[1][0] 
    • 90 
  • Can’t use one object in parentheses as a single element tuple. 
  • For a single element tuple include a trailing comma. 
    • K = (234, ) 
  • The empty tuple is simply empty parentheses. 
    • E = ()
  • Delimiting parentheses are optional for one or more elements.
    • p = 1, 1, 1, 4, 6, 19 
    • >>> p 
    • (1, 1, 1, 4, 6, 19) 
  • Tuples are useful for multiple return values. 
    • def MinMax(items) 
      • Return Min(items), Max(items) 
    • >>> MinMax([33, 30, 9, 82, 87]) 
    • (9, 87)
  • Tuple unpacking allow us to destructure directly into named references. 
    • lower, upper = MinMax([33, 30, 9, 82, 87]) 
    • >>> lower 
    • >>> upper 
    • 87
  • Tuple unpacking works with arbitrarily nested tuples (although not with other data structure) 
    • (a, (b, (c, d))) = (4, (3, (2, 1))) 
    • >>> a 
    • >>> b 
    • >>> c 
    • >>> d
    •  1 
  • a, b = b, a is the idiomatic python swap.
  • Use the tuple constructor to create tuples from other iterable series of objects. 
    • >>> tuple([234, 444, 897]) 
    • (234, 444, 897) 
    • >>> tuple("car") 
    • ('c', 'a', 'r') 
  • The in and not in operators can be used with tuples - and other collection types – for membership testing. 
    • >>> 5 in (3, 5, 9, 13) 
    • True 
    • >>> 5 not in (3, 5, 9, 13) 
    • False

Saturday, March 25, 2017

Python Part3: Bytes, Lists, Shallow copies and Dictionaries

Bytes

  • Immutable sequence of bytes.

Lists

  • Mutable sequences of objects.
    • e.g a = [1, 2, 3 ,4]
  • Get or set value using index
    • e.g a[1] = 20 and print(a[1])
  • Negative integers index from the end.
  • The last element is at index -1
  • Slicing extracts part of a list.
    • Slice = seq[start:stop]
  • Slice range is half open-stop not included.
    • >>> s = [1, 2, 3, 4, 5, 6]
    • >>> s[1:4]
    • 2, 3, 4
  • Slicing works with negative indexes. 
    • >>> s[1:-1] 
    • 2, 3, 4, 5 
  • Omitting the stop index slices to the end. 
    • Slice_to_end = seq[start:] 
  • Omitting the start index slices from the beginning. 
    • Slice_from_beginning = seq[:stop] 
  • Half open ranges give complementary.
    • slices S[:x] + s[x:] == s 
  • Omitting the start and stop indexes slices from beginning to the end – a full slice. 
    • Full_slice = seq[:]
  • Important idiom for copying lists: 
  • Copy list using 
    • Copy() method 
      •  U = seq.copy() 
    • List() constructor 
      •  V = list(seq) 
  • All of these techniques create shallow copies, mean create new list containing same object reference to source list.

Shallow copies: Examples

  • >>> A = [[1, 2], [3, 4]] 
  • >>> B = A[:]      (copy using full slice) 
  • >>> A is B      (both objects have different identities.) 
    • False 
  • >>> A == B 
    •  True 
  • >>> A[0] 
    • [1, 2] 
  • >>> B[0] 
    • [1, 2] 
  • A[0] is B[0]      (both objects have same identities.) 
    • True
  • >>> A[0] = [8, 9]      (This create a new list and set reference of A[0] to this.) 
  • >>> A[0] 
    • [8, 9] 
  • >>> B[0]      (B[0] is unchanged because it has reference to old list.) 
    • [1, 2] 
  • >>> A[1].append(5)      (A[1] and B[1] still have reference to same list. So changes reflects in both places.) 
  • >>> A[1] 
    • [3, 4, 5] 
  • >>> B[1] 
    • [3, 4, 5] 
  • >>> A      (Now both lists look like this) 
    • [[8, 9], [3, 4, 5]] 
  • >>> B 
    • [[1, 2], [3, 4, 5]]
  • Repeat lists using the * operator. 
  • Most often used for initializing a list of known size with a constant. 
    • S = [constant] * size 
  • Multiple references to one instance of the constant in the produced list. 
  • Repetition is shallow. 
    • >>> S = [[1, 2]] * 5 
      • [[1, 2], [1, 2], [1, 2], [1, 2], [1, 2]] 
    • >>> S[3].append(7) 
    • >>> S 
      • [[1, 2, 7], [1, 2, 7], [1, 2, 7], [1, 2, 7], [1, 2, 7]] 
  • Index(item) returns the integer index of the first equivalent element raises value error if not found. 
    • I = w.index(‘the’)
  • Count(item) returns the number of matching elements. 
    • W.count(‘the’) 
  • The in and not in operators test for membership. 
    • 5 in [1, 2, 3] 
    • 5 not in [1, 2, 3] 
  • Del seq[index] to remove by index. 
  • Seq.remove(item) to remove by value. Raises value error if not found. 
  • Insert items with seq.insert(index, item) 
  • Concatenate lists with + operator 
    • >>> M = [1, 2] 
    • >>> N = [3, 4] 
    • >>> K = m + n 
    • >>> k 
      • [1, 2, 3, 4]
  • In-place extension with += operator or extend method. 
    •  >>> K += [6, 7] 
    •  >>> K 
      •  [1, 2, 3, 4, 6, 7] 
    •  >>> K.entend([11, 12]) 
    •  >>> K 
      •  [1, 2, 3, 4, 6, 7, 11, 12] 
  • K.reverse() reverses in place. 
  • K.sort() sorts in place. 
  • K.sort(reverse=true) gives descending sort.

Dictionaries

  • Unordered mapping from unique, immutable keys to mutable values. 
  • Recap literals: 
    • Delimited by { and } 
    • Key-value pairs comma separated 
    • Corresponding keys and values joined by colon. 
    • Keys must be unique 
    • Urls = {'google':'http://google.com', 'microsoft':'http://Microsoft.com' } 
    • >>> url['google'] 
      • http://google.com
  • Dict() constructor accepts: 
    • Iterable series of key-value 2-tuples. 
      • >>> Names_and_ages = [('Alice', 32), ('Bob', 48)] 
      • >>> d = dict(Names_and_ages) 
      • >>> d 
        • {'Alice':32, 'Bob':48} 
  • Keyword arguments-requires keys are valid python identifiers. 
  • A mapping, such as another dict. 
    • >>> Phonetic = dict(a='alfa', b='bravo') 
    • >>> phonetic 
      • {'a':'alfa', 'b':'bravo'}
  • d.copy() for copying dictionaries. 
    • >>> e = d.copy() 
    • >>> e 
      • {'Alice':32, 'Bob':48} 
  • Or simply dict(d) constructor 
    • >>> f = dict(e) 
    • >>> f 
      • {'Alice':32, 'Bob':48}
  • Extend a dictionary with update() 
    • >>> g = dict('c':'charle', 'f':'fort') 
    • >>> f.update(g) 
    • >>> f 
      • {'a':'alfa', 'b':'bravo', 'c':'charle', 'f':'fort'} 
  • Update replaces values corresponding to duplicate keys. 
  • Iteration is over keys. 
  • Get corresponding value with d[key] lookup. 
    • >>> for key in f: 
    •  print("{key} => {value}".format(key= key, value=f[key])) 
  • Use values() for an iterable view onto the series of values 
  • No efficient way to get the key corresponding to a value. 
    •  >>> for value in f.values(): 
    •  print(value)
  • Keys() method gives iterable view onto keys – not often needed. 
    • >>> for key in f.keys(): 
    •  print(key) 
  • Use items for an iterable view onto the series of key-value tuples. 
  • Use with tuple unpacking. 
    • >>> for key, value in f.items(): 
    •  print("{key} => {value}".format(key=key, value=value)) 
  • The in and not in operators work on the keys. 
    • >>> 'a' in f 
    • >>> 'h' in f
  • Use del keyword to remove by key. del d[key] 
    • >>> del f['a'] 
  • Keys must be immutable. 
  • Values may be mutable. 
  • The dictionary itself is mutable.