Tuesday, November 25, 2014

Instagram Photo Cycler JavaSscript widget


A while ago I built for the company I work for a nice Dashboard presenting business and operational data on a TV.

I wanted to add to the Dashboard something cool that will drive people to be more creative.

I had an idea of showing on the dashboard Instagram photos of the company by posting photos to a predefined hashtag. For example: #mycompany.

There was one problem: the real-estate on a dashboard TV screen is very expensive and you can not show more then a single photo.

I remembered that I once encountered a cool JavaScript widget that simply cycles photos with nice transition effects. I thought that it will be nice to connect this widget with Instagram and put it on the dashboard.

Back then I didn't know that I can also get the assistance of Instafeed.js in order to get Instagram data easily, so I had to write this part my self.

The result was pretty cool, so I decided to make a jQuery widget from it to allow others to use it as well. You can download the widget and use it for your own photos or for showing photos of some hashtag.

Here is how the widget looks like for the hashtag #love:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
<script src="http://cdn.rawgit.com/malsup/cycle/master/jquery.cycle.lite.js" type="text/javascript"></script>
<script src="https://docs.google.com/uc?export=download&id=0B8vXkKUFKJw4anFQam9reXhyNWc" type="text/javascript"></script>

<br />
<div id="instagramCyclerCoderEyeLove" style="width:320px; height:320px;">
</div>
<script language="JavaScript">
 <!--

  $(document).ready(function() {
   $('#instagramCyclerCoderEyeLove').cycleInstagram({
    'get':   'tagged',
    'tagName':  'love',
    'accessToken': '161840.f92bbd9.e0a09d9b00f746c8b2662a4e784e55b0'
   });
  });

 </script>

And here is the result:

In order to show your own photos you can use the property "get" with the "user" value. Please note that in order to show you own photos, you can simply use for "userId" the word "self". In addition you can see how you can show more than just a photo and even control look of the widget very easily with the "template" property and simple usage of CSS:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
<script src="http://cdn.rawgit.com/malsup/cycle/master/jquery.cycle.lite.js" type="text/javascript"></script>
<script src="https://docs.google.com/uc?export=download&id=0B8vXkKUFKJw4anFQam9reXhyNWc" type="text/javascript"></script>

 <style>
  #instagramCyclerCodeEyerUser {
   background-image: url("https://docs.google.com/uc?export=download&id=0B8vXkKUFKJw4a1JVbTNoY0N0T0U"); 
   background-size: cover; 
   width:326px; 
   height:380px;
  }

  #instagramCyclerCodeEyerUser img {
   padding-top:28px;
   padding-left:36px;
  }

  #instagramCaption {
   margin-top:25px;
   padding-left:36px;
   font-size:18px;
   font-family: ‘Lucida Sans Unicode’, ‘Lucida Grande’, sans-serif;
   width: 250px;
   white-space: nowrap;
   overflow: hidden;
   text-overflow: ellipsis;
  }

 </style>

<div id="instagramCyclerCodeEyerUser"></div>
<script language="JavaScript">

  $(document).ready(function() {
   $('#instagramCyclerCodeEyerUser').cycleInstagram({
    'get':   'user',
    'userId':  'self',
    'tagName':  'todacellmon',
    'accessToken': '161840.f92bbd9.e0a09d9b00f746c8b2662a4e784e55b0',
    'template': '<div><a href="{{link}}"><img src="{{image}}" width="250" height="250" /></a><div id="instagramCaption">{{caption}}</div></div>'
   });
  });

 </script>


Here is the result:

PLEASE NOTE: In order to use Instagram API, you should create an access token. You have nothing to worry that others can see your access token as long as you create an access token only for READING. Frankly, creating the access token on Instagram, at least at the time that I did it, was not a simple task. You can find more help on how to do it on Instagram developers section or on this url

DOWNLOAD: Here you can download the widget

Thursday, November 13, 2014

Working with SHA1 on SQL Server


There are times you might need to convert some information to MD5 on your SQL Server in HEX format. As it is for now there is no out of the box function to do it on SQL Server. But you can easily accomplish this task by using the following function:
create FUNCTION [dbo].[sha1]
(
        @value varchar(4000)
)
RETURNS varchar(40)
AS
BEGIN
  return
    case when @value is not null then
      SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA1', @value)), 3, 40)
    else null end
END
GO

Testing it is quite straight forward. For example:
select dbo.sha1('123') 

