CodingChillout.Malta: HTML tags

http://codechillout.sphere-contest.com/problems/onlineround/HTMLTAGS

HTML tags

We often write HTML tags with both lower-case and capital letters. As a result, the website’s source code looks ugly. Your task is to write a program which will turn all the lowe-case letters in the HTML tags (i.e. those appearing in between of the signs “<” a “>”) into capital letters.

Input

You are given a fragment of HTML source code.

Output

Your output should print the same HTML source code, but with all the HTML tags written in capital letters.

Example

Input:
<html>
<head>
<TITLE>This is title</Title>
</head>
<body>
<b>Something</b>
</body>
</html>

Output:
<HTML>
<HEAD>
<TITLE>This is title</TITLE>
</HEAD>
<BODY>
<B>Something</B>
</BODY>
</HTML>

Answer

import fileinput
for line in fileinput.input():
   res = '';
   for c in line:
    if(c == '< '):
        flag = True
    elif(c == '>'):
        flag = False
    if(flag == False):
        res += c
    elif(flag == True):
        res += c.upper()
   print res

CodingChillout.Malta: Simple Number Conversion

http://codechillout.sphere-contest.com/problems/onlineround/CONVERT

Converting a number from any base to any base.
Assume that n ≤ 36 and the digits are 0,1,2,3,4,5,6,7,8,9, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z.

Input

The first line contains integer N, the number of test cases.
n s r
n is the number to convert
s is the source base
r is the resulting base

Output

For each n s r, output the number n in r base.

Example

Input:
4
56378 10 2
AB98BC 15 10
ABCDEF123456 36 2
1000100101010 2 10

Output:
1101110000111010
8182977
1001011010111011111010000110001101100010101101000110110111010
4394

import sys

digits ="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def base2base(number,rBase,sBase):
    '''
    # Implementation of Any base to Decimal, but int() is faster
    dec = 0
    for n in number:
        dec = digits.index(n,0,rBase) + dec * rBase
    '''
    dec = int(number,rBase)
    result = []
    while(dec != 0):
        dec,mod = divmod(dec, sBase)
        result.insert(0,digits[mod])
    for i in result:
        sys.stdout.write( "%s" % (i))
    print


instances = int(raw_input())
for v in range(0,instances):
    data = raw_input().split(" ")
    number = data[0]
    rBase = int(data[1])
    sBase = int(data[2])
    if(number != '0'):
       base2base(number,rBase,sBase)
    else:
        print 0

Code on Ideone

Finding the next Palindrome

Given a positive palindrome number P up to 10,000,000 digits. Find the next palindrome.

Input

The first line contains integer n, the number of test cases. Integers P are given in the next t lines.

Output

For each P, output the next palindrome larger than P.

Example

Input:
12
1
9
12
99
101
999
1001
808
900000000000000000000000000000000000009
123454321
1999999999991
199999999991

Output:
2
11
23
101
111
1001
1111
818
900000000000000000010000000000000000009
123464321
2000000000002
200000000002

#include 
#include 
#include 
#include 
int main(void) {
	char * number;
	int instances;
	scanf("%d", &instances);
	int i;
	for (i = 0; i < instances; i++){
		number =  malloc(sizeof(char)*(10000000));
		scanf("%s", number);
		int len = strlen(number);
		int k;
		int flag = 1;
		
		// In case the number is all 9s
		for (k = 0; k < len; k++){
			if (number[k] != '9'){
				flag = 0;
			}
		}
		
		if (flag == 1){
			printf("1");
			for (k = 0; k < len - 1; k++){
				printf("0");
			}
			printf("1\n");

		}
		else{
			int left = (int)ceil((double)len / 2)-1;
            int right;
			if(len%2 == 0)
			   right = left+1;
			 else
			   right = left;
			
			for (k = 0; k <= (int)floor(len / 2.0); k++){
				// if middle numbers are not 9
				if ((number[left] != '9') && (number[right] != '9')){
					int numL = number[left];
					int numR = number[right];
					number[left--] = (char)(numL + 1);
					number[right++] = (char)(numR + 1);
					break;
				}
				else{ // if middle numbers are 9
					number[left--] = '0';
					number[right++] = '0';
				}
			}
			printf("%s\n", number);
		}
	}
	free(number);
	return 0;
}

