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

Resizing a Fixed Virtual Machine VHD (VirtualBox)

Resizing a Fixed disk

Resizing can only be done on dynamically allocated disks. So one must first convert the disk to dynamic then resize.

In reality there is no way to change between Fixed-size and dynamic disks. However one may clone the existing Virtual Machine form one format to the other. This works with VHD (Virtual Hard Disk) format

The tool one needs for the said conversion and resizing is VBoxManage.exe and this can be found in:

C:\Program Files\Oracle\VirtualBox

Dynamic to fixed Cloning

VBoxManage clonehd [Current_VHD] [New-VHD] –variant Fixed

 

Fixed to Dynamic Cloning

VBoxManage clonehd [Current_VHD] [New-VHD] –variant Standard

 

Resizing

VBoxManage modifyhd [New-VHD] –resize [megabytes]

 

Note that resizing only works with increasing the size

1

Open a Command Prompt near the VHD (using Shift + Right Click)

2

C:\Program Files\Oracle\VirtualBox\VBoxManage clonehd Win7.vhd Win7D.vhd –variant Standard

3

And wait for it to finish.

4

“C:\Program Files\Oracle\VirtualBox\VboxManage” modifyhd Win7D.vhd –resize 40000

5

 

Importing the new Virtual Machine

6

7

8

9

Locate the new VM and Create and Power it up

10

The VM will still show the old size

11 12 13 14 15 16 17 18

That’s everything that is required

 

Basic AngularJS (1.3.13) SPA

Being on the saga to master AngularJS I decided to post about a basic application with a  module and controller that returns static data to the view. The view and controller are married by routing. This post will not go in detail on how things work.

index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="app">
<head>
    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular-route.min.js"></script>
    <script src="app.module.js"></script>
    <script src="app.config.js"></script>
    <script src="posts.module.js"></script>
    <script src="postsController.js"></script>
<body>
    <div>
      <div data-ng-view></div>
    </div>
</body>
</html>

line 2 defines data-ng-app=”app” which is an attribute Every angular application should have  (could live in other elements)

Line 8-11 are the JavaScript inclusion for the application (in a real website one would minify and merge the files together for faster loading)

Line 14 is where the view will be loaded     <div data-ng-view></div>

AngularJS is modular in such a way that one could separate functionality but one or more modules can be injected into another module for richer functionality.

app.module.js

(function () {
    'use strict';
    
    angular.module("app", [
        'ngRoute',
        'app.posts'
    ]);
   
})();

The main module’s name should match the data-ng-app=”app” as above

ngRoute and app.posts are injected modules that the app module will make use of.

ngRoute is a standard module that takes care of routing

app.posts is a custom module that is built for this application

app.config,js

(function(){
  'use strict';
  
    angular.module("app").config(['$routeProvider',
      function ($routeProvider) {
        $routeProvider
            .when('/', {
		  controller: 'postsController',
		  controllerAs: 'vm',
                  templateUrl: 'posts.html'
            })
            .otherwise({
                redirectTo:"/"
            });
     }
    ]);
});

Every module may have a configuration and this is the first thing that will execute from that module for initialization.  In this case the main module has routing initialized.

$routeProvider is where routing is setup.

in a nut shell the above is configuring that when visiting root ‘/’ use controller postsController with vm alias and use posts.html as a view template else redirect to root.

posts.module.js

(function () {
    'use strict';

    angular.module('app.posts', []);
    
})();

This is just the definition of posts module which has no dependencies. As one may notice it is almost the same as app.module.js

postsController.js

(function () {
    'use strict';

  // Register
  angular
        .module('app.posts')
        .controller('postsController',postsController);
        
 // Inject
 postsController.$inject = [];        

  // Function
 function postsController() {
    var vm = this;
    vm.persons = [
                   {
                      "Name":"Alfreds Futterkiste",
                      "City":"Berlin",
                      "Country":"Germany"
                   },
                   {
                      "Name":"Berglunds snabbkkp",
                      "City":"Luleb",
                      "Country":"Sweden"
                   }
                 ];
  }

})();

