יום שני, 18 במרץ 2013

Count from to step

Ruby

class CountFromTo  
def initialize ( pFrom , pTo , pStep )
@mFrom = pFrom
@To = pTo
@mStep = pStep
end

def CountNow
while @mFrom < @To do

@mFrom = @mFrom + @mStep

yield @mFrom
end
end
end

theCls = CountFromTo.new 3 , 50 , 5

theCls.CountNow {|i| puts "The i #{i}" }

Python


class CounterFromTo:
def __init__ (self , pFrom , pTo , pStep):
self.pFrom = pFrom
self.mTo = pTo
self.mStep = pStep
def __iter__ (self):
return self
def next (self ):
if self.current > self.high:
raise StopIteration

valueToRet = self.mFrom
self.mFrom += self.mStep
return valueToRet


for nextI in CounterFromTo ( 3 , 40 , 4 ):
print ( nextI)
and 
def CounterFromTo ( pFrom , pTo , pStep):  
current = pFrom
while current <= pTo:
yield current
current += pStep

for nextI in CounterFromTo ( 3 , 40 , 4 ):
print ( nextI)


and 
gen = (n for n in xrange(0,11))






יום ראשון, 10 במרץ 2013

10-03-2013 spring integration

GateWay

//Declare the gatway interface  

public interface ImyClient {
public Data processData (Data pData);
}

//Add gateway configuration :
<int:gateway id="myGateway"
default-request-channel="data-in-channel"
default-reply-channel="data-out-channel"
service-interface="com.mazalsadon.eilat.endpoints.gateway.ImyClient" />

//Test our code

public GatewayEndpointTest() {
ctx = new ClassPathXmlApplicationContext("endpoints-gateway-beans.xml");
// obtain our service interface
tradeGateway = ctx.getBean("myGateway",ImyClient .class);
}
public void publishTrade(Trade t) {
// call the method to publish the trade!
Trade it = tradeGateway.processTrade(t);
System.out.println("Trade Message published (Reply)."+it.getStatus());
}

public static void main(String[] args) {
GatewayEndpointTest test = new GatewayEndpointTest();
Trade t = new Trade();
test.publishTrade(t);
}
}

The spring activator


<int:service-activator
input-channel="data-in-channel"
output-channel="data-out-channel"
ref="dataProcessor"
method="receiveData" >
</int:service-activator>
<bean id="tradeProcessor"
class="com.mazalsadon.eilat.endpoints.gateway.TradeProcessor" />
The DataProcessor is a simple class that is invoked by the Activator endpoint when amessage arrives at the data-in-channel. It then processes the Trade and sends a reply
(via the return value):
public class TradeProcessor {
public Data receiveData(Data t) {
System.out.println("Received the Data via Gateway:"+t);
t.setStatus("PROCESSED");
return t;
}
}



 


10-3-2013 wcf

 we need that the server should know which client has send the message to it.

 

Client Side

 
using (OperationContextScope scope = new OperationContextScope((IContextChannel)channel))
{
    MessageHeader<string> header = new MessageHeader<string>("secret message");
    var untyped = header.GetUntypedHeader("Identity", "http://www.my-website.com");
    OperationContext.Current.OutgoingMessageHeaders.Add(untyped);
 
    // now make the WCF call within this using block
}
 

server-side:

 
MessageHeaders headers = OperationContext.Current.IncomingMessageHeaders;
string identity = headers.GetHeader<string>("Identity", "http://www.my-website.com");

10-03-2013 python

Decorator simple sample 
def myDecorator4 (funcToDecorate):
def theReturnFunct (pVal):
funcToDecorate(pVal)
print ("And the next Call please ")
funcToDecorate(pVal + 6 )
print ("finished")
return theReturnFunct

@myDecorator4
def myFunct164 (pVal):
print ("This is my test: " + str( pVal))

myFunct164 (6)

10-03-2013 Camel

Creating routes in Java

RoutesBuilders Interface

void addRoutesToCamelContext(CamelContext context)
throws Exception



from returns RouteDefinitionObject


DSL – Domain Specific language


TypeConvertor

// add our own type converter manually that converts from String -> MyOrder using MyOrderTypeConverter
context.getTypeConverterRegistry().addTypeConverter(MyOrder.class, String.class, new MyOrderTypeConverter());

// add our own type converter manually that converts from String -> MyOrder using MyOrderTypeConverter
context.getTypeConverterRegistry().addTypeConverter(MyOrder.class, String.class, new MyOrderTypeConverter());
MyOrder order = context.getTypeConverter().convertTo(MyOrder.class, "123");

adding a processor


