mardi 31 mars 2015

most elegant way of escaping $ in java

I have a base String "abc def", I am trying to replace my base string with "abc$ def$" using replaceFirst() method, which is running into errors as $ is not escaped.


I tried doing it with Pattern and Matcher APIs, as given below,


newValue = "abc$ def$";


if(newValue.contains("$")){


Pattern specialCharacters = Pattern.compile("$");


Matcher newMatcherValue = specialCharacters.matcher(newValue) ;


newValue = newMatcherValue.replaceAll("\\$") ;

}


This runs into error. Is there any elegant way of replacing my second string "abc$ def$" with "abc\\$ def\\$".so as to use the replacefirst() API successfully.


Thanks in Advance.


Finding a specific pattern using grep (or any other program)

I am looking for a very specific pattern in a database of proteins. The structure I am looking for is C1XXXC2-X(n)-C3XXXC4. C = cysteine.


For example: MALEAQMTLRMFVLVAMASTVHVLSSSFSEDLGTVPLSKVFRSETRFTLIQSLRALLSRQLEAEVHQPEIGHPGFSDETSSRTGKRGGLGRCIHNCMNSRGGLNFIQCKTMCS


As you can see, this sequences ONLY has four C's and they are in the pattern that I mentioned above. There cannot be any more C's in the rest of the sequence!


I was using this code: grep "[A-Z]"C...C"[A-Z]"C...C"[A-Z]*", but it would give me sequences with more than four C's.


Thank you in advance for any help.


Pattern for "Varied Parameters"

I am trying find out the best way to pass "varied parameters" through a method in interface. I created a solution that worked, but my concern is it will be used for thousand of GLResource objects. So, I would like to know if this solution is an anti-pattern or if there is another known solution for this kind of situation. I just want avoid refactoring it in the future.


Let's demonstrate:



At first, I created an interface that represents a OpenGL resource, that I called GLResource, and it have to be implemented by all OpenGL Resource.




public interface GLResource {
public void onSurfaceCreated(VariedParameters variedParameters);
public void onSurfaceChanged(VariedParameters variedParameters);
public void deleteResources();
public void onDrawFrame(Canvas canvas);
}



Basically, all OpenGL resource configuration will be passed through VariedParameters class. And sometimes you can pass a texture or vertex data, or another kind of object configuration.


The implementation of VariedParameters is simple:




class VariedParameters <K extends Enum<K>> {
private Map<K, Object> parametersMap = new HashMap<>();

public VariedParameters<K> putParameter(K key, Object value){
parametersMap.put(key, value);

return this;
}

public Object getParameter(K key){
return parametersMap.get(key);
}

public void clear(){
parametersMap.clear();
}
}



An implementation of GLResource could be:




public class Car implements GLResource{

@Override
public void onSurfaceCreated(VariedParameters variedParameters) {
Texture carTexture = (Texture) variedParameters.getParameter(CarParameters.CAR_TEXTURE);
Texture wheelTexture = (Texture) variedParameters.getParameter(CarParameters.WHEEL_TEXTURE);
Foo foo = (Foo) variedParameters.getParameter(CarParameters.FOO);

if(carTexture == null || wheelTexture == null || foo == null){
throw new IllegalArgumentException("Some arguments is missing.");
}

// Work with these parameters...
}

@Override
public void onSurfaceChanged(VariedParameters variedParameters) {
// TODO Auto-generated method stub
}

@Override
public void deleteResources() {
// TODO Auto-generated method stub
}

@Override
public void onDrawFrame(Canvas canvas) {
// TODO Auto-generated method stub
}

public enum CarParameters{
CAR_TEXTURE,
WHEEL_TEXTURE,
FOO;
}
}



And below is an example of code that will use all GLResource implementation:




public class Main {

public static void main(String[] args) {
Car car = new Car();

VariedParameters<CarParameters> carVariedParameters = new VariedParameters<>();
carVariedParameters.putParameter(CarParameters.CAR_TEXTURE, new Texture());
carVariedParameters.putParameter(CarParameters.WHEEL_TEXTURE, new Texture());
carVariedParameters.putParameter(CarParameters.FOO, new Foo());

car.onSurfaceCreated(carVariedParameters);
}

}


So, what do you think about this pattern?


Design pattern to remove duplicate code for Runnable interface

I have 2 classes with Runnable interfaces that are called when sending POST request to endpoints:



class Testinput implements Runnable {
private final String USER_AGENT = "Mozilla/5.0";
private static Enginetest enginetest;
private static MySqlite mySqlite = new MySqlite();
public Testinput(String v1,String v2, String urlpass) {
this.v1 = Integer.parseInt(v1);
this.v2 = Integer.parseInt(v2);
this.enginetest = new Enginetest();
this.urlpass = urlpass;
}

public void run(){
try{
enginetest.method2(v2, true);
List<String> res = enginetest.method1(v1);

String url = urlpass;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.addRequestProperty("content-type", "application/json");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

JSONObject json=new JSONObject();
json.put("result",res.get(0));

String urlParameters = json.toString();
System.out.println(urlParameters);

// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

int responseCode = con.getResponseCode();
if (responseCode!=200){
System.out.println("failed");
}
else{
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
} catch (Exception e){
NotifyAdmin.notify_watching("NOt working", "TODO");
e.printStackTrace();
}
}
}


ANd the second Runnable class:



class Getaccount implements Runnable {
private final String USER_AGENT = "Mozilla/5.0";
private static Enginetest enginetest;
private static MySqlite mySqlite = new MySqlite();
public Getaccount(String vimvalue, String urlPass) {
this.vimvalue= Integer.parseInt(vimvalue);
this.valuetest = new Valuetest();
this.urlPass = urlPass;
}

public void run(){
try{
Getaccount.setvalue(vimvalue);

String url = urlPass
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.addRequestProperty("content-type", "application/json");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

int responseCode = con.getResponseCode();
if (responseCode!=200){
System.out.println("failed");
}
else{
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
} catch (Exception e){
NotifyAdmin.notify_watching("NOt working", "TODO");
e.printStackTrace();
}
}
}


So the difference between these 2 classes is different methods we call inside run method and also different methods in Runnable interface (Getaccount, Testinput).


Since I have multiple Runnable interfaces in my code, what would be the best design pattern to remove duplication between run methods.


Pattern for hiding recursive function in Scala

Given this recursive function :



def visitAll(s: String): Unit = {
val files = getFiles
for (a <- files) {
visitAll(s)
doSomeWork()
}
}


This will act as a driver for work. Is there a pattern or Scala idiom that will allow to hide recursive structure from developer so all all developer needs to worry about is implementing method doSomeWork() ?


What is the appropriate pattern for mapping multiple data sources to a single business object?

We have a business model and associated repository. This is populated by disparate data from different tables in a database. At some point, after the user had made changes to the data, we have to reflect those changes back to the database. Currently this is done by associating the key with the object like this:



class DataObject
{
string SomeProperty;
// more properties

int Table1Id;
int Table2Id;
int Table3Id;
}


I proposed a slight cleanup by adding a property that identifies the source table, and then using a single "ExternalId" property; but I'm wondering if there is a better pattern for this that decouples the data and business layer better.


We are using C#, but this is a somewhat language agnostic question.


Finding Missing Files with Perl Script [Directory Entery and Export Protocol]

I exported some Files and after the Export there are actually 2 Files missing. In the Protocol is written that i Exported 560 Files but I only got 558.


Now I want to check which File is missing. So I decided to try it with a Perl Script, even tho im pretty new to this.



#!C:\Strawberry\perl\bin\perl.exe

#Pragmas
use strict;
use warnings;


my $Dir = 'Directory to the Exported Files';
my $Export = 'Directory to the Export Protocol File';
my $Expo;

#Open Directory
opendir( DIR, $Dir ) || die "can't opendir $Dir: $!";
my @files = readdir(DIR);
closedir(DIR);

#Open Export File
open( DATEI, "$Export" ) or die $!;
while (<DATEI>) {
$Expo = $Export . $_;
}
close(DATEI);

#Comparing which File is missing.....[Not working obviously :(]
foreach my $file (@files) {
if ( $Expo !~ m/$file/ ) {
print "$file\n";
}

}


The Export Protocol Looks like this...



DATEDATEDATE - USER EXPORT, counter '0000000001': Object: 'FILENAME' got exported. DATEDATEDATE- USER EXPORT. File: 'D:\Work\Export_Import\Export\FILENAME.xml' exported.



The only important Thing is the Filename :]


I hope you understood my Problem ...


Thank you!


How can I handle HTTP login flow/logic

I'm developing an application that requires the user to login. It's a terminal browser to navigate, and use, a popular email client.


I am struggling with the logic flow of actually logging the user in without things getting messy. I will try to explain what I'm trying to achieve in psedueo code, and then demonstrate what I've currently done.



username = 'joe@example.com'
password = 'itsasecret'

# User has logged in before using our application. Instead of
# logging in via HTTP, just inject the cookies into the session.
if userExistsInDatabase:
session.addCookies(db.getCookies(username))

# Check the session is still valid. Just because we load
# the cookie from the database doesn't mean it's valid as
# the account could be blocked, or session could have expired
if session.checkIfSessionIsValid():
print 'Logged In'
else:
# Login failed, now we need to do a HTTP request
# incase the session has died
if session.login(username, password):
# Login success
else:
# Login Failed
else:
# No session exists in DB, try to log in and add user to db
if session.login(username, password):
# Login success
else:
# Login Failed


I hope that code explains it better than I could in words. But, the problem I am having is everything is getting messy and fast, and it's a pain to have to repeat this code whenever I need to use it.


This is something I do regular on a lot of my projects, because most HTTP sites, at least the large ones, have a similar sort of login flow.


Any advice?


Where to start learning design patterns

I'm very newbie, but I'm allways hearing from my college that 'you should use design patterns'. Could you give me an advice where to start? Thank you!


Why is the usage of design patterns considered anti-pattern?

While reading Anti-patterns, I have met the following:



The use of patterns has itself been called an anti-pattern, a sign that a system is not employing enough abstraction.



Anybody can explain this thought thoroughly?


What is the proper way to implement MVC pattern in iOS app?

I'm trying to make a clear MVC project. So is it good or bad idea to use NSNotificationCenter's observers for communication between UIViews and ViewControllers?


For example in custom CustomView.m i make a button:



- (void) makeSomeButton{
....
[bt addTarget:self action:@(buttonWasClicked) forControlEvents:UIControlEventTouchDragInside];
...
}

- (void) buttonWasClicked {
[[NSNotificationCenter defaultCenter] postNotificationName:@"buttonWasClicked" object:nil];
}


And in the viewCotroller.m i'm adding observer in init section:



- (void)viewDidLoad { //
[self.view addSubview: [[CustomView alloc] initWithFrame ...]];
.....
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@(buttonWasClicked) name:@"buttonWasClicked" object:nil];
.....
}