Code on ideone

.NET HTTPRequest

HTTP Handlers
They are used to process individual endpoints.
Only one handler per request is used
Can be both asynchronous or synchronous
Earliest possible point where you have access to requests

 

HTTPHandlers are extension based. This means that for every extension .aspx .html etc there is a handler (some share handler).

The example used here is very simple and does nothing special except for displaying some static text. The reason is that ideally before attempting to do something elaborate one should check if it works by doing something simple especially while learning.

The examples here were created in ASP.MVC5 applications. The extension that is used is .kk

Synchronous HTTP Handler

The Solution name is HTTP_Handler

Step 1:

Ignore routing for .kk extension in App_Start/RouteConfig.cs (The reason is that we do not want MVC to try to interpret this file)

routes.IgnoreRoute("{file}.kk");

Step 2:

We create the class that will be our handler at the top level  since this is an example and name it CustomHandler.cs

This can be achieved by inheriting IHttpHandler or by using IHttpHandlerFactory (The example uses IHttpHandler)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HTTP_Handler
{
public class CustomHandler : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
HttpRequest Request = context.Request;
HttpResponse Response = context.Response;
Response.Write("test");
}

public bool IsReusable
{
get { return true; }
}
}
}

Step 3:

We configure the application to use the handler (Integrated mode).

In web.config

<system.webServer>

<handlers>

<add verb="*" path="*.kk" name="CustomHandler" type="HTTP_Handler.CustomHandler"/>

</handlers>

Step 4:

Build and Run

add hello.kk to the link and load it should print test on screen.

 Asynchronous HTTP Handler

 

The Solution name is HTTP_Async_Handler

Step 1:

Ignore routing for .kk extension in App_Start/RouteConfig.cs (The reason is that we do not want MVC to try to interpret this file)

routes.IgnoreRoute("{file}.kk");

Step 2:

We create the class that will be our handler at the top level  since this is an example and name it CustomHandler.cs

This can be achieved by inheriting IHttpAsyncHandler

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HTTP_Async_Handler
{
public class CustomHandler:IHttpAsyncHandler
{
// Long Process
private static void generateNumbers(HttpContext context)
{
string s = "";
for (int i = 0; i < 1000; i++)
{
s = s + ' ' + i.ToString();
}
context.Response.Write(s);
}

public static Action<HttpContext> _Handle = generateNumbers;

public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
context.Response.Write("BeginProcessRequest Executed");
return _Handle.BeginInvoke(context,cb,extraData);
}

public void EndProcessRequest(IAsyncResult result)
{
// Clean up code here
}

public bool IsReusable
{
get { return true; }
}

public void ProcessRequest(HttpContext context)
{
context.Response.Write("ProcessRequest Executed Will not execute");
}
}
}

Step 3:

We configure the application to use the handler (Integrated mode).

In web.config

<system.webServer>

<handlers>

<add verb="*" path="*.kk" name="CustomHandler" type="HTTP_Handler.CustomHandler"/>

</handlers>

</system.webServer>

Step 4:

Build and Run

add hello.kk to the link and load it should print test on screen.

 

Want to know more?

Investigate IHttpHandlerFactory

Classic mode & Integrated mode (IIS)

Send an SMS over My GO account programmatically using c# ( Outdated)

Introduction

As the title says this post describes how to send SMS messages from GO mobile website www.go.com.mt/mygo/  programmatically with C#.  This is for educational purposes only and I’m not affiliated in any way to GO. Use the contents of this page  at your own risk.

Requirements:

  • GO Mobile phone line
  • My Go account for the phone line (Free for every GO Mobile phone)

Tools Used:

Sending an SMS manually