And here is the output:
40bd001563085fc35165329ea1ff5c5ecbdbbeef


 

Wednesday, November 12, 2014

Working with MD5 on SQL Server


There are times you might need to convert some information to MD5 on your SQL Server in HEX format. As it is for now there is no out of the box function to do it on SQL Server. But you can easily accomplish this task by using the following function:
create FUNCTION [dbo].[md5]
(
        @value varchar(4000)
)
RETURNS varchar(40)
AS
BEGIN
  return
    case when @value is not null then
      (SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', @value)), 3, 32))
    else null end
END
GO

Testing it is quite straight forward. For example:
select dbo.md5('123') 

And here is the output:
202cb962ac59075b964b07152d234b70 


 

Tuesday, April 9, 2013

PC speaker beeps with no apparent reason

I had this problem for about few months: from time to time with no warning, my PC started beeping from its speakers for no apparent reason.
Sometimes it started with several beeps, sometimes it started with a single long beep. When I restarted my computer the problem seemed to pass till the next time.
First, I suspected I had a virus. I made sure I updated my Kaspersky to the latest version and scanned for viruses with no luck.

I then went to Windows device drivers manager and stopped the speakers service - but still, the beep used to come whenever it wanted. Eventually, I came with the theory that my machine is getting too hot and therefore I get a warning beep. So I opened the case of the PC to make sure my ventilation is working properly - all seemed right.

So, I decided to download this small app named Core Temp. It can give detailed about the temperature of each core of your CPU. It uses information from the CPU itself and not sensors that measure temperature outside the CPU.

After loading the app I noticed the temperature was around 70 degrees. It seems to me a bit high, but nothing unreasonable. So I decided to wait for the next beep to come.
After few days the beep came again. I loaded the Core Temp and was amazed to see that the CPU temperature was on 95 degrees!
I quickly opened my PC case and noticed both ventilation are working properly. So I decided to give a closer look at the hit sink below the CPU ventilation. I noticed a huge amount of dust that filled the hit sink.

I started cleaning all the dust that accumulated there along the time. Then started my computer again and loaded the Core Temp. Then I noticed the temperature was around 35 degrees!
Eventually the mystery was solved: my PC was beeping like crazy, since the CPU was hitting too much and I couldn't tell there was a problem, because ventilation seemed to work properly.
So if your PC starts to beep with no apparent reason, do yourself a favor and give it attention. It might say that something is seriously wrong. Probably your CPU is over hitting and the blame might be more then a low performing ventilation: DUST.
I assume that the dust may have caused 2 major things:
  • Less effective hit dispensation.
  • Increases the drag of the ventilation and therefore cause it to rotate slower.
When my computer was not working too hard: temperature was around 70 degrees, which was not so good, but not so bad.

When my computer was working hard, CPU temperature started climbing higher and higher till  it reached around 95 degrees and the computer started beeping to warn about the hit.
The small difference of removing the excessive dust made the difference for more than 50 degrees! Worth the effort!

Monday, February 4, 2013

Change address bar back to Google on FireFox

Nowadays, when you install new software on your machine, you can never know if it comes with some other bundled packages that during installation simply change the behavior of your browser/system. During the installation process you get a small check box selected by default, usually on the bottom of the window so you do not notice that you are going to install some additional software.

Lately this thing happened to me, even tough I always pay attention to these kind of things. I even do not remember what I installed. But as a result of the installation I was not longer able to directly do search on my FireFox address bar.
Companies that usually change the address bar for you without you wanting it are:
I was able to repair this issue very easily by doing the following steps:
  1. Write on FireFox address bar: "about:config". It will take you to advanced settings of FireFox.
  2. Use the "search" text field on the top to filter: "keyword.URL".
  3. Right click on the resulted row and select: "Reset".
That's it. As simply as that.

It is also a good thing if you will try to filter the list by the strings: "ask" and "conduit" in order to reset other things they might have changed in you browser.
Please make sure that you do not do mistakes in the process.

Thursday, July 12, 2012

Use Google photos screen saver without installing Picasa



Google photo screen saver used to be part of Google Pack. Then Google decided to move it under Picasa. That means, that if you want to use Google photo screen saver you have to install Picasa.


I use Adobe Light Room to edit my photos and I love it. I love Google's photo screen saver. It shows photos much more nicely then Microsoft's built-in photos screen saver and also ads more sources to get photos (like RSS feeds from the internet).


I wanted to install Google's photo screen saver without needing to install Picasa. I managed to do it easily by installing Picasa, grabbing it's screen saver file: GPhoto.scr and then uninstalling Picasa.


If you would like to use Google photo screen saver without needing to install Picasa, you can simply download it here, then place this file under Windows folder: c:\windows (or you own windows installation folder).


When going to screen savers selection on Windows (the location of this option depends on your Windows version, but can be easily found) you should see Google's photos screen saver on the screen savers list.


Enjoy it!

Monday, June 6, 2011

Configure Timeout for Apache HttpClient 4.0

Adding HTTP request timeout support to HttpClient 4.0  of Appache is quite an easy task. But not as straight forward as one might think. I needed to add such timeout for one of my HTTP requests. I expected to have a method named: "setTimout" or "setConnectionTimeout". But couldn't find any method regarding timeout. After a little digging I found how it can be done. Hope it will save you some time.
In general, all you have to do is create an instance of HttpParams and use it in order to define the connection timeout.
Let's see how the code looks:
package com.bashan.blog.http;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
/**
 * @author Bashan
 */
public class HttpRequest {
  public static void main(String[] args) throws Exception {
    // Set connection timeout
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 5000);
    HttpConnectionParams.setSoTimeout(params, 5000);
    HttpClient httpClient = new DefaultHttpClient(params);
    HttpResponse response = httpClient.execute(new HttpGet("http://google.com"));
    System.out.print(EntityUtils.toString(response.getEntity()));
  }
}

