XmlSerializable Generic Dictionary

No Comments

I need to use generic dictionary on both JSON and XML serialization.


using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Xml;

namespace Rubik.Staging
{
[XmlSchemaProvider(“GetInternalSchema”)]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
#region IXmlSerializable Members

private const string ns = “http://www.rubik.com.tr/staging”;

public static XmlQualifiedName GetInternalSchema(XmlSchemaSet xs)
{
bool keyIsSimple = (typeof(TKey).IsPrimitive || typeof(TKey) == typeof(string));
bool valueIsSimple = (typeof(TValue).IsPrimitive || typeof(TValue) == typeof(string));

XmlSchemas schemas = new XmlSchemas();

XmlReflectionImporter importer = new XmlReflectionImporter(ns);
importer.IncludeType(typeof(TKey));
importer.IncludeType(typeof(TValue));

XmlTypeMapping keyMapping = importer.ImportTypeMapping(typeof(TKey));
XmlTypeMapping valueMapping = importer.ImportTypeMapping(typeof(TValue));

XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);

if(!keyIsSimple)
exporter.ExportTypeMapping(keyMapping);
if(!valueIsSimple)
exporter.ExportTypeMapping(valueMapping);

XmlSchema schema = (schemas.Count == 0 ? new XmlSchema() : schemas[0]);

schema.TargetNamespace = ns;
XmlSchemaComplexType type = new XmlSchemaComplexType();
type.Name = “DictionaryOf” + keyMapping.XsdTypeName + “And” + valueMapping.XsdTypeName;
XmlSchemaSequence sequence = new XmlSchemaSequence();
XmlSchemaElement item = new XmlSchemaElement();
item.Name = “Item”;

XmlSchemaComplexType itemType = new XmlSchemaComplexType();
XmlSchemaSequence itemSequence = new XmlSchemaSequence();

XmlSchemaElement keyElement = new XmlSchemaElement();

keyElement.Name = “Key”;
keyElement.MaxOccurs = 1;
keyElement.MinOccurs = 1;

XmlSchemaComplexType keyType = new XmlSchemaComplexType();
XmlSchemaSequence keySequence = new XmlSchemaSequence();
XmlSchemaElement keyValueElement = new XmlSchemaElement();
keyValueElement.Name = keyMapping.ElementName;
keyValueElement.SchemaTypeName = new XmlQualifiedName(keyMapping.XsdTypeName, keyMapping.XsdTypeNamespace);
keyValueElement.MinOccurs = 1;
keyValueElement.MaxOccurs = 1;
keySequence.Items.Add(keyValueElement);
keyType.Particle = keySequence;
keyElement.SchemaType = keyType;
itemSequence.Items.Add(keyElement);

XmlSchemaElement valueElement = new XmlSchemaElement();

valueElement.Name = “Value”;
valueElement.MaxOccurs = 1;
valueElement.MinOccurs = 1;

XmlSchemaComplexType valueType = new XmlSchemaComplexType();
XmlSchemaSequence valueSequence = new XmlSchemaSequence();
XmlSchemaElement valueValueElement = new XmlSchemaElement();
valueValueElement.Name = valueMapping.ElementName;
valueValueElement.SchemaTypeName = new XmlQualifiedName(valueMapping.XsdTypeName, valueMapping.XsdTypeNamespace);
valueValueElement.MinOccurs = 1;
valueValueElement.MaxOccurs = 1;
valueSequence.Items.Add(valueValueElement);
valueType.Particle = valueSequence;
valueElement.SchemaType = valueType;
itemSequence.Items.Add(valueElement);
itemType.Particle = itemSequence;
item.SchemaType = itemType;
sequence.Items.Add(item);
type.Particle = sequence;
schema.Items.Add(type);

xs.XmlResolver = new XmlUrlResolver();
xs.Add(schema);

return new XmlQualifiedName(type.Name, ns);
}

public void ReadXml(System.Xml.XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

bool wasEmpty = reader.IsEmptyElement;
reader.Read();

if (wasEmpty)
return;

while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
reader.ReadStartElement(“Item”);

reader.ReadStartElement(“Key”);
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();

reader.ReadStartElement(“Value”);
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();

this.Add(key, value);

reader.ReadEndElement();

reader.MoveToContent();
}

reader.ReadEndElement();
}

public void WriteXml(System.Xml.XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

foreach (TKey key in this.Keys)
{
writer.WriteStartElement(“Item”);

writer.WriteStartElement(“Key”);
keySerializer.Serialize(writer, key);
writer.WriteEndElement();

writer.WriteStartElement(“Value”);
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();

writer.WriteEndElement();
}
}