then
- (void) buttonWasClicked{
// button was clicked in customView so do something
}


If it's not correct, please, explain what is the proper way to implement MVC pattern in iOS app?


which is the best design pattern for winforms .net?

I want to redesign an existing windows desktop form application with modularity and seperation of concerns principles but I cannot specify which design pattern is appropriate one.


Delegates vs interface observer pattern resources

Can anyone help me with links to videos or good tutorials about Delegates vs interface observer pattern?


lundi 30 mars 2015

iOS Objective-C: weakSelf Syntax

Nearly every example of the weakSelf pattern I encounter online has the syntax



__weak typeof(self) weakSelf = self;


But the compiler complains about this syntax in the latest version of Xcode, requiring:



__weak __typeof__(self) weakSelf = self;


Did the syntax change, or am i missing an import? I tried pulling in <objc/runtime.h> but no change.


Stealthy bonus question: Why not just cast it explicitly?



__weak MyBoffoClass *weakSelf = self;


I found one answer here that said it was better to cast it directly, but no reasoning as to why.


C# Accessing a nested variable by name

I multiple classes with the following nested structure -



class A
{
public B b;
public C c;
}

class B
{
int count;
}

class C
{
public d D
}

class D
{
string name;
}


I need to access the deepest level variables of multiple such object structures at runtime. I will not know the structure of the class beforehand, and I will need to repeatedly do this over and over.


My approach was to use reflection string to variable name and store the object structure, however knowing the object structure is there any way I can access it faster or will I have have to use multiple level reflection? For example to access name I would do the following via c# code - a.c.d.name, but by using reflection -GetType(A).GetMember(c).GetType().GetMember(d).GetType().GetMember(name).SetValue(blah);


Any suggestions?


Whats the best approach (design pattern) to access database in C#?

I am a newber in design pattern. Currently I am developing a system where I have a releation DB. What would be the best approach to CRUD from my DB? My current code looks like the follow (C# code):


I defined a inteface with commons functions to all classes.



namespace Model
{
public interface ICommon
{
void insert();
void update();
void delete();
}
}


The Common class (abstract one) implements ICommon interface and few orders methods and attributes.



namespace Model
{
public abstract class Common : ICommon
{
public Guid RecId { set; get; }

public abstract void insert();
public abstract void update();
public abstract void delete();
public abstract List<Common> find();

/// <summary>
/// Insert or update the record
/// </summary>
public void save()
{
if (this.RecId == Guid.Empty)
{
this.insert();
}
else
{
this.update();
}
}
}
}


Then, the proper class (UserTable class for example) extends the Common class and implements the abstracts methods and others particulars attributes.


The way that I am doing my CRUD its from StoresProcedures and SqlParameter, SqlCommand and SqlConnection. Here it is a example:



class CustTableModel : Common
{
public string SerialNumber { set; get; }
public string ApplicationVersion { set; get; }
public string KernelVersion { set; get; }
public string Name { set; get; }
public bool Active { set; get; }

public override void insert()
{
List<SqlParameter> parameters = new List<SqlParameter>();
SqlParameter parameter;

// SerialNumber
parameter = new SqlParameter("@serialNumber", System.Data.SqlDbType.Int);
parameter.Value = this.SerialNumber;
parameters.Add(parameter);

// ApplicationVersion
parameter = new SqlParameter("@applicationVersion", System.Data.SqlDbType.Int);
parameter.Value = this.ApplicationVersion;
parameters.Add(parameter);

// KernelVersion
parameter = new SqlParameter("@kernelVersion", System.Data.SqlDbType.Int);
parameter.Value = this.KernelVersion;
parameters.Add(parameter);

// Name
parameter = new SqlParameter("@name", System.Data.SqlDbType.Int);
parameter.Value = this.Name;
parameters.Add(parameter);

// Active
parameter = new SqlParameter("@active", System.Data.SqlDbType.Bit);
parameter.Value = this.Active;
parameters.Add(parameter);

DBConn.execute("CUSTTABLE_INSERT", parameters); // The code of DBConn is below.
}
}


Just to a better understanding, here it is the DBConn class:



public class DBConn
{
protected SqlConnection sqlConnection;
protected string command { set; get; }
protected List<SqlParameter> parameters { set; get; }

protected void openConnection()
{
this.sqlConnection = new SqlConnection();
this.sqlConnection.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=JYL_SOAWS_DB;Integrated Security=True";
this.sqlConnection.Open();
}

protected void closeConnection()
{
if (this.sqlConnection.State == System.Data.ConnectionState.Open)
{
this.sqlConnection.Close();
}
}

/// <summary>
/// Executa o processo no banco.
/// </summary>
/// <returns>Quantidade de registros afetados.</returns>
protected SqlDataReader run()
{
SqlCommand command = new SqlCommand();
SqlDataReader ret;

this.openConnection();

command.CommandType = System.Data.CommandType.StoredProcedure;
command.Connection = this.sqlConnection;
command.CommandText = this.command;

if (this.parameters != null)
{
foreach (SqlParameter parameter in this.parameters)
{
command.Parameters.Add(parameter);
}
}

ret = command.ExecuteReader();

this.closeConnection();

return ret;
}

/// <summary>
/// Interface da classe à outros objetos.
/// </summary>
/// <param name="commandName">Nome da store procedure a ser executada.</param>
/// <param name="parameters">A lista com os parâmetros e valores.</param>
/// <returns>Numero de registros afetados.</returns>
public static SqlDataReader execute(string commandName, List<SqlParameter> parameters = null)
{
DBConn conn = new DBConn();

conn.command = commandName;
conn.parameters = parameters;

return conn.run();
}
}


I am pretty sure that there is a better way.


Could anyone help me? Thanks is advance.


Unable to understand what kind of design pattern this is?

I am not able to understand the below design. Let's assume the below classes and interfaces



interface A
{
....
}
class B implements A
{
....
}
class C extends B implements A
{
...
}


I found this design in one of the IBM frameworks (wcs order framework). So here why class C needs to implement A ?


What are the different scenarios in which you can use this design?


What type of design pattern is this?


Is using the singleton pattern a good idea when accessing libraries using MVC?

I have a web app, this app as you already know will have a lot of requests, and each request will run on a different thread, meaning that if I use singleton to access my DAL library it will not be a problem.


However I'm unsure about wether this is the best approach, because I read that one request my use different threads sometimes, and I have also read that locking threads may cause a performance lost sometimes when using single instances.


Just so you understand me better this is what I plan to do:


DAL <- SingleInstance <- BAL <- SingleInstance <- Controllers <- Views


Is this a good approach?


This is the singleton I plan to use:



public static Products Instance
{
get
{
return Nested.instance;
}
}

class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}