Browse www.go.com.mt/mygo/

Go mobile login
Fig:1

To send an SMS  a user first has to login with his mobile number and password as shown in Fig:1

Go Sms form
Fig:2

If the login is successful the user is given access to the  form in Fig:2 that takes recipients and a maximum of 420 characters in an SMS. When finished typing the desired SMS click send SMS button.

How to achieve the above programmatically?

To send an SMS there are needed two POSTs, one for Login and the other for the actual SMS to be sent. So a method for sending a POST over HTTPS was created.

  1. public static void httpsPost(String uri, String post_data, String referer,  CookieContainer cookieC){
  2. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
  3. request.ProtocolVersion = HttpVersion.Version11;
  4. request.Method = "POST";
  5. request.ContentType = "application/x-www-form-urlencoded";
  6. request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0";
  7. request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
  8. request.KeepAlive = true;
  9. request.ReadWriteTimeout = 300;
  10. request.Referer = referer;
  11. request.CookieContainer = cookieC;
  12. byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
  13. request.ContentLength = postBytes.Length;
  14. Stream requestStream = request.GetRequestStream();
  15. requestStream.Write(postBytes, 0, postBytes.Length);
  16. requestStream.Close();
  17. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  18. }

Parameters:

Uri – is the url the POST is sent.

Post_data – is the actual data that post will carry

Referrer – is the previous url the post request originated.

cookieC –keeps the cookie the Web Server sends to the browser  to maintain the Session state. This is so that to keep the program logged to your My Go account between login and sending a SMS message.

To make sure the Web Server sends the same HTML code that it sends to the Web Browser, the UserAgent is spoofed to the same as the Web Browser used in this case FireFox 5.

Login Form

  1. <form name="my_go_login" method="post" action="./servlet/authorisation">
  2. <input name="msisdn" class="login-screen" type="textbox">
  3. <input name="password" class="login-screen" type="password">
  4. <input type=hidden name=actionx value="authenticatemain">
  5. <INPUT class="login-button" TYPE="image" src="./images/login_screen/submit_button.jpg">
  6. </form>

Note:  the HTML code was cleared from irrelevant tags for clarity. The tags removed include table for formatting and client side validation on the form data.

From the HTML code at https://www.go.com.mt/mygo/  we investigate the login form.

referrer – https://www.go.com.mt/mygo/

url – https://www.go.com.mt/mygo/ servlet/authorisation

msisdn – mobile number to login with

password – the password for the account

actionx – a hidden input which is always set to the value “authenticatemain”

Send SMS form

  1. <form name="smsform" action="./servlet/groupsms" method="post">
  2. recipients:
  3. <input type="text" name="phone_entries" id="phone_entries"/>
  4. message:
  5. <textarea name="smsInput"></textarea>
  6. <input type="hidden" name="pentries" values=""/>
  7. characters left:
  8. <input readonly name="count" value="420 (0 SMS)">
  9. <input class="transparent" type="button" value="send SMS" onClick="submitsmsform()">
  10. </form>

This form is POSTed to the server by AJAX which requires more time to figure out what is really going on.

  1. //identifies browser being used and then connects to servelet to retrieve data
  2. function TxRxXML(inputText)
  3. {
  4. if(inputText != "" && inputText != "," && inputText != " ")
  5. {
  6. //if IE
  7. if(window.ActiveXObject)
  8. {
  9. request = new ActiveXObject("Microsoft.XMLHTTP");
  10. }
  11. //if other browsers
  12. else if(window.XMLHttpRequest)
  13. {
  14. request = new XMLHttpRequest();
  15. }
  16. //event handler that fires when the state of the page changes
  17. request.onreadystatechange = processRequestChange;
  18. request.open("POST", "./servlet/ajaxwebsms?rand=-4974711596692347436", true );
  19. request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  20. request.send("phone_entries=" + inputText);
  21. }
  22. return false;
  23. }

Development becomes easier with the use of Temper Data which empowers the developer to pause and inspect requests and their content. With some manual SMSes testing the query string was figured out.