Controllers can be written in different ways but the most elegant (opinionated) is Register/Inject/Function

Register the controller with a function name

Inject parameters

Function is the controller’s logic. The variable vm stands for ViewModel because that’s exactly what it represents. and Some JSON data is set to a property in that view model.

posts.html

<ol>
    <li data-ng-repeat="person in vm.persons">
      {{ person.Name + ', ' + person.Country }} <br/>
    </li>
</ol>

This is the view template that will be loaded instead of <div data-ng-view></div>

data-ng-repeat means repeat this element for as much items in the list

The vm here is the alias that was defined in the routing and has nothing to do with the controller vm variable ( but for logical sense it is the same )

{{}} mean execute the expression in between which in this case are the Name and Country

 

here is the code

Same example but using $http request here

Best Practices learned so far

Always encapsulate your code as a module to avoid polluting the global namespace

Always use ‘use strict’;

Use employ single responsibility principle

Separate every thing in files and make sure you organize files by feature if the application is large

Code neatly and use indentation

Love the community: When posting on the internet about code always include a version number

Experts worth following

John Papa

Tod Motto 

Resources

Very good introduction by Dan Wahlin : https://www.youtube.com/watch?v=i9MHigUZKEM

www.angular-tips.com

www.scotch.io

www.egghead.io

https://angularjs.org/

https://www.ng-book.com/

Configuring IIS and Setting up Thinktecture v2 Identity Server

As the title indicate, this post is about installing IIS and Configuring ThinkTecture v2 up and running.

Run appwiz.cpl

Search and run app.wiz.cpl

Select IIS and required features

 

click “Turn windows features on or off” (1)

Tick  “IIS Management Console” (2)

Tick ASP.NET 4.5 (3)

 

It is of utmost importance that ASP.NET 4.5 is ticked else when one would attempt to navigate to thinktecture v2 the following HTTP Error 500.19 will pop up.

HTTP Error 500.19

3Wait for features to be found and installed.

 

4

 

click close

IISNavigate to Localhost

IIS is up and running. Next is Downloading ThinkTecture V2 configuring IIS  to serve ThinkTecture V2

ThinkTecture V2 Release

Visit https://github.com/IdentityServer/IdentityServer2/releases and download ThinkTecture V2

Follow along this video and everything should be fine https://vimeo.com/51088126ThinkTecture V2 Initial Landing Page

https://vimeo.com/51666380

Importing Excel 2013 Data into SharePoint 2013

Importing Excel Data into SharePoint 2013

Open your Excel file

Exporting Excel 2013 Data to SharePoint 2013
Exporting Excel 2013 Data to SharePoint 2013

Click the Insert tab (1), select your data (2), click table (3) and click Ok (3)

 

Click anywhere inside the table (if the previous step as performed correctly a Design tab appears)

 

Exporting Excel 2013 Data to SharePoint 2013
Exporting Excel 2013 Data to SharePoint 2013

Click “Design” tab (1)

Click “Export” (2)

Click “Export table to SharePoint List” (3)

Enter Address URL Path of the site you wish to Import the Excel Data to (4)

This turns SharePoint as a source of data for the table to be exported (5) (The benefit of the Link is demonstrated after the export is completed)

Enter the preferred List name (6)

Enter Description (7)

Click Next

Click Finished

 

4

This means the data has been published to SharePoint List.

SharePoint Exported List
SharePoint Exported List

That’s it the Excel data is exported to SharePoinT

 

Benefit of “Create a read-only connection to the new SharePoint List”

Click “new item”

Add an Item to the List
Add an Item to the List

Fill out the Form and click Save

Refresh Excel Data
Refresh Excel Data

Right click on the table and click “Refresh” on the context menu

Updated Excel List
Updated Excel List

The latest data is visible in the Excel sheet.

ASP.NET Identity with Facebook (out of the box)

The following is a walk through of how to deal with authentication using Identity Providers mainly Facebook.

Open https://developers.facebook.com/

Add a New App
Add a New App

Click “Add a New App”

 

Add a New App
Add a New App

Click “WWW”

Create New Facebook App ID
Create New Facebook App ID