internal static readonly Products instance = new Products();


Note: My Dal will access the database using ADO.NET(I have my reasons to use ado), and the BAL will only use this method to do select or CRUD operations. Thanks.


What's the design pattern here (if it is one)?

I would like to know if the following code represents any of the known design patterns. I'm doubtfully wondering if it applies to the Proxy pattern. The point is that in the system B (who implements the interfaces), I can call the Alaskan or Russian bear repositories directly, but in most cases the generic repository (BearRemoteRepository) would be called. Beyond the above question I'm wondering if this is a good practice, to have opened the possibility of using two different interfaces, even if they have the same methods of its parent. Important! The two bears have different behaviours...



//System A:
public interface IBearRepository {

public Bear save(Bear pBear);

}


public interface IBearAlaskaRepository extends IBearRepository {

}

public interface IBearRussiaRepository extends IBearRepository {

}


//System B:
public class BearRemoteRepository implements IBearRepository {

IBearRepository bearAlaskaRemoteRepository;
IBearRepository bearRussiaRemoteRepository;

@Override
Bear save(Bear pBear) {
ICompromissoRepository remoteRepository = resolveRepository(pBear)
return remoteRepository.save(pBear);
}

private IBearRepository resolveRepository(Bear pBear) {
if (pBear in BearAlaska) {
return bearAlaskaRemoteRepository;
} else {
return bearRussiaRemoteRepository;
}
}
}

public class BearAlaskaRemoteRepository implements IBearAlaskaRepository {

@Override
Bear save(Bear pBear) {
return save(pBear);
}

}

public class BearRussiaRemoteRepository implements IBearRussiaRepository {

@Override
Bear save(Bear pBear) {
return save(pBear);
}

}

Software Design Pattern for Master Detail

Can anyone suggest a design pattern for a master/detail UI? Basically, I have a master page that shows a collection of items. You can select an item, delete, add, edit. When you add or edit, it will show the Detail UI, where the single item is edited and saved.


The master has the basic functionality of -



  • getItems (collection)

  • getItem

  • deleteItem


The detail has the functionality of -



  • getItem

  • saveItem


Many different objects in my application will have this same pattern; they are just different types. My natural tendency is to create two generic base classes that do as much of the work as possible - BaseMaster, BaseDetails class


and just inherit from them from each object type. However from experience I find that you put too much code into the base classes and end up fighting around the functionality of them.


I was thinking some sort of dependency inject/composition over inheritance idea would be the way to go but cannot quite picture it fully.


Which is the better way to communicate between two views?

One of our our project requires a simple custom keyboard control that will be reused throughout the project's many views and possibly future projects as well.


A question was posed:


If we know that the keyboard control's sole purpose is to provide the user a way to input data to modify a single UITextField or UILabel is it:


a) better to pass a reference to that UITextField to the CustomKeyboardView and let that view handle the modification of the textfield's text inside of it's class or:


b) write a delegate for returning the values from the CustomKeyboardView and make the parent viewController handle receiving callbacks from the keyboard and setting the correct value of the UITextField or:


c) do it using some other pattern?


It is worth noting that the code for writing text to the textfield is a bit more involved than simply passing raw characters, it compares the value that is already in the textfield and passes the character according to that state.


Shared builder pattern on iOS?

I'm struggling now with a dilema in my project and really can't help myself with finding proper solution. Here's the problem:


I have to POST some object to the backend using RESTful API but this object contains of many properties which can be filled across many different views. I don't want to make a call to the API everytime I fill another property but instead I want to gather all info and send this request once.


I thought about a builder pattern but I'd like to have it as a singleton so I won't have to pass everything from view to view... But is it a good approach? I thought that once I finish collecting properties and called [builder build] I'd nill all of those properties.


I don't like the idea of having many properties in my API methods and also I hate the idea of passing properties across many views until user tap on send or so on.


Could you guys give my a hint?


Algorithm for conditioned migration

Literal description of the problem:


Given a number of schools, each school holds a number of teachers according to its needs. At the end of the scholar year, some teachers ask for changing their positions (schools where they're currently teaching) according to an ordered list (i.e: change me to school1, if not possible, school2, if not possible school3, etc..) Remembering that each school must have EXACTLY the number of teachers it needs (not more, not less).


Each teacher has an importance number that is unique, so that if two or more teachers ask for the same school at the same time, the one having the higher importance number will get the desired school.


if we are unable to migrate one or more teachers following his list, then we keep him at his initial school answering: "sorry, your demand is affordable for this year"


How can we afford this "migration" ?


(p.s: by "afford" I mean change the position of each teacher to the best (best according to his list) desired school.




I/ Algebraic modeling of the problem


Given E={e1..en}, n>=0, a set of positive integers (e for entity)


Given L={l1..lm}, m>=0, a set of positive integers (l for location)


Given P:E --> L , a function. (P for position)


Given C:L --> IN*, a function. (C for capacity)


Given U:L --> IN, a function. (U for used) defined by: U(l)=card({e/P(e)=l})


Given A:L --> IN, a function. (A for available) defined by: C(l)=A(l)+U(l) for any l in L.


Let D:E --> L^k, where 0 < k <= m, D(e)=(l1,l2,..li) a function (D for destinations)


(That is, each entity has an ordered non-empty list of locations (destinations) willing to move to).


Let I:E --> IR+, a bijection (I for Importance). (That is, each entity has a unique importance number I(e))


II/Rules of Migration:


The asked task, is to find out the new P' function (Positioning) that affords the following:


1- P'(e) belongs to {l1,l2,..,li} where (l1,l2,..,li)=D(e)


2- If we P'(e)=ls and P'(e)=lt are two possible solutions, where D(e) = (l1,...,ls,...,lt,...,li), then we must keep the solution that matches the destinations' order (i.e ls in this case) and exclude the other one)


3-If A(l) = 1 and P'(e1)=l and P'(e2)=l are two possible solutions, where I(e1)>I(e2) then we must keep the solution that matches the importance's order (i.e in this case P'(e1)=l) and exclude the other one.


4- If none of the desired destinations is possible, then P'(e)=P(e)


How should I break down this huge function into smaller parts

I am trying to understand good design patterns in Python and I cannot think of a way to break this huge function into smaller parts without making the code cluttered, overly complex or plain ugly.


I didn't want to clutter my question by posting the whole file, I mean this function itself is already very large. But the class has only two methods: parse_midi() and generate_midi(file_name, file_length).


pitches, velocities, deltas, durations, and intervals are all MarkovChain objects. MarkovChain is a simple class with methods: add_event(event), generate_markov_dictionary(), and get_next_event(previous_event). MarkovChain.src_events is a list of events to generate the Markov chain from. It is a simple implementation of first order Markov Chains.



def parse_midi(self):
# on_notes dictionary holds note_on events until corresponding note_of event is encountered
on_notes = {}
time = 0
previous_pitch = -1
tempos = []
delta = 0
for message in self.track_in:
time += message.time
delta += message.time
# There are also MetaMessages in a midi file, such as comments, track names, etc.
# We just ignore them
if isinstance(message, mido.Message) and message.type in ["note_on", "note_off"]:
# some midi files use note_on events with 0 velocity instead of note_oof events
# so we check if velocity > 0
if message.velocity > 0 and message.type == "note_on":
on_notes[message.note] = time
self.pitches.add_event(message.note)
self.velocities.add_event(message.velocity)
self.deltas.add_event(delta)
delta = 0
if previous_pitch == -1:
self.intervals.add_event(0)
else:
self.intervals.add_event(message.note - previous_pitch)
else:
# KeyError means note_off came without a prior associated note_on event!"
# Just ignore them
with ignored(KeyError):
self.durations.add_event(time - on_notes[message.note])
del on_notes[message.note]

previous_pitch = message.note
# Tempo might be many tempo changes in a midi file, so we store them all to later calculate an average tempo
elif message.type == "set_tempo":
tempos.append(message.tempo)
elif message.type == "time_signature":
self.time_signature = self.TimeSignature(message.numerator, message.denominator,
message.clocks_per_click, message.notated_32nd_notes_per_beat)
# some tracks might be aempty in a midi file. For example they might contain comments as track name, and no note events
if len(self.pitches.src_events) == 0:
print("There are no note events in track {}!\n"
"The file has {} tracks. Please try another one.".format(self.selected_track, self.num_tracks))
exit(1)
# a midi file might not contain tempo information at all. if it does, we calculate the average
# else we just assign a default tempo of 120 bpm
try:
self.average_tempo = int(sum(tempos) / len(tempos))
except ZeroDivisionError:
self.average_tempo = mido.bpm2tempo(120)

Simpler Singleton Pattern

I have been reviewing some code of some old projects and I found a singleton there. It is a requirement to use a singleton and I was thinking of a way to make it look "simpler" when using.


I found, it would be easier to access the methods and properties like a static class. So I basically implemented a singleton using static methods to skip the requirement to use GetInstance(). This is how I implemented it:



public class ExampleSingleton
{
string someRequiredValue = "This is an example.";

/// <summary>
/// Private Constructor
/// </summary>
private ExampleSingleton() { }
private static volatile ExampleSingletoninstance;

/// <summary>
/// !!! PRIVATE !!!
/// Instance Property.
/// Returns the instance of this singleton.
/// (ThreadSafe)
/// </summary>
private static ExampleSingleton Instance
{
get
{
if (instance == null)
{
lock (_lock)
{
if (instance == null)
{
instance = new ExampleSingleton();
}
}
}

return instance;
}
}

/// <summary>
/// Example field contains a value that should be
/// accessible from outside.
/// </summary>
public static string SomeRequiredField
{
get
{
// Here you do the job you would have to do "outside"
// of the class normally.
return ExampleSingleton.Instance.someRequiredValue;
}
}

// Helper for a secure thread synchronisation.
private static object _lock = new object();
}


So when you want to access the singleton values you can just do it like this:



// Access the values like this
string requiredField = ExampleSingleton.SomeRequiredField;

// Instead of this
string requiredField = ExampleSingleton.Instance.SomeRequiredField;

// Or even this
string requiredField = ExampleSingleton.GetInstance().SomeRequiredField;


Am I violating the principles of the singleton pattern here? It basically is still a singleton pattern but the work of getting the instance is done internally. What could be the con's of this example? Are there other pro's?


Thanks


ios cell filling design pattern

I have a collection cell which used in multiple screens and setting lots of data in it. Which approach is better, setting data in UIViewController or in UICollectionviewCell? I didn't see second much but i don't know how to find right design pattern for this. As example:


First:



@implementation ProductViewController:UIviewController
{
-(UICollectionviewCell*)CellForIndexpath:(UIcollectionview*) collectionview..{
myCell *cell=[collectionview dequecellwithcellidentifier:@"cell"];
Product *pr=[datasource objectAtIndex:indexpath.row];
cell.lblName.text=pr.name;
cell.lblSize.text=pr.size;
[cell.imgCover setimage:pr.image];
..
return cell;
}
}


second:



@implementation ProductViewController:UIviewController
{
-(UICollectionviewCell*)CellForIndexpath:(UIcollectionview*) collectionview..{
myCell *cell=[collectionview dequecellwithcellidentifier:@"cell"];
Product *pr=[datasource objectAtIndex:indexpath.row];
[cell initProduct:pr];
return cell;
}
}
@implemeantation myCell:UICollectionviewCell{
-(void)initProduct:(Product*)pr{
self.lblName.text=pr.name;
self.lblSize.text=pr.size;
[self.imgCover setimage:pr.image];
..
}
}

dimanche 29 mars 2015

When Iterator invalidation is occurred in observer pattern with single process single thread environment

I'm implementing an observer pattern that the subject notifies observers and I knew it has a issue as bellow.



  • Issue : iterator for notify() can be invalid, when container for observers like std::vector, std::list is modified on being notified.


But as I think, in single thread single process environment, invalid iterator issue never be happen except in as bellow situation.



  • situation 1 : some observers modify observer container when it notified.

  • situation 2: loop for notify() modify observer container on being notified.


I know, situation 1,2 make iterator invalid, but I want to know concrete case.


Hope some advice. Thanks.


Using Object Oriented Design with Ruby, how to show transfer of ownership?

Say we have the following classes: Bakery, Equipment, and Batch. Bakery is composed of Equipment like so:



class Bakery
attr_accessor :equipment
end


Equipment looks like this:



class Equipment
attr_accessor :name, :quantity
end


So to represent a bakery with two ovens we can do this:



ovens = Equipment.new
ovens.quantity = 2
bakery = Bakery.new
bakery.equipment = [ovens]


Now the Batch class represents one batch of baked goods. It is itself composed of a Formula with several Step objects. The Formula class contains the order of steps and timing information so that Batch knows when some equipment needs to be used. (I'm leaving out the Formula and Batch code for brevity. Full code is available here and here.)


My question is how do I use OOD to temporarily transfer ownership of some equipment (say, 1 oven) from bakery to batch. bakery holds an instance of Equipment that represents two ovens. One of those ovens is going to be temporarily occupied by a batch process. Should I create a new instance of Equipment and pass it to the batch while decrementing the quantity of ovens? Or should I not bother with the quantity attribute and simply create one instance of Equipment for each oven in the bakery? In that case I could simply pop the last oven off the bakery.equipment array and push it onto batch.equipment until batch is finished. One business logic requirement is to be able to query future availability of bakery.equipment. So there needs to be some distinction between the current state (i.e. how many ovens are occupied) and future states (i.e. how many ovens will be occupied at 9:00 PM).


Pattern name meaning: "Configurable Back-Ends"

What is the best name of the design pattern that describes a system where you can choose to CONFIGURE your system to be deployed using a back-end service from a list of compatible services? For example, software that can be CONFIGURED to use any number of different "brands" of SQL database: MySQL, PostGRES, Oracle, etc. (Note: NOT a pattern that focuses on "hot swapping" backends at runtime.)


So far, in my research, I have come up with a handful of pattern names that do not seem to exactly describe this: Facade, PlugIn, Extensibility.


Design or Algorithm to Validate a Pattern of Data in DataTable C#

I have a very weird situation . I have a Excel file with data like


Header data_xyz

A|B|C

datA 1|2|3

datB 1|2|3

datC 1|2|3

.

.

.

.

END of Pattern

Recurring Pattern

Header data_xyz

A|B|C

datA 1|2|3

datB 1|2|3

datC 1|2|3

.

.

.

.

END of Pattern


Now we need to validate the data in columns A,B,C is Numeric and similarly check the datA,datB be not empty .


Rules will be 1)No of data rows in pattern differ 2)Each Pattern is defined so any data other than pattern will be invaid


Can we use some design to achieve the same .


Thanks in advance


Algorithm for conditioned migration

I/ Algebraic modeling of the problem


Given E={e1..en}, n>=0, a set of positive integers (e for entity)


Given L={l1..lm}, m>=0, a set of positive integers (l for location)


Given P:E --> L , a function. (P for position)


Given C:L --> IN*, a function. (C for capacity)


Given U:L --> IN, a function. (U for used) defined by: U(l)=card({e/P(e)=l})


Given A:L --> IN, a function. (A for available) defined by: C(l)=A(l)+U(l) for any l in L.


Let D:E --> L^k, where 0 < k <= m, D(e)=(l1,l2,..li) a function (D for destinations)


(That is, each entity has an ordered non-empty list of locations (destinations) willing to move to).


Let I:E --> IR+, a bijection (I for Importance). (That is, each entity has a unique importance number I(e))


II/Rules of Migration:


The asked task, is to find out the new P' function (Positioning) that affords the following:


1- P'(e) belongs to {l'1,l'2,..,l'i} where (l'1,l'2,..,l'i)=D(e)


2- If we P'(e)=l's and P'(e)=l't are two possible solutions, where D(e) = (l'1,...,l's,...,l't,...,l'i), then we must keep the solution that matches the destinations' order (i.e l's in this case) and exclude the other one)


3-If A(l) = 1 and P(e1)=l and P(e2)=l are two possible solutions, where I(e1)>I(e2) then we must keep the solution that matches the importance's order (i.e in this case P(e1)=l) and exclude the other one.


4- If none of the desired destinations is possible, then P'(e)=P(e)


Which algorithmic problem would matches the one I've exposed?


Avoid lazy loading by ensuring that there is only one static method in a Singleton class

Disclaimer : I am aware that using an enum is one of the most effective ways of creating a Singleton so let's keep this argument aside for now. I am also aware that Singleton is considered an anti-pattern for some use cases so let's leave this aside as well.