url – https://www.go.com.mt/mygo/servlet/groupsms

referrer – https://www.go.com.mt/mygo/main_right.jsp

phone_entries – target mobile number

smsInput – url encoded message

message_template= left blank (not needed unless using the sms template facility)

count – Just a string that holds the number of characters left and in how many SMSes the message need to be split.

int len = 420 – message.Length; (message length is prior url encoding)
if (len > 279) num_of_smses = 1;
else if (len > 147) num_of_smses = 2;
else if (len > 11) num_of_smses = 3;
else if (len > 0) num_of_smses = 4;
count=” + len.ToString() + “+%28″+num_of_smses.ToString()+”+SMS%29&

save_message– save or not the message on the account (on/off)

pentries– target mobile number

So to Login and Send an SMS we get the following:

  1. public static void sendSms(String mobile_Number, String password, String recipient, String message)
  2. {
  3. CookieContainer myCookie = new CookieContainer();
  4. /* login */
  5. String url     = "https://www.go.com.mt/mygo/servlet/authorisation";
  6. String referer = "http://www.go.com.mt/mygo/";
  7. // Create Login Query String
  8. String vars = msisdn="+mobile_Number+"&password="+password+"&actionx=authenticatemain";
  9. // Login
  10. httpsPost(url, vars, referer, myCookie);
  11. /* send sms*/
  12. url = "https://www.go.com.mt/mygo/servlet/groupsms";
  13. referer = "https://www.go.com.mt/mygo/main_right.jsp";
  14. // 420 is the maximum number of characters that can be sent at once
  15. int len = 420 - message.Length;
  16. // apply URL Encoding to the message
  17. message = HttpUtility.UrlEncode(message);
  18. // Calculate the number of SMSes to be sent
  19. int num_of_smses = 1;
  20. if (len > 279) num_of_smses = 1;
  21. else if (len > 147) num_of_smses = 2;
  22. else if (len > 11) num_of_smses = 3;
  23. else if (len > 0) num_of_smses = 4;
  24. else throw new Exception("You have exceeded the limit of 420 Characters");
  25. // Create SMS Query string
  26. vars = "phone_entries=" + recipient + "%2C&smsInput="+message+"&message_template=&count=" + len.ToString() +"+%28"+num_of_smses.ToString()+"+SMS%29&save_message=on&pentries=" + recipient + "%2C";
  27. // Send SMS
  28. httpsPost(url, vars, referer, myCookie);
  29. }

Parameters:

mobile_number – the mobile number representing the account

password – password for the account

recipient – the number of the target mobile phone to receive the SMS

message – the actual SMS message in plain text

To make sure the Web Server sends the same HTML code to the application the UserAgent is set to the same as the Browser used in this case FireFox 5.

Test it

  1. static void Main(string[] args)
  2. {
  3. sendSms("YOUR_NUMBER", "PASSWORD", "NUMBER_TO", "ACTUAL MESSAGE");
  4. }

The code was tested in Visual Studio 2010 in a Console Application the Target Framework was changed to .NET Framework 4 as shown in Fig:3 so as to be able to include the reference to System.Web shown in fig:4.

Change to .net Framework 4
Fig:3
Add System.web reference to visual studio 2010
Fig:4

Make sure the following name spaces are included

  1. using System.Text;
  2. using System.Net;
  3. using System.IO;

Final note

If multiple SMS are to be sent, one could separate login from sending SMS but keep in mind that the session times out after being idle for some time.

What is not included:

Error Handling.

Message Templates.

An explanation of how to send to multiple recipients. This is left for the reader to try out. (probably just separate the numbers with coma)

How to access and retrieve My Go phone book and how to add entries to it programmatically.

Between login and sending an SMS from the website a real web browser sends some GET/POST requests for autocomplete mobile numbers in the phonebook stored in the account. These are skipped entirely.

Does not cater beyond the 8 free daily SMSes that require confirmation from the user to charge the account for the SMS.