You can see in the 3 lines marked in yellow, how the HttpParams class is used in order to define the connection timeout. Later an HttpClient instance is created with params that is passed to it.


You can download this class here.

Friday, May 27, 2011

Show timer with seconds using NSTimer on iPhone and Objective C

I am currently developing an iPhone App using X-Code and Objective-C. I had to show a simple timer showing the elapsed number of seconds and minutes. I don’t know much about Objective-C, but from my past experience I knew this task can be easily accomplished using a Timer. The timer should be called every second, and a simple int variable will hold the seconds. The variable is incremented on every call of the timer.
This is how I the timer is defined:
NSTimer *mainTimer = [NSTimer scheduledTimerWithTimeInterval:1 
                  target:self 
                  selector:@selector(timerController) 
                  userInfo:nil 
                  repeats:YES];

Note that the timer is set to be activated every one second and the function that will be called every one second is named “timerController”.

In the “timerController” function I wrote the code that will increment the seconds variable as well as update a label on the screen. In order to update the label with the minutes and seconds I wrote a small function. The function gets seconds and returns a string of the format: “mm:ss” (for example, for input of 90 the function will return: “01:30”. Let’s see the function that returns the time:


- (NSString*)getTimeStr : (int) secondsElapsed {
  int seconds = secondsElapsed % 60;
  int minutes = secondsElapsed / 60;
  return [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
}

And let’s have a look at the “timeController” function that use it:


- (void)timerController {
  seconds++;
  [[self timeLabel] setText:[self getTimeStr]];
}

The “timeLable” is a UILabel control that is connected with a label that is show on the iPhone screen.


Thursday, May 26, 2011

Add Facebook Like Button to your Blogger.com (BlogSpot)

Facebook Like button is a great and easy way of sharing things that you like with your friends. If you have a blog on Blogger.com (BlogSpot) you can easily add a Facebook like button to any of your posts. Each post will have it's own Like button. This can help increasing the traffic of your blog.

Let's see how we can easily add Facebook like button:

Step 1: Editing out blog template as HTML:

  • press on: "Design" on your blog main menu.
  • Then press on "Edit HTML" on the upper sub menu.
  • Check "Expand Widget Templates" checkbox.
Step 2: Find the place in which Facebook Like button code should be entered:
Search for the String:
<data:post.body/>
Facebook Like button should be placed before this code.

Step 3: Put the following code in your blog template:
<b:if cond='data:blog.pageType == &quot;item&quot;'>
<iframe allowTransparency='true' expr:src='&quot;http://www.facebook.com/plugins/like.php?href=&quot; + data:post.url + &quot;&amp;layout=standard&amp;show_faces=false&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&quot;' frameborder='0' scrolling='no' style='border:none; overflow:hidden; width:450px; height:40px;'/>
</b:if>

After you save your template, go to one of your posts. You could see that a Facebook Like button was added right under the name of your post.

Monday, May 16, 2011

Log4j SMTPAppender and deadlocks - Adding Timeout support

On the post: Sending Email alerts with Log4j we saw how we can easily send mails whenever our system has an exception. But we have to remember that using Apache Log4j SMTPAppender, can be very risky if not used cautiously. In general, the Log4j SMTPAppender has 2 main problems:

  1. The part that send the mail, is synchronous. In fact, it is synchronous between all Log4j appenders. It means that when you log an error and a mail is being sent, all log commands are locked. This is quite risky. Especially when your system has many errors (for whatever reason). This may cause your whole system to get stuck. This issue can be easily handled by using: AsyncAppender. I may write about AsyncAppender in more detail in the future.
  2. The code responsible for sending the mail, which is written by Apache developers, doesn't has a Timeout. That mean, a mail being sent can be stuck forever and simply cause your entire system to go into a deadlock.
    In this post, we will improve the Apache SMTPAppender to include a Timeout property. The Timout property will make sure, that if a mail is being sent using SMTP connection for too long, it will be dropped. We may loose a report about an exception, but we will make sure our system won't be stuck indefinitely.


We will create a new class name: SMTPAppenderTimeout, that extends SMTPAppender. This new class will override the SMTPAppender method: createSession.
The new createSession method will make sure to add the following 2 properties to the mail session: 

  • mail.smtp.connectiontimeout
  • mail.smtp.timeout


These 2 properties instruct the Java mail framework to set a timeout on the SMTP connection.
Let's have a look on the SMTPAppenderTimeout class:

package com.bashan.blog; 
import org.apache.log4j.net.SMTPAppender; 
import javax.mail.Authenticator; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import java.util.Properties; 
/** 
* @author Bashan 
*/ 
public class SMTPAppenderTimeout extends SMTPAppender { 
  private int timeout; 
  public int getTimeout() { 
    return timeout; 
  } 
  public void setTimeout(int timeout) { 
    this.timeout = timeout; 
  } 
  @Override 
  protected Session createSession() { 
    Properties props; 
    try { 
      props = new Properties(System.getProperties()); 
    } catch (SecurityException ex) { 
      props = new Properties(); 
    } 
    if (timeout > 0) { 
      String timeoutStr = Integer.toString(timeout); 
      props.setProperty("mail.smtp.connectiontimeout", timeoutStr); 
      props.setProperty("mail.smtp.timeout", timeoutStr); 
    } 
    if (getSMTPHost() != null) { 
      props.put("mail.smtp.host", getSMTPHost()); 
    } 
    Authenticator auth = null; 
    if (getSMTPPassword() != null && getSMTPUsername() != null) { 
      props.put("mail.smtp.auth", "true"); 
      auth = new Authenticator() { 
        protected PasswordAuthentication getPasswordAuthentication() { 
          return new PasswordAuthentication(getSMTPUsername(), getSMTPPassword()); 
        } 
      }; 
    } 
    Session session = Session.getInstance(props, auth); 
    if (getSMTPDebug()) { 
      session.setDebug(getSMTPDebug()); 
    } 
    return session; 
  } 
} 

You can also download the SMTPAppenderTimeout.



Let's see an example of a log4j.xml file which use SMTPAppenderTimeout to allow timeout of 5 seconds (5000ms):       


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
	
	<appender name="RollFile" class="org.apache.log4j.RollingFileAppender">
		<param name="File" value="C:\\testlog.txt" />
		<param name="MaxFileSize" value="10MB" />
		<param name="MaxBackupIndex" value="1" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d{HH:mm:ss} %-5p [%c{1}]: %m%n" />
		</layout>
	</appender>
	<appender name="Email" class="com.bashan.blog.SMTPAppenderTimeout">
		<param name="BufferSize" value="10" />
		<param name="SMTPHost" value="smtpout.secureserver.net" />
		<param name="SMTPUsername" value="test_user" />
		<param name="SMTPPassword" value="test_password" />
		<param name="Timeout" value="5000" />
		<param name="From" value="someone@mail.com" />
		<param name="To" value="bashan@mail.com" />
		<param name="Subject" value="System Error Notification" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d [%t] %-5p %c %x - %m%n" />
		</layout>
	</appender>
	
	<root>
		<priority value="info" />
		<appender-ref ref="RollFile" />
		<appender-ref ref="Email" />
	</root>
</log4j:configuration>

You can also download the log4j.xml.