Search

shirishweb

Your right place for "Right to Know"

Python defaultdict() versus dict.get()

Python is a great language. Dict is one of data structure available in python which allows data to store in the form of key/value pair. Many times we might encounter a situation where we have to retrieve a value using the dictionary key. When our key is not found in the dictionary it will throw an exception of KeyError.

KeyError

The solution to this is using defaultdict or dict.get() to return a default value if the key is not found in the dictionary.

Lets dig into both of these

defaultdict can be found in collections module of python. So, in order to use it, we have to import it first as:

from collections import defaultdict
mydict = defaultdict(int)

defaultdict constructor takes default_factory as argument which is a callable. This can be

int : default will be integer value of 0

str : default will be empty string ”

list : default will be empty list []

and so on.

If we want our own default value then we can pass function pointer.

Lets say that we want default value to string ‘default’. We can achieve this in defaultdict as

def mydefault():
        return 'default'

mydict = defaultdict(mydefault)
print mydict['test']

will output ‘default

The same result can also be achieved using the dict.get method as

mydict = {}
mydict.get('test','default')

will output ‘default

Thus same result can be achieved using both approach. dict.get have to provide a default value every time it is called whereas using defaultdict we cant setup a default value only one time.

Now lets check the efficiency of both of them in term of execution time.

For this we will be using ipython notebook since it has got %timeit command to measure the execution of any python statements over any desired looping of same statements.

In Ipython notebook environment, let us create two function that implements defaultdict in one and dict.get method in another.

defining_two_defs

Here we have implemented a() function to execute defaultdict value retrieving and b() to use dict.get method. Now lets calculate the execution time of both function in 100 loops as

defaultdict_timeit

dict.get_timeit_2

First executing a() function over 100 loops we can see that it took over 8.88 micro sec per loop using the best of three.

dict.get_timeit

Here when we run b() function over 100 loops we can see that it tooks 19.3 micro sec per loop using the best of 3 approach.

Hence defaultdict seems more efficient over dict.get method.

Lets rerun this test again but this time will be using default %timeit command of notebook which will be looping the statement for default 1000 loops

defaultdict_timeit_2

Clearly here also defaultdict seems more efficient that dict.get method and the experiment shows that defaultdict more that two times faster than dict.get method.

Advertisements

Hunting for processes holding network port

Many times, we may encounter certain errors within the application showing some strange errors with network issues. Like XAMPP showing error when apache is started complaining that the port is already in use. In such case, we need to find which service/program is using the port and reconfigure the application/service as per the requirement.

Today I will be showing how to hunt for such process using the powershell in windows system step by step. Lets hunt for process holding the network port 80.

  • First start run and type in powershell to start powershell terminal1. Powershell in run
  • Run this command

start powershell -verb runas

2. Start powershell in elevated mode

  • to start another powershell terminal in elevated [administrator privileged mode]
  • Run command

netstat -aonb

3. Netstat command

  • to view all the listening / established / connected ports with details
  • Since this is a long list, looking for specific port might be difficult, so we cant search this list output by using command

    netstat -aonb | findstr :80

5. Grep 80 port from netstat

  • It shows that the process with PID 4088 is holding that port.
  • Now lets find the process with that PID ie 4088. To do this, we can any of two commands as

tasklist | findstr 4088

OR

Get-Process -PID 4088

6. Grep process with pid

  • Voila, we have hunted the process we are looking for. Now we know that port 80 is used by process httpd.exe.

Installing Webmin tool on CentOS 7

Webmin is a free system administrator’s tool which gives the admin the direct configuration of the linux system through web. Thus eliminating the hard-to-remember linux commands. Actually this tool can be used for quick modifications on the linux system like setup user accounts, Apache, DNS, file sharing and much more. If you don’t know the exact commands to configure any aspects of the linux command line system, webmin is your tool.

Installation procedures:

  1. Download the webmin rpm through wget
  2. wget http://prdownloads.sourceforge.net/webadmin/webmin-1.820-1.noarch.rpm
  3. installed required dependencies
  4. yum –y install perl perl-Net-SSLeay openssl perl-IO-Tty
  5. install web from the rpm package
  6. rpm –U webmin-*.rpm