The two basic use cases for a class to be loaded in the JVM are:



  1. An instance of the class is created using the new operator (e.g. new MyClass())

  2. The class is referenced in a static context (e.g. System.out.println())


Let's consider an example of Singleton that does not use lazy loading.



public class Singleton {
private static final Singleton INSTANCE = new Singleton();

private Singleton() { }

public static Singleton getInstance() {
return INSTANCE;
}

public static void someStaticMethod() {

}
}


Sine this class has a private constructor, it's not possible to instantiate it using the new keyword. While it is possible to use reflection to create an instance of the class, let's leave that argument aside for now. So the only other way that this class will get loaded is that you refer to it in a static context.


There are two mutually exclusive use-cases for using the class in a static context :



  1. We call someStaticMethod without calling getInstance first.

  2. We call getInstance to get a reference to the only instance of the class.


We only need lazy loading if we ever have to exercise use case 1 in our application. If we don't exercise use case one in our application, we never need lazy loading because when we call getInstance, we intend to load the instance of the class.


This brings me to the question. Instead of worrying about lazy loading, wouldn't it be better that the standard way to implement a Singleton using a class is to ensure that the only static method in the Singleton class is the getInstance method? Besides, having a static method other than the getInstance method in a Singleton class would mean that we are mixing the use case of a static class and a singleton class in one class which IMO should not be done in the first place. What's the fuss about lazy-loading a Singleton anyway?


What is mean by thread safe

Hi I've been going through the singleton pattern, But I'm not able to understand how the below code is thread safe :-



public class ThreadSafeSingleton
{
private ThreadSafeSingleton()
{
}

public static ThreadSafeSingleton Instance
{
get { return Nested.instance; }
}

private class Nested
{
static Nested()
{
}

internal static readonly ThreadSafeSingleton instance = new ThreadSafeSingleton();
}
}


Can somebody explain it ? Cheers :)


Appropriate design for hierarchy object initialization

I am not sure what is the appropriate design for my program. I like to develop a code that contain 3 types (levels).



  1. Manager

  2. Officer

  3. Employee


while the Employee has some fields, the Officer has the same fields with some extension and the Manager have all (they inherits one from each other).


My question is what appropriate design should I use to build those objects? I thought about: 1. "Builder" design, which can create part of the object and you can extend it, if you need to use higher level. 2. Some articles point that I should use "Composite" design.


Any advise will be blessed , Im open for suggestion and for new design. IF you can please add example. Thanks.


how to log the operation of business object in an elegant way by using design pattern?

For example I have two class call Log,and Order,Order is a business object. If i need to log the insert operation of business object Order.Then i have to do something like that:



public class Order
{
IOrderDal dal = DALFactory.DataAccess.CreateOrder();
logger = new Logger();
public void Inerst(OrderInfo order)
{
dal.Insert(order);
logger.log(orderInfo.ToString(),"Insert",DateTime.Now.ToString());
}
public class Logger
{
public void log(string description,string operation,string time)
{
....//dosometing to persist the information
}
}


My question is that if i have hundreds of business object need to be logged,then i have to add the code like logger.log(orderInfo.ToString(),"Insert",DateTime.Now.ToString()) in each operation of bussiness objects?I think there must be some desgin methodlogy to make life easier.


Android Chat application - best practice

I'm building a chat application for Android and I thought about a programming design that include design patterns.


I want to know if my solution for doing it is the right thing to do or there is a better solution, that will be more efficient and easy in long term.


My application is currently have couple of basic actions/services that I can use:



  1. Monitoring

  2. Chat

  3. View

  4. Network


I thought to create the next classes:



  1. MainController - the main controller of the whole application(Mediator design pattern)

  2. MonitoringController - controller for only the monitoring issues, it only know the mainController and the other monitoring related classes.

  3. ChatController - same like MonitoringController, but chat issues related.

  4. ViewController - in charge for every change from/to the activities or fragments in the application, know the MainController.

  5. NetworkController - same like MonitoringController, but network issues related.


So, in other words, the mainController is my biggest class that know every other controller in the system, and that component is the only one that pass the events from one controller to the other. Every controller is implementing a dedicated interface that is used also in the mainController, so the mainController is implementing all the interfaces of all the controllers that "speak" with him.


This is how it's going to be for a top level design (of course that this will be larger in the next months, depends on the features I will add). enter image description here


Concerns:




  1. The mainController class will grow on every new feature, so that class will hold a lot of logic inside.




  2. The mainController will hold an instance of every other controller and vice verse - each controller will hold an instance of the mainController. So, I don't sure if this is a good thing from OOP perspective.




Advantages:




  1. I have only one controller(Main) that know every other controller, which I think is better from the other option of holding instance of each service that I need to use.




  2. Every controller don't know and doesn't care to which other controller to pass his callback, this is the mainContoller concern (fire and forget).