#endregion

#region IXmlSerializable Members

public XmlSchema GetSchema()
{
return null;
}

#endregion
}

}

Categories: Development Tags: Etiketler:, , , ,

Integrating svn with trac on windows.

No Comments

After many misleads, i put many different files into work.
Here is the post-commit solution to integration on windows.
I suggest that add svn bin and python paths to enviroment.

post-commit.bat

%~dp0\post-commit-hook.cmd %1 %2

post-commit-hook.cmd

@ECHO OFF
::
:: Trac post-commit-hook script for Windows
::
:: Contributed by markus, modified by cboos.
:: Usage:
::
:: 1) Insert the following line in your post-commit.bat script
::
:: call %~dp0\trac-post-commit-hook.cmd %1 %2
::
:: 2) Check the ‘Modify paths’ section below, be sure to set at least TRAC_ENV

:: ———————————————————-
:: Modify paths here:

:: — this one must be set
SET TRAC_ENV=c:\urtracsite

:: — set if Python is not in the system path
SET PYTHON_PATH=C:\urpythonpath

:: — set to the folder containing trac/ if installed in a non-standard location
SET TRAC_PATH=C:\urtrachome
:: ———————————————————-

:: Do not execute hook if trac environment does not exist
IF NOT EXIST %TRAC_ENV% GOTO :EOF

set PATH=%PYTHON_PATH%;%PATH%
set PYTHONPATH=%TRAC_PATH%;%PYTHONPATH%

SET REV=%2

:: GET THE AUTHOR AND THE LOG MESSAGE
for /F %%A in (‘svnlook author -r %REV% %1’) do set AUTHOR=%%A
for /F “delims==” %%B in (‘svnlook log -r %REV% %1’) do set LOG=%%B

:: CALL THE PYTHON SCRIPT
Python “%~dp0\post-commit-hook.py” -p “%TRAC_ENV%” -r “%REV%” -u “%AUTHOR%” -m “%LOG%”

post-commit-hook.py

#!/usr/bin/env python
# trac-post-commit-hook
# —————————————————————————-
# Copyright (c) 2004 Stephen Hansen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# —————————————————————————-

# This Subversion post-commit hook script is meant to interface to the
# Trac (http://www.edgewall.com/products/trac/) issue tracking/wiki/etc
# system.
#
# It should be called from the ‘post-commit’ script in Subversion, such as
# via:
#
# REPOS=”$1″
# REV=”$2″
# LOG=`/usr/bin/svnlook log -r $REV $REPOS`
# AUTHOR=`/usr/bin/svnlook author -r $REV $REPOS`
# TRAC_ENV=’/somewhere/trac/project/’
# TRAC_URL=’http://trac.mysite.com/project/’
#
# /usr/bin/python /usr/local/src/trac/contrib/trac-post-commit-hook \
# -p “$TRAC_ENV” \
# -r “$REV” \
# -u “$AUTHOR” \
# -m “$LOG” \
# -s “$TRAC_URL”
#
# It searches commit messages for text in the form of:
# command #1
# command #1, #2
# command #1 & #2
# command #1 and #2
#
# You can have more then one command in a message. The following commands
# are supported. There is more then one spelling for each command, to make
# this as user-friendly as possible.
#
# closes, fixes
# The specified issue numbers are closed with the contents of this
# commit message being added to it.
# references, refs, addresses, re
# The specified issue numbers are left in their current status, but
# the contents of this commit message are added to their notes.
#
# A fairly complicated example of what you can do is with a commit message
# of:
#
# Changed blah and foo to do this or that. Fixes #10 and #12, and refs #12.
#
# This will close #10 and #12, and add a note to #12.

import re
import os
import sys
from datetime import datetime

from trac.env import open_environment
from trac.ticket.notification import TicketNotifyEmail
from trac.ticket import Ticket
from trac.ticket.web_ui import TicketModule
# TODO: move grouped_changelog_entries to model.py
from trac.util.text import to_unicode
from trac.util.datefmt import utc

try:
from optparse import OptionParser
except ImportError:
try:
from optik import OptionParser
except ImportError:
raise ImportError, ‘Requires Python 2.3 or the Optik option parsing library.’