from(ftp://myftpsite.com/friends?username=MazalShadon&password=123456).
process(new Processor() {
public void process(Exchange exchange) throws Exception {
System.out.println("Comming from ftp: "
+ exchange.getIn().getHeader("CamelFileName"));
}
}).
to("jms:myFriends");

יום שבת, 9 במרץ 2013

LDD The release method

(int scull_release(struct inode *inode, struct file *filp
{
return 0;
}
flush method is called before the release is called 

Memory allocation in the device drive


use the kmalloc and the kfree


cp /dev/zero /dev/myDevice


starch myDevice


Capture


 


יום חמישי, 7 במרץ 2013

07-03-2013

MDX

image001http://www.sqlservercentral.com/articles/MDX/95065/

 

QT

QEventLoop,

QObject

StartTimer

QMetaObject

image001 (1)

PHP

$this->usedate = date ('y-m-d h:i:s)j
$t = strtotime ($this->usedate)
vardump

Regex


capturing groups and back references


/(text1) (text2) /$2 $ 1/ –> text2 text1


ActiveMQ


multicast


transport connector


network  connector


zerocons protocol alternative to multicast udp


Bash


set – o noclobber


מונע דריסה של קבצים על ידי כתיבה של הstdout  אליהם


 


 


 


יום רביעי, 6 במרץ 2013

06-03-2013

c++

tuple <int,int> getDimensions ()
{
return make_tuple (1,2);
}

int w , h ;

tee (w,h) = getDimensions()

forword_as_tuple

SQL_SERVER


check constraint violation 547


non repeatable read


set XACT_ABORT


האם להרוג את הטרנזקציה גם על שגיאה קלה

@@Error 
XACT_STATE commit המצב של הטרנזקציה האם היא ניתנת ל 
Save Transaction here 
Rollback Transaction here
https://www.simple-talk.com/sql/t-sql-programming/handling-constraint-violations-and-errors-in-sql-server/
 

Hadoop


Input format


abstract class FileInputFormat


expend it TextInputFormat

























InputFormat:Description:Key:Value:
TextInputFormatDefault format; reads lines of text filesThe byte offset of the lineThe line contents
KeyValueInputFormatParses lines into key, val pairsEverything up to the first tab characterThe remainder of the line
SequenceFileInputFormatA Hadoop-specific high-performance binary formatuser-defineduser-defined


InputFormats provided by MapReduce


input split –> break the data into task if 64 Bit 


JopConfig object


Camel


CamelContext context = new DefaultCamelContext ();


eip –> enterprise integration pattern


jms:queue:IncomingOrders


ActiveMqComponent based on jmsComponent


pool connection factory


Neo4j


GraphDatabaseFactory().NewEmbededDataBase ()


loadPropertiesFromFile (neo4j.properties )


Embedded Linux


Enable Disable BlockLayer


The kernel command line –> from configuration


slab cache



kmem_cache_create allocate free destroy


memory pools


mempool create


setup macro – deprecated


python


slicing


from collections import Sequence

class MyList(Sequence):
def __init__(self, *items):
self.data = list(items)

def __len__(self):
return len(self.data)

def __getitem__(self, slice):
return self.data[slice]

s = MyList(1,2,3)
# lots of free methods
print s[1:2], len(s), bool(s), s.count(3), s.index(2), iter(s)



Ruby


def thing.greet(greeting, *names)
names.each do |name|
puts "#{greeting}, #{name}!"
end
end

>> thing.greet("Hello", "Alice", "Bob", "Charlie")
Hello, Alice!
Hello, Bob!
Hello, Charlie!



Java Script


prototype


 


 


 


 


 

 

יום שלישי, 5 במרץ 2013

05-03-2013

DX

multi threaded rendering

Linux

pool method against select method

Thread groups

tgid – pid of the first lightweight process in a thread group

Linux process descriptor

process descriptor handling

thread_info structure

kernel mode process stack

Stack

     esp decrement along the stack growing

thread_info structure <- -> process descriptor

allocate_thread_info

contrianer_of (pointer ,container_type ,container_field ) used to get in open file method the container that points to the inode cdev member

gdk+

gdkBin thebase class for the gdk+ controls

GdkWidget 

Cxf

Service: Endpoint.Publish (address, theServiceObject )

Client

Service –> <wsdl:service>

myService.getPort () return the SEI proxy

NIO

Files.CreateSymbolicLink

readSymbolicLink

JMS

Implements MessageDrivenBean , MessageListener

JNDI

string Names

Composite Names

maven

mvn archetype : generator

plugin –> goals

Swing

paintComponent (Graphics g) {
super.paintComponent (g);
model.draw (g);

JFrame , keyListener 

graphicks2D 

Windows appstore apps


Windows.UI.Xaml


await async


  private void Button_Click_1(object sender, RoutedEventArgs e)
{
var theTask = AccessTheWebAsync();

Debug.WriteLine("print when the methods go into await ");

}

async Task<String> AccessTheWebAsync()
{

string urlContents = await Task.Run(() =>
{
Thread.Sleep(6500);
return "new Task<string>()";
});

myBtn.Content = "Change Content in UI thread";

// The return statement specifies an integer result.
// Any methods that are awaiting AccessTheWebAsync retrieve the length value.
return "this return the task";
}

SISS


foreach loop container


Data flow task


execute sql task


File system task




יום ראשון, 3 במרץ 2013

03-03-2013

Camel

Component – Create endpoints based on the URI

file –> FileComponent –> FileEndpoints

EndPoint  - edge of a channel send and receive messages from and to the channel . creates producer consumer and exchange messages .

producer – Create and send messages to the endpoint

consumer –. Receive messages from the producer

Event driven consumer – async

Polling consumer – sync

Neo4j

graphdb.getNodeByID

Node.CreateRelationShipTo

Traversal.Descriptor.evaluator (new Evaluator ){

@override
public Evaluation evaluate (Path)



 


Redis


redis.multi do  -> Begin Transaction 


end


ZREVRANGE key start stop

Return the range of elements from the sorted set

Mget (*Keys ) –> return the values of all the specified keys

 


MongoDB


Try to fetch data in a single query  .

 

Embedded Linux 


make xconfig

$cp.config.old.config

physical address

bus address

virtual address  

address translation macros


virt_to_phys


Translation look aside buffers –> tlb


kmalloc , kfree


start_kernel main.c


setup_arch


setup_processor


Microsoft surface


TagVisualizer


 


 


 


 


 


 



יום שבת, 2 במרץ 2013

DDD and control systems part 2

כאשר אני צריך entity כאן ועכשיו בתוך שיכבת ה Domain אני ניגש ל Entity Repository על מנת לבקש אותו .

כלומר כאשר ה Service שמטפל בהחזרה של ה שואב האבק הרובוטי לתחנת העגינה צריך את הEntity של תחנת העגינה או את הentity של השואב האבק הרובוטי הוא ניגש לEntityRepository על מנת לבקש את reference לobject שלהם .

ראיתי מספר גישות למימוש ה Entity Repository :

לייצר עבור כל סוג של Entity את ה EntityRepository משל עצמו .כאשר החיסרון של גישה זו הינה שיכולים להיווצר הרבה מאוד class ים של entities repositories כאשר לכל אחד תפקיד מצומצם מאוד של להחזיק referance לEntity .

Capture4

לייצר Entity repository אחד מרכזי עבור כל ה Entities כאשר כאן החיסרון יכול להיות הפרה של עקרון ה Srp ומה קורה כאשר entities מוגדרים ב assemblies שונים ? אפשר להתחיל לסבך את המערכת .

Capture5

 

שיטה היברידית של חלק Entity Repository יעודי וחלק משותף המאפשר אגידה של concrete entities המיצגים את את התפקיד במימוש שונה

Capture6

02.03.2013

Android

Row , synthetic sensors

SensorManager   class

Sensor class

public boolean isAccelerometerSupported(Context context)
{
SensorManager sm = (SensorManager) context
.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);
return sensors.size() > 0;
}
SensorEvent.timestamp 
Sensor.getMinDelay ()
Sensor.getMaximumRange ()
Sensor.getResulotion ()
SensorEventListener 

Java SE


java 8 lambdas


List<Int>  theList =  Arrays.asList(1,2,3,4,16)
.stream()
.map(s -> "Hello " + s)
.collect(Collectors.toList());





 
 
SoccerService soccerService = (teamA, teamB) -> {
SoccerResult result = null;
if (teamA == teamB) {
result = SoccerResult.DRAW;
}
else if(teamA < teamB) {
result = SoccerResult.LOST;
}
else {
result = SoccerResult.WON;
}

return result;
};


 


Ruby 

sub and gsub (Replace all )
myStr = “test test”
myStr2 = myStr.sub (/te/ , “*”)
puts “#{mystr2}”
 
class Regexp
Regexp.new (“mm/dd”)
%{mm/dd}
=~ positive match 
!~ negative match 
 

Groovy


assert


class Book {



String titie


}


def gb = new Book ()


gb.SetTitle (“Mazal sadon”)


gb.Title = “my life”


Linux


struct cdev *my_cdex = cdev_alloc ();


cdev_add


cdev_del


The user-level library glibc.so has an implementation of the threads.


light-weight processes – representation of the user space thread in kernel space


 Each user-thread has a 1×1 mapping to an LWP


for each process its light weight process share the same group id allowing resource sharing

#include <sched.h>
int clone (int (*fn) (void *), void *child_stack, int flags, void *arg);



 


 

 

 

 

 

 

יום שישי, 1 במרץ 2013

DDD and control systems part I

משפט פתיחה קצת מסובך :

בניגוד למערכת IT שמסתובבות סביב ה DB ורק ל5% מהם מתאימה ארכיטקטורה של Domain driven Design (המטוטולוגיה כלומר ההתמקדות בdomain עם שפת ה domain מתאימה לכולם אבל שיכבת ה domain ב BLL עם ה Services , Entities and Value objects  מתאימה רק למקצת מפרויקטי ה IT ). הארכיטקטורה של DDD מתאימה לרוב פרויקטי שו”ב ומפשטת את המימוש של המורכבות שלהם .

ניקח כדוגמא את המערכת הבאה של שואב אבק רובוטי אשר נשלט על ידי מחשב Desktop .כלומר המשימה שלו (איזה חדרים לנקות , מתי להתחיל לפעול קבלת התראות על מצב הסוללה )נשלטת על ידי המחשב הDesktop אופן התזוזה של השואב  ההחלטה אם המגירה של ה אבק מלאה נשלטים על ידי מחשב פנימי .

blog1

 

Capture2

 

Domain

ב Domain driven design של המערכת הזו כאשר בוחנים את המורכבות  שלה סביר להניח שיש domain אחד שאחראי על כל הפעולות שלה .אולי אם המערכת היתה שולטת גם על הספריקלים של הכיסוי אש אולי היה טעם להפריד לשני domain ים שונים .

 

QCRS Query Command Responsibility segregation

בהתאם לעקרונות של QCRS אנו נפצל את המערכת לשניים :

חלק של Query :

שתפקידיו:

  • להציג מפה של הבית ובה מיקום השואב כרגע איזה חדרים נוקו כבר איזה חדרים צריך עוד לנקות מכשולים שמוגדרים מראש וכד
  • להציג גרף של ניקיון הבית באחוזים
  • להציג נתוני Data Mining איזה חדר היה הכי מלוכלך
  • להציג נתוני הפעלה של השואב כגון מד סיבובי מנוע , מצב המגירה של האבק באחוזים
  • להציג התראות כגון “קשה לי מצטער תנקה קודם כל קצת ידנית ואח”כ אני אכנס לפעולה בחדר הזה “

 

חלק של Command :

חלק שמאפשר לבעלת הבית לתת פיקוד ישירות לשואב אבק כדוגמת :

עזוב עכשיו מלשאוב את חדר השינה וחוש לנקות את החדר של הילדה (המורה הפרטי לאלגברה צריך לבוא עוד כרבע שעה ואם הוא יראה את הבלאגן שמה לא אדע איפה לקבור את עצמי מבושה )

חלק אשר מנצל את יכולתו החישובית של ה מחשב ה desktop ומנתח לפי הנתונים שזורמים מהשואב היכן כדאי לשואב לעבור עכשיו על מנת לעבוד יותר יעיל ,היכן בהסתמך על נתוני העבר האיזור היותר מגופגפ בבית שבו צריך לתת יותר גז בשאיבה וכד

את החלק של ה command אנו נתכנן ונבנה באמצעות DDD

Entitites

הEntities של המערכת יכולים להיות כדלקמן :

  • תחנת עגינה וטעינה
  • השואב הרובוטי עצמו
  • מכשול שאליו אסור להתקרב כדוגמת ואזה
  • חדר בבית (שאותו צריך לנקות )
  • הבית עצמו
  • תוכנית ניקוי
  • סוללה של השואב הרובוטי

לכל ישות ישנו id המורה על יחודיות לדוגמא תוכנית ניקוי עם id של תוכנית ניקוי קצרה לפני שהחותנת באה וכד

ה Entities  מכילים  State לדוגמא :

הישות של השואב הרובוטי מכילה את ה state של האם נוריות האזהרה דולקות , מצב המקום הפנוי בתא האבק וכד

וגם operational כדוגמת :

הדלק אורות

Value objects

  • כמות אבק במגירה
  • זמן עבודה נותר
  • כמות האנרגיה שנשארה לשואב הרובוטי

Aggregations

הישות סוללה של השואב הרובוטי מחוברת כ aggregate root של ישות השואב , אין לסוללה הזו משמעות ללא הקשר לשואב .

Services

אילו מרכיבים את לב הלוגיקה של המערכת ומכילים את הפעולות שלא ניתן לפנות אל entity ספציפי ולדרוש שיבצעם 

דוגמאות :

VCGotoDockingStationService

הפקודה לשואב הרובוטי לחזור לתחנת העגינה אינה יכולה להיות חלק מהישות של השואב הרובוטי עקב כך שהיא מכילה פניה למספר Entities שונים : תחנת העגינה , השואב עצמו , המחשולים שפזורים בדרך ועוד לכן העדפתי לממש אותה כService .

Capture3

 

יש עוד הרבה נושאים לדבר עליהם :

  • Repositories
  • Factories
  • השילוב של ה Domain layer בין השכבות של ה application , UI , ו Infrastracture
  • המימוש של המערכת

אם אקבל תגובות אשמח להמשיך לכתוב על הנושא