  3. Implementing new features is easy - I don't need to change a lot of code to support it, and I can add another controller if that feature is large enough.




Appreciate any thought or idea.


samedi 28 mars 2015

Object pool vs Object container

What is the difference between object container (such as tomcat / spring container) vs object pool? At a high level both manages the object life cycle. Only difference I note is that multiple objects are loaned from pool of the similar type while the container creates objects of different types which may be used in the application. Interested to know if there is something more to it...


What is the best way to create DTOs from entities and update entities from DTOs in a layered architecture?

Option 1:


At first I would make a call to my service layer, which served as an API for my core domain, to get a domain object or a list of domain objects and then pass them into the assembler which would construct the DTOs I needed for my view. The problem I have with this approach are cases where the domain object is large and I don't want to load in the whole object just to copy a few fields needed for the DTO (ie showing a list of summaries entities).


Option 2:


The next approach I used was to wire in a repository (for read-only purposes) into my assembler so that I could only query the database for the fields I need in the DTO. I can also use this repository when I get a DTO and need to use it to update and entity. For example, a DTO filled will values I need to update on my entity comes into my assembler, the assembler looks up the entity from a repository and then overlays the information from the DTO on the entity and then returns the entity. The controller then calls the service layer to save the entity that the assembler returned.


Option 3:


I could wire in the repositories directly into the controllers but something about exposing the repository in the controller seems wrong to me because the service layer should be handling transactions and security, but then again, if I put a repository in the assembler I am basically doing the same thing.


Any thoughts are welcome. I just want to understand pros and cons and what has worked well for others.


enter image description here


Backbone relation beetween models

I'm working on tool which will be used to create query for elasticsearch, where I have filters which are presented as panels.


I've got a collection of filters, and represtantation in UI, mostly everything works like a charm with pretty default backbone conventions.


I've got problematic situation when some filters need to have another filters in collection, so this makes some kind of relation beetween them. When I remove the main filter, all of the related filters should also be removed.


For example, filter 'type' can have value of 'picture' or 'movie'. When 'movie' option is selected I need also to set 'resolution', which is another filter in my elasticsearch query, but in client-side application is strictly related.


I read a lot about patterns, but Backbone.relational seems to be a bit overkill. I thought about adding references to the main filter ('type') of which another filters depends on it, or maybe create more nested structure which in the end (sending to ES) needs to be flattened out.


Totally don't know which solution is better, hope you guys can help me.


Trying to parse string values into an array after a pattern match

I have the following lines in a text file:



<Entry>
<Key argument="ComputerNames"/>
<Value type="string" argument="localhost,localhost,engine1,engine2"/></Entry>
<Entry>
<Key argument="BranchIDMultiple"/>
<Value type="int" argument="1"/></Entry>


I know how to find the line that has ComputerNames. I know how to read the next line as well. I need to parse the line as follows where the number of arguments can be dynamic. Parse output should be: my @result = $result[0]=localhost, $result[1]=localhost, $result[2]=engine1, $result[3]=engine2. There must be one argument however there can be any number above 1.

I'm not able to construct the right regex to accomplish the split. Any ideas? That would be really helpful. Thank You!


Decoupling in threaded environment java

I am facing this decoupling problem. Let me explain this with example:


Say i have different classes that uses some JAR. Now this JAR keeps on getting updated and we also need to update our system along with this too. Now if there is a slight change in this JAR i have to make changes to every class, so we decided to decouple it. But these classes call the JAR classes in such a way that they make an object of it, set some flag and on the basis of that derive results. Hence every object has its own importance in every method.


Let me explain this with simple example.


Say i have a class X



class X {
Base base;
public int getCalResult(int a, int b) {
base = new Base();
base.setA(a);
base.setB(b);
return base.getResult();
}

public int getCalResult2(int a, int b, int c) {
base = new Base();
base.setA(a);
base.setB(b);
base.setC(c);
return base.getResult();
}
}

class Base { This is some legacy class inside JAR so can't change this
int a, b, c, d;
public setA(int a) {
this.a = a;
}
public getResult() {
return a + b + c + d;
}
}


How to decouple this sort of structure and make it thread safe at the same time. Any pointers ? Any design patterns ?


I want that all the calls to JAR must be maintained in a single class, so that in case if there is change in JAR i only have to deal with single class and not all of them


Lua and patterns workaround

Good day, I ask if someone could help me for doing this in this way in lua. I have a string that contains name of files (including complete fullpath) separated by a "|", at the end is a number who indicated the current file (is for a player). So I just wanna keep it with the name of the files, but right now I have to use match function 2 times, one for separation and the other for cut it out the path. I wonder if and how is possible to do this with only one. Ex. I have:



local s = "W:\\Videos\\Tokyo Ghoul\\[Tokyo Ghoul][EP01]Tragedia.mkv|W:\\Videos\\Tokyo Ghoul\\[Tokyo Ghoul][EP02]Incubación.mkv|W:\\Videos\\Tokyo Ghoul\\[Tokyo Ghoul][EP03]Paloma.mkv|W:\\Videos\\Tokyo Ghoul\\[Tokyo Ghoul][EP04]Cena.mkv|2";


So i do:



for val in s:gmatch('(.-)|') do
print(val);
table.insert(list, {
type = "item",
icon = icon;
text = val:match(".*\\(.*)")});
end


I receive:



[Tokyo Ghoul][EP01]Tragedia.mkv
[Tokyo Ghoul][EP02]Incubación.mkv
[Tokyo Ghoul][EP03]Paloma.mkv
[Tokyo Ghoul][EP04]Cena.mkv


What I want is just use only one gmatch function. Hope someone can help me.


Java - making a class more generic

Here's some code I've inherited for a game. The sample code creates Armor.


At the moment to make some new Armor, you need to write a new class. E.g.



// Armor.java
public class Armor extends Item {
public int tier;

public Armor( int tier ) {
this.tier = tier;
}
}


and



// ClothArmor.java
public class ClothArmor extends Armor {
{
name = "Cloth armor";
}

public ClothArmor() {
super( 1 );
}

@Override
public String desc() {
return "Some Cloth Armor.";
}
}


How would you structure the code to make it more generic? It would seem obvious to just read from a text-based config file but I can see this running into problems when you wanted to create an Armor with special abilities for example.


Are there any resources or design patterns I can use to figure out how to proceed?


Creating only 1 instance or a Singleton

I used a class called 'City' & there will only be 1 city in the entire game; will it be beneficial to create an instance, if only 1 or a singleton.


The class itself will contain methods that won't all be static, & I've read that the singletons themselves consist of static attributes and methods only & can be bad practice or am I mistaken?


Pattern to abstract serialization\deserialization details from data classes

In my current PHP project I have a number of classes that are pure data-classes, similar what is called POCO in C# world (I omit getters\setters for now):



class MyEntity {
public $id;
public $name;
}


I need to serialize\deserialize such entities in different formats (for example, to/from JSON and XML) and keep serialization detailes out of the classes itself.


For deserialization a Builder pattern seems to be a good choice, but I'm not sure about serialization. I suppose I'm missing something obvious here.


vendredi 27 mars 2015

"chaining" a class to a main class

I couldn't think of the way to describer what I want to do, but I've seen several libraries and frameworks do it and I'm trying to figure it out for something I'm working on.


I'm working on an API client that has multiple classes. I have a main class that will contain all the OAuth stuff. I'd like the person using my API Client to be able to do something like so:



$api = baseAPI();

$user = $api->user->getUserProfile('user');

echo $user->Nickname;


user would be a class that has several methods. One could see an Admin object being accessible and a login object.


I hope I delivered my question well enough that someone understands what I'm trying to accomplish. I could try to explain it better if I did not.


Much appreciation.


what pattern should i use with transformers?

i have my transformer abstract class:



public abstract class Transformer<T, S> {

public abstract S transform(T object);

public abstract T revert(S object);

public List<S> transformArray(Collection<T> iterable) {
try {
List<S> transformed = new ArrayList<S>();
Iterator<T> iterator = iterable.iterator();
while (iterator.hasNext()) {
T element = iterator.next();
transformed.add(this.transform(element));
}
return transformed;
} catch (Exception e) {
e.printStackTrace();
return null;
}

}

public List<T> revertArray(Collection<S> iterable) {
try {
List<T> transformed = new ArrayList<>();
Iterator<S> iterator = iterable.iterator();
while (iterator.hasNext()) {
S element = iterator.next();
transformed.add(this.revert(element));
}
return transformed;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

}


And i want to have my DTOTransformer, which is like



public abstract class DTOTransformer<DTOREQ, OTHER, DTORES> {

Transformer<DTOREQ, OTHER> forwardTransformer;
Transformer<OTHER, DTORES> backwardTransformer;

// Not overriding, since isn't and hasn't a transformer
public OTHER transform(DTOREQ object) {
return forwardTransformer.transform(object);
}

// Not overriding, since isn't and hasn't a transformer
public DTORES revert(OTHER object) {
return backwardTransformer.transform(object);
}

}


The problem is that i have not actually any implementation for backwardTransformer and forwardTransformer's transform() method. What i want is that when i create a subclass from DTOTransformer, for example, ClientDTOTransformer then i have to implement the transform and revert methods (which are not the same of the methods that Transformer's class offers since i have a "triangular" transformation).


I have already tried using the adapter pattern but i couldn't implement it.


Do you know how i could do this? Or if you know a better way to do this, i am open to suggestionsRegards!


Patterns and practices for offline-first mobile apps

Please help me with a starting point to available patterns and practices for building reliable offline-first mobile apps. Offline-first means that:



  1. app is client-server

  2. a mobile app is able to function without Internet connection. User can CRUD data.

  3. once user enters in Internet enabled area - app synchronises with the server.

  4. user uses the app on multiple devices so that there should be kind of synchronisation mechanism supporting versioning. The simplest one.


Thanks!


What is the proper design for interacting with controls using MVVM where I need to do calculations based on XAML controls?

I am still a bit green in WPF. I am refactoring a sizable applications where all the work was done in the code behind. I am refactoring to use MVVM.


A bit about the application: This application contains a single window, the single window and the pertinent pieces of the XAML are below:



<Grid>
<Border Style="{StaticResource ClipBorderStyle}" Name="ImageBorder">
<Grid Style="{StaticResource ClipGridStyle}" Name="ImageGrid">
<Image Name="KeyImage" Style="{StaticResource MainImageStyle}" Source="{Binding ImageSource}" Cursor="{Binding ImageCursor}"></Image>
<Canvas Name="KeyCanvas" Height="{Binding Source=KeyImage, Path=Height}" common:CanvasAssistant.BoundChildren="{Binding CanvasControls}"></Canvas>
</Grid>
</Border>
</Grid>


When the user clicks on the image, I drop a control onto the Canvas at the location where the user clicked. There can be many objects, and multiple control types. Currently I have a view model defined for each of the different control types and I keep an observable collection of them in a main view model. I am about half way through refactoring, and am realizing I still have a ton of work being done in the code behind, and am modifying the objects in the DataContext a lot. I am curious how I can move a lot of this out of the code behind into a more structured format (maybe into the view model, maybe another pattern). If it were simply modifying data, this would not be a problem, but in many cases I need to do transforms, and track the location on the image. The user can interact with the application using both their mouse and their keyboard (click to select an object, left arrow to move it, etc).


The Core Questions When I have to to something like any of the following:



private Point TranslateImageCoordinatesToParentGrid(Point pointOnImage)
{
return KeyImage.TransformToVisual(ImageGrid).Transform(pointOnImage);
}


OR



private void Marker_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
var Marker = (Marker)sender;
if (Marker.IsMouseCaptured)
Marker.ReleaseMouseCapture();
}


OR



private void Marker_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
var Marker = (Marker)sender;
Marker.CaptureMouse();
_dataContext.SelectedObject = Marker;
Marker.Focus();
}


OR