That’ it. It now installed in your system. Now browser https://localhost:10000

If in case of SSL related problem and want to disable it, we can change it in configuration

vim /etc/webmin/miniserv.conf

and change the line containing

ssl=1

to

ssl=0

and open the link  http://localhost:10000 again and login with your root account

Using find command in Unix and Linux systems

“Find” command searches all the files and directories inside directory that matches the given criteria like name, size, ownership, permission etc.

syntax:
find <path> [option/criteria] <argument>
option can be:
-atime <+N/-N/N> :- Access time based search
-mtime <+N/-N/N> :- Modification time based search
-name <Name> :- Name based search
-size <+N/-N/N> :- Size based search
-user <owner> :- owner based seach
-group <group> :- Group based search
-perm <permission> :- Permission based search
-type <type> :- File type based search
type can be ‘f’ or ‘d’ denoting searches for files only or directory only respectively

Examples;
1> Find all the files inside /home/test directory that have been modified within 7 days

1
2> Find all the files with ‘.conf’ filename extension inside the /etc directory

2
3> Find all the empty files (0 length files) inside the current directory

3
4> Find all the files and directories inside the whole system that have the permission ‘770‘ and t hat belongs to the user ‘test’

4
5> Find all the directories inside the /var/log directory

5
6> Find all the files in /etc that have length
a) Exactly 100KB

6
b) Within 100KB

7
c) Greater than 100KB

8
d) That have 100 characters in it.

9

Furthermore, three logical characters can be used to create more filtered search expression for the find query command.
-and
-o
!
7> Find all the empty files inside the current directory and remove them all

10
8> Find all the configuration files with .conf filename extension inside the /etc directory and copy them into the /home/test/backup directory

11
9> Find all the readonly files
12
10>Find all the directories with 770 permission and chmod to 755
14
11> Find all empty directories
15
12> Find all the empty file in current directly only and delete each one showing a prompt
16
13> Find all the files or folder in current directory and copy all the files to /backup directory preserving the permissions, times and ownership of every file and subdirectory
17

Javascript Module: Basic Desing and Pattern

1. Creating a Module
First we need to understand about “Immediately Invoked Function Expression (IIFE)”. These IIFEs are simple function when declared, are called immediately.

IIFE

This will also create a new scope where we can put all out logics. This is an anonymous module. We can namespace this module as

Simple Module

2. Creating a private method

Private method simply is a method that are wrapped inside a module, intended to prevent access from externally outside of the module. This will make our methods more secure. Private methods are useful when we have to access sensitive data over the internet or make external server calls.

code3

3. Module Gateway: “Return”

Inside the module, we will reveal only part of the scope for external access. This is made possible by using the return statement within the Module. This return statement return object the mode and is made accessible from the module’s namespace.

code4

We can access this public method as:

code5

4. Code management with “Locally scoped object literals”

We see in above code that we aren’t namespacing our return object. We can also namespace our returned object with the module scope that makes our code more managed and readable. We can also segregate our private methods from return within the namespaced object.

code6

5. Desing better with revealing module pattern

With revealing module pattern we only return things that are necessary for external access for our module to work perfectly as intended. This create a public gateway to our module and get access to only this that we want to reveal.

code7

6. Extending our module

There might be some cases that our built method doesn’t work fully and lack some of the functionality needed on some cases specifically. In that case we can easily extend our pre built module and add some other functionality within it.

code8

Here we have extended our Module to NewModule that have new “newMethod” added methods.

NewModule has an argument Module || {}. Here we have passed pre-built Module to the NewModule. If this Module is not defined or “undefined” then we pass new object “{}” as argument to our NewModule and extend it.

WiMAX

WiMAX (Worldwide Interoperability for Microwave Access) is a wireless communications standard designed to provide 30 to 40 megabit-per-second data rates, with the 2011 update providing up to 1 Gbit/s for fixed stations. WiMAX refers to interoperable implementations of the IEEE 802.16 family of wireless-networks standards ratified by the WiMAX Forum. WiMAX can provide at-home or mobile Internet access across whole cities or countries. In many cases this has resulted in competition in markets which typically only had access through an existing incumbent DSL (or similar) operator.