Click “Create New Facebook App ID”

Create New app ID/Details
Create New app ID/Details

Select Category and click “Create App ID”

Go to Visual studio 2013

New VS2013 Project
New VS2013 Project

Create new Project name it and select “ASP.NET Web application”

New VS2013 Project Selection
New VS2013 Project Selection

Set  Authentication to “Individual User Accounts” and Click Ok

Build and run your project and copy the local URL go to Facebook Development in your browser where you left off

Website URL
Website URL

Paste the url in “Site URL” and “Mobile site URL” in this case localhost:61617 and click next

 

Application DashBoard
Application DashBoard

Refresh the page click Show button near App Secret

 

Authentication
Authentication

Enter your Facebook Password

Go to visual studio

Startup Authentication
Startup Authentication

Navigate in solution explorer to App_start/start.auth.cs

Facebook App ID and App Secret
Facebook App ID and App Secret

Scroll down Facebook boilerplate authentication code. Paste App Id and App Secret and uncomment the three lines

Rebuild the Project and run

Log In
Log In

Once it opens in the browser click Login

Facebook Login
Facebook Login

On the left of the page there should be a Facebook button click it

Application Authorization
Application Authorization

Click okay to authorize

Associate E-mail address with account
Associate E-mail address with account

Enter E-mail address to associate with that Facebook account on your application

Display E-mail after authentication
Display E-mail after authentication

The e-mail will show every time the user is logged in.

That is how to authenticate a user using Facebook as an Identity Provider. Out of the box.

 

What’s else can we do with Facebook?

There a lot of things one can do with Facebook by using Facebook SDK the user can authorize your Web Site to access several Scopes. At the least one could skip the last two steps by requesting access to the e-mail and use that programmatically without the user having to type it.

The following is how to incorporate Facebook SDK in your project.

NuGet Manager
NuGet Manager
Facebook SDK
Facebook SDK

More info at http://www.nuget.org/packages/Facebook/7.0.5-beta

and https://developers.facebook.com/docs/graph-api

The guideline is do not ask for more data than your application really need, because once you lose trust of the users, your web site is dead.

 

SharePoint Workflow Designer 2013 not displaying workflows

Today I encountered a strange anomaly in SharePoint Designer 2013.

I pushed a fresh Windows 8.1 image and installed Visual studio 2013 Premium Update 2 (couldnt go for update 4 due to informix driver). I installed sharePoint Designer 2013 and wanted to use it to resume on a workflow. When I loaded it, to my dismay SharePoint Designer displayed an empty workflow ready to start designing … I thought I lost my work. I started looking for a solution and I encountered this post http://community.office365.com/en-us/f/154/t/264867.aspx

To cut story short they ask the user to install this SharePoint Designer update http://www.microsoft.com/en-us/download/details.aspx?id=41467

I did so and it worked. So why things worked before the refresh of the image? My conclusion is because before i had Visual studio 2013 Premium Update 4, So I think something required by SharePoint Designer 2013 is missing in Update 2 but available in Update 4

SharePoint Link to a document in Library

Setting the Library for Links

Open the library

Library ToolBar
Library ToolBar

Click the Library Tab (1) then click Library Settings (2)

Library Settings Page
Library Settings Page

click Advanced Settings

Enable Content Types
Enable Content Types

Tick Yes

Add from existing site content types
Add from existing site content types

click Add from existing site content types

Link to a document Content Type Selection
Link to a document Content Type Selection

Select Document content types from (1) and Link to a document from (2)

 

Adding Link to a Document Content Type
Adding Link to a Document Content Type

Click Add

 

Populate the Library

Library Content Types
Library Content Types
Adding a Document
Adding a Document

Click New (1) followed by Link to a document (2)

Providing Name, document Link and Verify Link Validity
Providing Name, document Link and Verify Link Validity

Enter a document Name and a Link (please click “Click here to test” checks if your URL is valid)

 

Link in Library
Link in Library

Done!

 

Note that if you do this to Documents Library of a site/subsite and after you create a child subsite, this will not effect the default Documents Library of that child subsite