private void controlMarker_OnMouseMove(object sender, MouseEventArgs e)
{
var controlMarker = (controlMarker)sender;
var controlDataContext = ((controlMarkerObject)controlMarker.DataContext);
if (!controlMarker.IsMouseCaptured) return;

var tt =
(TranslateTransform)
((TransformGroup)controlMarker.RenderTransform).Children.First(tr => tr is TranslateTransform);
var currentMousePos = e.GetPosition(ImageGrid);

// center mouse on controlMarker
currentMousePos -= controlDataContext.CenterOffsetFromTopLeft;

var v = _dataContext.Start - currentMousePos;
tt.X = _dataContext.Origin.X - v.X;
tt.Y = _dataContext.Origin.Y - v.Y;


var currentImagePos = TranslateImageGridCoordinatesToChildImage(currentMousePos + controlDataContext.TopLeftOffset);

controlDataContext.ImagePosition = currentImagePos;
}



  1. Where is the appropriate place for this logic that interacts with both the view and the view model (and view models for the controls)?

  2. Is the code behind the appropriate place for this?

  3. Should I be using this eventing model where I defined the mouse events, or convert them to ICommands?

  4. Is there a better/cleaner pattern to use for an application like this?


Insert regex pattern into db table

I want to insert regex pattern into the table as a value. For eg : INSERT INTO table VALUES("r|h[at]"). So when I execute SELECT * from table where name == "hat"; I'll get 1 row. How can I insert regex pattern into a column as value?


JavaScript: Why so much abstraction/interfacing in Addy's Observer Pattern?

I'm working through the design pattern example for the Observer Pattern in Addy Osmani's book, "JavaScript Design Patterns". My question is why is it important that there are so many levels of abstraction in his implementation of the pattern?


For instance, in his example, just to add an observer ('push' an observer to an array), this involves:



  • using the native push() method.

  • creating a ObjectList.add() method.

  • inheriting/extending the ObjectList object with the Subject object.

  • creating the Subject.addObserver() method which to be used as an interface, but which uses the ObjectList.add method under the hood.

  • extending the Subject.addObserver() method for new objects.

  • Implementing it by calling the addObserver() method on the newly extended object.


Here's the code example for the design pattern in its entirety:



function ObserverList(){
this.observerList = [];
}

ObserverList.prototype.add = function( obj ){
return this.observerList.push( obj );
};

ObserverList.prototype.count = function(){
return this.observerList.length;
};

ObserverList.prototype.get = function( index ){
if( index > -1 && index < this.observerList.length ){
return this.observerList[ index ];
}
};

ObserverList.prototype.indexOf = function( obj, startIndex ){
var i = startIndex;

while( i < this.observerList.length ){
if( this.observerList[i] === obj ){
return i;
}
i++;
}

return -1;
};

ObserverList.prototype.removeAt = function( index ){
this.observerList.splice( index, 1 );
};

function Subject(){
this.observers = new ObserverList();
}

Subject.prototype.addObserver = function( observer ){
this.observers.add( observer );
};

Subject.prototype.removeObserver = function( observer ){
this.observers.removeAt( this.observers.indexOf( observer, 0 ) );
};

Subject.prototype.notify = function( context ){
var observerCount = this.observers.count();
for(var i=0; i < observerCount; i++){
this.observers.get(i).update( context );
}
};

// The Observer
function Observer(){
this.update = function(){
// ...
};
}


And here's the implementation/usage:


HTML



<button id="addNewObserver">Add New Observer checkbox</button>
<input id="mainCheckbox" type="checkbox"/>
<div id="observersContainer"></div>


Script



// Extend an object with an extension
function extend( extension, obj ){
for ( var key in extension ){
obj[key] = extension[key];
}
}

// References to our DOM elements

var controlCheckbox = document.getElementById( "mainCheckbox" ),
addBtn = document.getElementById( "addNewObserver" ),
container = document.getElementById( "observersContainer" );


// Concrete Subject

// Extend the controlling checkbox with the Subject class
extend( new Subject(), controlCheckbox );

// Clicking the checkbox will trigger notifications to its observers
controlCheckbox.onclick = function(){
controlCheckbox.notify( controlCheckbox.checked );
};

addBtn.onclick = addNewObserver;

// Concrete Observer

function addNewObserver(){

// Create a new checkbox to be added
var check = document.createElement( "input" );
check.type = "checkbox";

// Extend the checkbox with the Observer class
extend( new Observer(), check );

// Override with custom update behaviour
check.update = function( value ){
this.checked = value;
};

// Add the new observer to our list of observers
// for our main subject
controlCheckbox.addObserver( check );

// Append the item to the container
container.appendChild( check );
}


Now I compared his implementation with other implementations of the same pattern (books and blogs). And it seems that Addy adds a ton more abstraction than other implementors of the observer pattern. The question is, why? Couldn't this be done more simple? Does this achieve a greater degree of decoupling? If so, how exactly is that? Doesn't the design pattern itself create a decoupling?


Loop through a two-dimensional array with actions on change of a value in a column

A very common problem while looping throug a two-dimensional array (representing a table) is to have an action to execute only when a value in a column changes. To give a concrete example:


Output some HTML from tabular data.

Given this table



category | product
------------------
Vehicles | Bike
Vehicles | Car
Clothes | Shirt


Create HTML like this:



<h1>Vehicles</h1>Bike<br />Car<hr />
<h1>Clothes</h1>Shirt<hr />


To solve the problem, I could change the code like this:



$current_category = '';
$first = true;
foreach($table as $row){
if ($row['category'] != $current_category){
if(!$first){
// after a group
$echo '<hr />';
}
// before a group
echo '<h1>'.$row['category'].'</h1>';
} else if (!$first){
// inside a group
echo '<br />';
}
// foreach line
echo $row['category'];
$current_category = $row['category'];
$first = false;
}
// after a group, duplicated code
$echo '<hr />';


I feel that this is more complicated than necessary. Also there is code duplication for what I want to execute after the group.


The code for this relatively simple requirement is already convoluted. It get's almost impossible, if we need to watch two changing columns in the array.


I'm looking for an approach of this problem that keeps the code easy to read, while being able to loop through the array and execute some code



  • foreach line

  • before a group of lines

  • after a group of lines

  • inside a group of lines


I hope the question is clear, even though I have some difficulty to explain this general problem in simple terms.


Is there a way to prototype a namespace in a limited scope?

I have a prototyped function that i would like to use it in a limited scope in order to provide it with a jquery plugin.



//Prototype
function StringBuilder(str) {
this.value = str;
}
StringBuilder.prototype.append = function (str) {
this.value = this.value + str;
return this;
};

//jQuery plugin with Revealing module pattern
jQuery.Rut = (function () {
//i would like to be able to use StringBuilder only in this scope
helloWorld = new StringBuilder('Hello');
helloWorld.append(' World');
})(window);


Is that possible?


Thanks


Node express with Kue - producer consumer design pattern advise

I'm writing a node application that pops messages onto a Kue job queue from REST calls processed by Express. I then want a number of worker processes running across multiple threads and servers to consume these messages and perform their long running tasks.


I have successfully written a standalone app that seems to work OK, but I'm confused about how I can distribute this across multiple servers. I've been looking into PM2 which seems to be the best way to load balance node processes.


My questions are..



  • Would it be best that express/Kue message producer app be a separate app to the workers apps? So for instance, one Express app running on one server, then a worker app running separately on all the servers?

  • Can I stop/start all/some of the workers across different servers with a single instance of PM2? Or, do I need an instance of PM2 running on each server?

  • Can anyone offer up a better solution?


The worker processes are basically copying/moving large files to and from remote servers, hence the need for distribution across multiple servers instead of just threads, for disk i/o and bandwidth performance.


You input is much appreciated.


Design pattern for having custom processing in a generic function

Here is the use case:


I want to develop a rest api to send email so that anyone who want to send email to anybody, can use this api.


Now say one client want to send an email BUT before sending the email, he want to do some book keeping. Say, want to store the sender, receiver information in DB. However, not every client want to store those information.


So, in this case which design pattern will be perfect? I am thinking of using strategy but before that I want to evaluate the options. It would be great help, if anyone provides some input


Aggregating-based architecture issues

i'm need your help again.


I have an document viewer application what can read two different kinds of documents:



  1. Special one (based on PDF, with custom header)

  2. Standart one ("raw" PDF).


With raw PDF viewer should acts like any other one.

With custom - execute some additional actions during it's opening,

which are not available to raw PDF.

These actions should be available later in the application's menu only. And only for custom document.



Project OOP architecture (designed by other man) looks like this:



class GenericDocument
class PdfLibDocument
class CustomDocumentHighLevel
class CustomDocumentLowLevel


I.e.



class GenericDocument
{
SmartPointer< PdfLibDocument > m_document;
...
};


and so on.


Custom document has much specific functionaly:



class CustomDocumentLowLevel
{
public:
void DoSomeBlackMagic();
...
// Another black magic
};


The problem occurs then i need to "pull" some low-level method from CustomDocumentLowLevel to GenericDocument (to show in app menu) - because i need to add this method to ALL FOUR classes!

And probably in the future i need to "pull" more methods from custom document.

Looks like this software architecture is bad choice in such case, isn't it?


So i need find a way to refactor this code. Should i replace aggregating with inheritance? Introduce interfaces?


jeudi 26 mars 2015

Java regex for # delimited record

I have text rows of following format. It is a record of fixed segments of upto 6 columns delimited by comma and which can repeat one or more times. The segment separation is delimited by #


Example:

single record in row:



AA,123,SRC,DES,X,ABCD123


two records in row:



AA,123,SRC,DES,X,ABCD123#AB,234,SRC,DES,X,ABCD234


I'm looking for build reg-ex for this structure pattern. So far I've build partial reg-ex based on my requirements (which will be case-insensitive).



regexp ="^([a-z]{2},[a-z0-9]{1,5},[a-z]{3},[a-z]{3},[a-z]{1}(,[a-z0-9]{1,25})?)+$"


What I'm struggling with is finding the repeated segments. Here is a link that has some delimiter expression information but I'm unable to incorporate it. Can someone help me understand?


JAVA RegEx on _ delimited string


python JSON complex objects (accounting for subclassing)

My question can be described as follows:


what is the best practice for serializing/deserializing complex python objects into/from JSON, that would account for subclassing and prevent multiple copies of same objects (assuming we know how to distinguish between different instances of same class) to be stored multiple times?


In a nutshell, I'm writing a small scientific library and want people to use it. But after watching Raymond Hettinger talk Python's Class Development Toolkit I've decided that it would be a good exercise for me to implement subclassing-aware behaviour. So far it went fine, but now I hit the JSON serialization task.


Until now I've looked around and found the following about JSON serialization in Python:



Two main obstacles that I have are accounting for possible subclassing, single copy per instance.


After multiple different attempts to solve it in pure python, without any changes to the json representation of object, I've ended up understanding, that at a time of deserializing json, there is now way to know instance of what class heir was serialized before. So some mention about it shall be maid, and I've ended up with something like this:



class MyClassJSONEncoder(json.JSONEncoder):
@classmethod
def represent_object(cls, obj):
"""
This is a way to serialize all built-ins as is, and all complex objects as their id, which is hash(obj) in this implementation
"""
if isinstance(obj, (int, float, str, Boolean)) or value is None:
return obj
elif isinstance(obj, (list, dict, tuple)):
return cls.represent_iterable(obj)
else:
return hash(obj)

@classmethod
def represent_iterable(cls, iterable):
"""
JSON supports iterables, so they shall be processed
"""
if isinstance(iterable, (list, tuple)):
return [cls.represent_object(value) for value in iterable]
elif isinstance(iterable, dict):
return [cls.represent_object(key): cls.represent_object(value) for key, value in iterable.items()]

def default(self, obj):
if isinstance(obj, MyClass):
result = {"MyClass_id": hash(obj),
"py__class__": ":".join([obj.__class__.__module, obj.__class__.__qualname__]}
for attr, value in self.__dict__.items():
result[attr] = self.represent_object(value)
return result
return super().default(obj) # accounting for JSONEncoder subclassing


here the accounting for subclassing is done in



"py__class__": ":".join([obj.__class__.__module, obj.__class__.__qualname__]


the JSONDecoder is to be implemented as follows:



class MyClassJSONDecoder(json.JSONDecoder):
def decode(self, data):
if isinstance(data, str):
data = super().decode(data)
if "py__class__" in data:
module_name, class_name = data["py__class__"].split(":")
object_class = getattr(importlib.__import__(module_name, fromlist=[class_name]), class_name)
else:
object_class = MyClass
data = {key, value for key, value in data.items() if not key.endswith("_id") or key != "py__class__"}
return object_class(**data)


As can be seen, here we account for possible subclassing with a "py__class__" attribute in json representation of object, and if no such attribute is present (this can be the case, if json was generated by another program, say in C++, and they just want to pass us information about the plain MyClass object, and don't really care for ingeritance) the default approach to creating an instance of MyClass is pursued. This is, by the way, the reason why not a single JSONDecoder can be created all obejcts: it has to have a default class value to create, if no py__class__ is specified.


In terms of a single copy for every instance, this is done by the fact, that object is serialized with a special json key myclass_id, and all attribute values are serialized as primitives (lists, tuples, dicts, and builtint are preserved, while when a complex object is a value of some attribute, only its hash is stored). Such approach of storing objects hashes allows one to serialize each object exactly once, and then, knowing the structure of an object to be decoded from json representation, it can look for respective objects and assign them after all. To simply illustrate this the following example can be observed:



class MyClass(object):
json_encoder = MyClassJSONEncoder()
json_decoder = MyClassJSONDecoder()

def __init__(self, attr1):
self.attr1 = attr1
self.attr2 = [complex_object_1, complex_object_2]

def to_json(self, top_level=None):
if top_level is None:
top_level = {}
top_level["my_class"] = self.json_encoder.encode(self)
top_level["complex_objects"] = [obj.to_json(top_level=top_level) for obj in self.attr2]
return top_level

@classmethod
def from_json(cls, data, class_specific_data=None):
if isinstance(data, str):
data = json.loads(data)
if class_specific_data is None:
class_specific_data = data["my_class"] # I know the flat structure of json, and I know the attribute name, this class will be stored
result = cls.json_decoder.decode(class_spcific_data)
# repopulate complex valued attributes with real python objects
# rather than their id aliases
complex_objects = {co_data["ComplexObject_id"]: ComplexObject.from_json(data, class_specific_data=co_data) for co_data in data["complex_objects"]]
result.complex_objects = [c_o for c_o_id, c_o in complex_objects.items() if c_o_id in self.complex_objects]
# finish such repopulation
return result


Is this even a right way to go? Is there a more robust way? Have I missed some programming patter to implement in this very particular situation?


I just really want to understand what is the most correct and pythonic way to implement a json serialization that would account for subclassing and also prevent multiple copies of same object to be stored.


Thanks in advance!


How many :attr_accessor are too many for a class?

How many :attr_accessors are too many for a class, or, what is the "right" number of such methods (if there is such a thing as a "right number")?


So, as a trivial example, take



class Example
:attr_accessor :a, :b, :c, :d, :e, :f, :g, :h, :i, :j, :k
# instance methods here...
end


Obviously, sometimes a large number of such variables and the corresponding accessors are necessary (perhaps you'd see this in an ActiveRecord::Model); but I'm looking for a decent heuristic to use when determining whether to refactoring based on the raw number of instance variables within a class.


Answers highlighting and/or summarizing articles, presentation, books, etc. on this design issue are much appreciated.


Partitioned IOC Containers

I'm currently porting a large WIN app so I can extend it out to MVC. One of the principals is that it support multiple DALs which is dynamically bound by fluent config. for example



interface IDataStore
{
}

class SqlRepository :IDataStore
{
//do sql stuff
}

class VistaDBRepository : IDataStore
{
//do vista db stuff
}


and finally



class WCFClientRepository :IDataStore
{
//do WFC stuff
}


to consume this implementation in the business logic it goes like this



public IDataStore GetCurrentStore()
{
get
{
switch(EnterpriseConfiguration.Instance.ActiveProvider)
{
case "MSSQL":
return new SqlRepository();
case "VistaDB":
return new VistaDBRespository();
case "WFC":
return new WCFReposity();
}
}
}

void GetDate()
{
using(IDataStore db = GetCurrentStore())
{
//do something with db
}
}


with that there is a connection listener that will monitor between the primary db provider (SQL) and the mobile provider (WCF) if the connection drops or is not available with the primary provider it will elect the secondary provider (WFC) as primary. this is to support mobile users and works great, user who are inside the LAN go directly to SQL and will auto switch to WFC when they leave.


finally VistaDB is used as a persistance store (plugin info, form metadata, locality, countries etc....)


I want to replace this pattern with a IOC container, my idea would be to build up a container for each defined IDataStore that can bind to a name, in turn get consumes as such



SQLReposity db = Container.Resolve<IDataStore>().ContainerName("MSSQL");
VistaDBReposity db = Container.Resolve<IDataStore>().ContainerName("VistaDB");
WFCReposity db = Container.Resolve<IDataStore>().ContainerName("WCF");


Any ideas on would to build out the container using Unity or StructureMap?