The bandwidth and range of WiMAX make it suitable for the following potential applications:

  • Providing portable mobile broadband connectivity across cities and countries through a variety of devices.
  • Providing a wireless alternative to cable and digital subscriber line (DSL) for “last mile” broadband access.
  • Providing data, telecommunications (VoIP) and IPTV services (triple play).
  • Providing a source of Internet connectivity as part of a business continuity plan.
  • Smart grids and metering

Mobile WiMAX was a replacement candidate for cellular phone technologies such as GSM and CDMA, or can be used as an overlay to increase capacity. Fixed WiMAX is also considered as a wireless backhaul technology for 2G, 3G, and 4G networks in both developed and developing nations. Devices that provide connectivity to a WiMAX network are known as subscriber stations (SS). Portable units include handsets (similar to cellular smartphones); PC peripherals (PC Cards or USB dongles); and embedded devices in laptops, which are now available for Wi-Fi services. In addition, there is much emphasis by operators on consumer electronics devices such as Gaming consoles, MP3 players and similar devices. WiMAX is more similar to Wi-Fi than to other 3G cellular technologies. USB can provide connectivity to a WiMAX network through what is called a dongle. Generally these devices are connected to a notebook or net book computer. Dongles typically have omnidirectional antennas which are of lower gain compared to other devices. As such these devices are best used in areas of good coverage. Mobile_wimax_usb

Comparisons and confusion between WiMAX and Wi-Fi are frequent, because both are related to wireless connectivity and Internet access.

  • WiMAX is a long range system, covering many kilometres, that uses licensed or unlicensed spectrum to deliver connection to a network, in most cases the Internet.
  • Wi-Fi uses the 2.4 GHz, 3 GHz, 5 GHz, and 60 GHz radio frequency bands to provide access to a local network.
  • Wi-Fi is more popular in end-user devices.
  • Wi-Fi runs on the Media Access Control’s CSMA/CA protocol, which is connectionless and contention based, whereas WiMAX runs a connection-oriented MAC.
  • WiMAX and Wi-Fi have quite different quality of service (QoS) mechanisms:
    • WiMAX uses a QoS mechanism based on connections between the base station and the user device. Each connection is based on specific scheduling algorithms.
    • Wi-Fi uses contention access — all subscriber stations that wish to pass data through a wireless access point (AP) are competing for the AP’s attention on a random interrupt basis. This can cause subscriber stations distant from the AP to be repeatedly interrupted by closer stations, greatly reducing their throughput.
  • Both IEEE 802.11, which includes Wi-Fi, and IEEE 802.16, which includes WiMAX, define Peer-to-Peer (P2P) and wireless ad hoc networks, where an end user communicates to users or servers on another Local Area Network (LAN) using its access point or base station. However, 802.11 supports also direct ad hoc or peer to peer networking between end user devices without an access point while 802.16 end user devices must be in range of the base station.

Although Wi-Fi and WiMAX are designed for different situations, they are complementary. WiMAX network operators typically provide a WiMAX Subscriber Unit that connects to the metropolitan WiMAX network and provides Wi-Fi connectivity within the home or business for local devices, e.g., computers, Wi-Fi handsets and smartphones. This enables the user to place the WiMAX Subscriber Unit in the best reception area, such as a window, and still be able to use the WiMAX network from any place within their residence.

The local area network inside one’s house or business would operate as with any other wired or wireless network. If one were to connect the WiMAX Subscriber Unit directly to a WiMAX-enabled computer, that would limit access to a single device. As an alternative for a LAN, one could purchase a WiMAX modem with a built-in wireless Wi-Fi router, allowing one to connect multiple devices to create a LAN.

Using WiMAX could be an advantage, since it is typically faster than most cable modems with download speeds between 3 and 6 Mbit/s, and generally costs less than cable.

Increase you internet speed by limiting QoS.

There is a feature in windows machine where the Microsoft reserves your some percentage of your internet bandwidth speed. QoS packet scheduler Provides traffic control on a network using IPSEC and applications and equipment supporting the quality of service. The service also manages the quality of bandwidth. In fact the service is expected to provide a kind of intelligent allocation of bandwidth between applications where the need is greatest. for this purpose the 20% is also has been denied by Microsoft. If you do not use netmeeting or windows media player (to play internet stream, streaming) you can disable it.