parser = OptionParser()
parser.add_option(‘-e’, ‘–require-envelope’, dest=’env’, default=”,
help=’Require commands to be enclosed in an envelope. If -e[], ‘
‘then commands must be in the form of [closes #4]. Must ‘
‘be two characters.’)
parser.add_option(‘-p’, ‘–project’, dest=’project’,
help=’Path to the Trac project.’)
parser.add_option(‘-r’, ‘–revision’, dest=’rev’,
help=’Repository revision number.’)
parser.add_option(‘-u’, ‘–user’, dest=’user’,
help=’The user who is responsible for this action’)
parser.add_option(‘-m’, ‘–msg’, dest=’msg’,
help=’The log message to search.’)
parser.add_option(‘-c’, ‘–encoding’, dest=’encoding’,
help=’The encoding used by the log message.’)
parser.add_option(‘-s’, ‘–siteurl’, dest=’url’,
help='(deprecated) the base_url from trac.ini will ‘
‘always be used.’)

(options, args) = parser.parse_args(sys.argv[1:])

if options.env:
leftEnv = ‘\\’ + options.env[0]
rghtEnv = ‘\\’ + options.env[1]
else:
leftEnv = ”
rghtEnv = ”

commandPattern = re.compile(leftEnv + r'(?P[A-Za-z]*).?(?P#[0-9]+(?:(?:[, &]*|[ ]?and[ ]?)#[0-9]+)*)’ + rghtEnv)
ticketPattern = re.compile(r’#([0-9]*)’)

class CommitHook:
_supported_cmds = {‘close’: ‘_cmdClose’,
‘closed’: ‘_cmdClose’,
‘closes’: ‘_cmdClose’,
‘fix’: ‘_cmdClose’,
‘fixed’: ‘_cmdClose’,
‘fixes’: ‘_cmdClose’,
‘addresses’: ‘_cmdRefs’,
‘re’: ‘_cmdRefs’,
‘references’: ‘_cmdRefs’,
‘refs’: ‘_cmdRefs’,
‘see’: ‘_cmdRefs’}

def __init__(self, project=options.project, author=options.user,
rev=options.rev, msg=options.msg, url=options.url,
encoding=options.encoding):
msg = to_unicode(msg, encoding)
self.author = author
self.rev = rev
self.msg = “(In [%s]) %s” % (rev, msg)
self.now = datetime.now(utc)
self.env = open_environment(project)

cmdGroups = commandPattern.findall(msg)

tickets = {}
for cmd, tkts in cmdGroups:
funcname = CommitHook._supported_cmds.get(cmd.lower(), ”)
if funcname:
for tkt_id in ticketPattern.findall(tkts):
func = getattr(self, funcname)
tickets.setdefault(tkt_id, []).append(func)

for tkt_id, cmds in tickets.iteritems():
try:
db = self.env.get_db_cnx()

ticket = Ticket(self.env, int(tkt_id), db)
for cmd in cmds:
cmd(ticket)

# determine sequence number…
cnum = 0
tm = TicketModule(self.env)
for change in tm.grouped_changelog_entries(ticket, db):
if change[‘permanent’]:
cnum += 1

ticket.save_changes(self.author, self.msg, self.now, db, cnum+1)
db.commit()

tn = TicketNotifyEmail(self.env)
tn.notify(ticket, newticket=0, modtime=self.now)
except Exception, e:
# import traceback
# traceback.print_exc(file=sys.stderr)
print>>sys.stderr, ‘Unexpected error while processing ticket ‘ \
‘ID %s: %s’ % (tkt_id, e)

def _cmdClose(self, ticket):
ticket[‘status’] = ‘closed’
ticket[‘resolution’] = ‘fixed’

def _cmdRefs(self, ticket):
pass

if __name__ == “__main__”:
if len(sys.argv) < 5:
print “For usage: %s –help” % (sys.argv[0])
else:
CommitHook()

Categories: Development Tags: Etiketler:, ,

CUDA EmuDebug problem (cudaError_enum)

No Comments

If you are willing to debug cuda code u may have 2 options one is nexus which requires 2 GPU Enabled cards for local debugging and the other ugly way EMUDEBUG Configuration but there is a tricky problem. Altough your code works perfect for standart Debug on GPU, when u switch to EMUDEBUG suprise u have Microsoft C++ exception: cudaError_enum So do not forget to change the library cudart.lib to cudartemu.lib.
cudartemu

Categories: Development Tags: Etiketler:,

Cuda hash

No Comments

At last i can manage to write some code and finished the very first step of a project about cuda and sha-3 candidates.
If you’re interested, please have a look at trac home.
Currently our crew is one guru Gökay Saldamli and insignificant me. But i believe the future is CUDA and this project can be a good base for new hashing algorithms.
Especially for file systems or fast comparison of huge files.

Categories: Development Tags: Etiketler:, , ,

Röyksopp @ İstanbul – Türkiye

No Comments

Watching royksopp alive is one my wishes and this year many of my wishes granted.

I missed their concert in Tokyo  and was really sorry for it. But they suprised me by showing up in EFES ONE LOVE FEST.
Sound system was awfull and people were rude. But their performance had to be seen. And thank you very much for the people who did not let them to finish. GREAT BIS.

Watch these little cell phone videos.

PS: Please use forward for next one

Categories: Music Tags: Etiketler:,

CUDA and Intellisense

No Comments

CUDA SDK helps developers to use GPU computing power to c developers. You may find help in SDK about code coloring in Visual Studio. But i am sure many of you have been searching for intellisense for cu and cuh as c files. Here is my solution.

Add c and cuh extensions to NCB Default C/C++ Extensions key under
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Languages\Language Services\C/C++ path

Categories: Development Tags: Etiketler:,

The Sky Crawlers

No Comments
The Sky Crawlers is the new animated feature film by Mamoru Oshii, the world-famous Japanese filmmaker, whose works include Ghost in the Shell (1995) and Innocence (2004). The film was nominated for the Golden Lion at the 65th Venice Film Festival, and was greeted with three awards at Sitges 2008.
The Sky Crawlers is based on a popular six-part novel by a best-selling writer, MORI Hiroshi. The novel has sold more than 900,000 copies in Japan alone. The story unfolds in another possible ‘now.’ The main characters are youngsters called “Kildren”, who are destined to live eternally in their adolescence, and fight a “war as a show” organized and operated by adults.

My humble opinion is this masterpiece must to be watched. 3D scenes are far beyond Hollywood productions.

 Sky Crawlers
War has never completely vanished in any age.To humans, the sense of reality it imparts has always been essential. The feeling that, in this era, at this very moment, someone somewhere is fighting, is a critical element to human society. And it absolutely cannot be faked. To show what war is truly like, the legends in history textbooks alone are not enough. Having humans who will actually die, reporting on them, showing the world their wretchedness, all that is necessary to preserve peace. Otherwise, the world will lose its grasp of the very meaning of “peace”,j ust like we have, who must kill in the sky to feel that we are truly alive. And since the game involves us fighting a never-ending war, certain rules become necessary. For example, the existence of an undefeatable enemy.
Categories: Anime Tags: Etiketler:,

Røyksopp – Junior

No Comments
Røyksopp - Junior

Røyksopp - Junior

For me their music can be described as classical music out of electronic musical instruments. They are the virtuoso. After their success with oddly sounded girl in “what else is there” , this album has a lot of vocals. My favorite is (Anneli Drecker); You don’t have a clue.
Also duo wrote very interesting lyrics.

The Girl and The Robot

I go mental every time you leave for work
You never seem to know when to stop
I never know when you’ll return
I’m in love with a robot

In the night, call you up and
Wanna know when you’re coming home
don’t deny me, call me back
I’m so alone

In the night, wait up for you
Even though you don’t want me to
Go to bed, leave the lights on
what’s the use

So you want to understand me
You just see what you want to see
there’s no way I can help you out
You don’t know what it’s all about

Fell asleep again in front of MTV
God, I’m down at the bottom
No one’s singing songs for me
I can’t wait for tomorrow

When you’re gone and rain starts falling
I just sit here by the phone
don’t deny me, call me back
I’m so alone

Oh, when you gonna come home?
Oooooh I just gotta know
When you gonna come home?
Oh

Baby I can’t stand it when you go to work
You never seem to know when to stop
I never know when you’ll return
I’m in love with a robot

Featuring: Robyn

Categories: Music Tags: Etiketler:,

File Manager For TinyMCE

I really hate when a open source project (TinyMCE) relies on a commercial product  (MCFileManager) to work. After some hard work here is a file manager for all. Download here . Requires Microsoft .NET Framework 3.5 (Update Panel used.). Turkish language support is added.
Do not forget to add “filemanager” into plugins line and file_browser_path setting in tinyMCE.init() function.

tinyMCE.init({
// General options
mode: "exact",
...
plugins: "safari...,filemanager",
...
file_browser_path:"http://www.urhost.com/uploadfolder/"
...

Categories: Development Tags: Etiketler:, ,

PUNISHER: WAR ZONE

No Comments
Punisher: War Zone

Punisher: War Zone


Marvel is making many films out of its huge comic heroes, but many of them is so childish.

They wear underwear over their thights

But as we all know PUNISHER is a rock solid brutal who crushes enemies skulls. And same goes for the movie. All the fight scenes are very authentic but i suggest you to watch out the first one, cause he gave a head hit by jumping across a table. I am sure the movie will be criticized as a blood bath although it has the same subject “Some one must take responsibility to make hard decisions” with BATMAN : DARK KNIGHT.

Categories: Movies Tags: Etiketler:,