For this,

  • go to run (Win +R )
  • in the run-box type in gpedit.msc
  • A Group Policy window appears. Go to Computer Configuration > Administrative Template > Network. Open QoS packet scheduler and select limit reservable bandwidth and put the value ( between 0-100 ) in the Bandwidth limit % box. Minimum value ensure greater increase in internet speed or you can disable it by selecting not configured.

QoS feature  is not available in Window 7.

BLOCK ANY WEBSITES ON YOUR FRIEND’S COMPUTER!!!

This tutorial will teach you “how to block specific website on a computer”

If you are running Vista/Window7 , you need to have administrative right. For this you need to log on windows with your account with administrative rights(to access the folder system32)

Now just Go to My computer and then go to the C:\ drive or whichever is your root drive. Then just go to Folder “windows” and then to “system32” folder. There you can see another folder “drivers” , just double click it. Then go to folder “etc” . Overall you are in:

C:\windows\system32\drivers\etc

there you can see a file named hosts. Just open a notepad and drag and drop the file to the notepad. This will show you a some lines of texts as “This is a sample host file used by…………”. If you see this you’re right in the place where you should be. Now just below the 127.0.0.1 write another 127.0.0.1 (this is the ip address the computer i.e source ip address) and press tab and then type in the address of the website that you want to block and save it (CTRL + S).This will do it! Now the computer will be blocked to the specified website…You can check by going to the website through your internet browser.

Note: you can also open hosts file by typing following in the cmd(command)

notepad “C:\windows\system32\drivers\etc\hosts”

and modified the contents as your requirement.

Amazing Stuffs that can be added to your Browser

Image

This slideshow requires JavaScript.

Add a multifunction clock to your desktop

Windows 7 includes some useful utilities like a calculator and the snipping tool. What it lacks, however, is an alarm clock and a stop watch.

If you use the Google Chrome browser, here’s how you can add a multifunction clock to your desktop:

First, install the Clock app by Google, from the Chrome Web Store.

Next, click on the Clock app from your list of Chrome apps to launch it. The clock will launch into the time and date tab first. The other tabs are for world clock, alarm, timer, and stop watch.

Windows users who want to launch it from the taskbar, can pin it there. Just right-click on the Clock app from your Chrome app list, then select “Create shortcut.” Make sure that “Pin to Taskbar” is checked then click the “Create” button.

That’s it. Now you’ve got cool little multifunction clock on your desktop that works even when you’re offline.

View slideshows of local files in Firefox

You use Firefox (or another browser) to view photos on Facebook, Picasa, and other photo-sharing sites, and with Slide Show Viewer, a Firefox extension, Windows users can use Firefox to view slideshows of the photos stored on their hard drive.

After installing the add-on (you can download it here), you’ll find it located in the tools menu. You can find the tools menu by going to Option and clicking Menu Bar to show that toolbar. Then from Tools in the menu bar you’ll see Slide Show Viewer listed. (You can also add an icon for Slide Show Viewer to the menu bar by following this path View > Toolbars > Customize and then dragging it from the list to the menu bar.

Click Slide Show Viewer from the Tools menu and it opens in a new tab. From the menu in the upper-right corner of the page, you can navigate to a folder to view. In my experience, I could view only folders containing images. I couldn’t, for example, view a folder of Office docs, though I’m not sure why anyone would want to watch a slideshow of Word and Excel docs.

To flip through pictures when viewing a slideshow, you can use the arrow keys (right or up arrow to move forward, left or down arrow to move back) or the mouse buttons (left button to move back and the right mouse button to move forward). You can use your mouse’s scroll wheel to pan and scroll on full-size images that are too large to fit in your Firefox window.

Unfortunately, I couldn’t find any way to play a slideshow where it would automatically flip through photos in a given folder. Also, I couldn’t play a folder that contained folders of photos. For example, I could not view the Pictures folder but had to drill down to either the Sample Pictures or the Stage folder to view images.

From the control panel in the upper-right corner, you can use two check boxes to view the full image or have it cropped to fit your browser window. You can use the Escape key to hide and restore the control panel

Create a free website or blog at WordPress.com.

Up ↑