lundi 29 février 2016

What is the purpose of protocols in objective c or swift if all methods are optional (such as uitextfielddelegate)

So I just went through the pain of learning objective c and swift (it is actually been a great experience so far) and while I get what the purpose of protocols serve (to have a type conform to a set list of methods or/and properties), I don't understand what the purpose of a protocol with all optional methods.

if all methods are optional in a protocol, why would you conform to the protocol instead of just writing the functions from scratch in your class? I don't see what the benefit or purpose of conforming to the protocol is in this case.

Are the optional methods there just as suggestions of functionality that could be implemented? Thanks again for any help.

Creating instances of revealing module pattern

I am trying to understand how create different instances of revealing module pattern. I have a code block below and create module1 and module2 instances of myRevealingModule and setting their name variables.But name of module1 is overwritten by module2. How can i have different name values for module1 and module2? What am i missing? Thanks!

var myRevealingModule = (function(){

    var name = 'Default';

    function setName (nameVal) {
       name = nameVal;
    };

    function getName () {
       return name;
    };

    return {
        fullName: name,
        set: setName,
        get: getName
    };

}());
var module1  = myRevealingModule;
module1.set("module1 name");
var module2  = myRevealingModule;
module2.set("module2 name");

How can create an instance of class into an other class whithout invoking destructor method in c++

I try to instantiate my class A (its goal is to notify other classes observers by a result ) into class B and after adding the observers the class A call its destructor and delete these observers . What I want is to instantiate my class A into class B without invoking the destructor. I think about a handler class which will be singleton but nothing is clear in my mind. Please help me. I code with c++.

My code looks like this:

Class A{
  A(){addListeners()}
  ~A(){deleteListeners()}
};

and

Class B{
  B()
};

and out of the declaration of B I introduce a method configure that returns an instance of B.

shared_ptr<B> configureB(){
  A = new A(); B->notifyListeners()
}

How to implement encapsulation for this simple scenario?

I have a js lib file whose variable I don't want to be directly available to other files. Example:

My first file called lib.js is as follows :

lib.js

var foo = 90;

function printFoo(){
    console.log(foo)
}

In the second file below which calls lib.js, I want printFoo() work fine but I also want direct access to variable foo from lib.js being prevented. How can I do that?

<script src="lib.js"></script>
<script>
  console.log(foo);// I don't want foo of lib.js being accessible here

  printFoo();// but i want this line to display the value of foo from lib.js
</script>

How to design an application broker and trades reconciliation

I want to design a stock broker and trade calculation program in java; but unable to see any sample app or methods to start with. I am interestedin financial domain problem solving. Please help me to get an idea.

I have done my homework so far here... Design an application for Stock Brocking Reconciliation

Difference between interceptors and decorators

Are there any differences between interceptors and decorators in Java? Strictly speaking, can I implementing things with decorators which are not possible with interceptors and vice versa?

Except the problem that I would have to examine the method name to add method-specific behavior in an interceptor:

Interceptor:

@Nice
@Interceptor
public class NiceGreeterInterceptor {
  @AroundInvoke
  public Object decorate(InvocationContext ic) throws Exception {
    Method method = ic.getMethod();
    String methodName = method.getName();
    Object result = ic.proceed();
    if (methodName.equals("greet")) {
      return "NEW " + result;
    }
  }
}

Decorator:

@Decorator
public class GreeterDecorator implements Greeter {
  @Inject
  @Any
  @Delegate
  private Greeter greeter;

  @Override
  public String greet() {
    return "NEW " + greeter.greet();
  }
}

Design an application for Stock Brocking Reconciliation

I want to write a program on Stock Brock/trading Reconciliation application. There is a stock brocking firm holdings traders/investors profile who have invested in various company’s stocks and taken number of shares.

Each stock having per second stock price.

 Investors buy number of share from particular company.
 Investor buy/sell shares basis on day calculation (intraday) stocks.
 Investors has to pay brokerage charges 2$ on per transaction.
 Reconcile the profit/loss of investors by trading the stocks.

My Designed classes are;

// Stock class

public class Stock {

    public String companyName = null;
    public String stockRating = null;
    public int price = 0;
    public int numberOfShares = 0;

    public Stock(String companyName, String stockRating, int stockPrice, int numberShares) {
        // TODO Auto-generated constructor stub
        this.companyName = companyName;
        this.stockRating = stockRating;
        this.price = price;
        this.numberOfShares = numberShares;
    }

    public String getCompanyName() {
        return companyName;
    }
    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }
    public String getStockRating() {
        return stockRating;
    }
    public void setStockRating(String stockRating) {
        this.stockRating = stockRating;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    public int getNumberOfShares() {
        return numberOfShares;
    }
    public void setNumberOfShares(int numberOfShares) {
        this.numberOfShares = numberOfShares;
    }

}

//Stock Holder class

public class ShareHolder {

private String shareHolderName;
private String uidaiNo;
private String bankDetails;

public String getShareHolderName() {
    return shareHolderName;
}
public void setShareHolderName(String shareHolderName) {
    this.shareHolderName = shareHolderName;
}
public String getUidaiNo() {
    return uidai;
}
public void setUidaiNo(String uidai) {
    this.uidai = uidai;
}
public String getBankDetails() {
    return bankDetails;
}
public void setBankDetails(String bankDetails) {
    this.bankDetails = bankDetails;
    }

}

//StockPortfolio class

public class StockPortfolio {

private static final int PORTFOLIO_SIZE = 10;
private Stock [] stocksPortfolio;

 public Stock [] getstocksPortfolio(){
      return stocksPortfolio;
  }

  public void setstocksPortfolio(Stock [] value){
      stocksPortfolio = value;
      }
}

//Main class

import java.util.Scanner;

public class StockBrokingReconcilation {

    private static StockPortfolio stockPortfolio;
    private static final int PORTFOLIO_SIZE = 10;

    private static void stockReconciling() {
      for (int i = 0; i<PORTFOLIO_SIZE; i++){
        Scanner console = new Scanner(System.in);

        System.out.println ("Stock's name:");
        String companyName = console.next();

        System.out.println ("Stock's rating");
        String stockRating = console.next();

        System.out.println ("Stock's price:");
        int stockPrice = console.nextInt();

        System.out.println ("Numbers of shares: ");
        int numberShares= console.nextInt();

      stockPortfolio.getstocksPortfolio()[0] = 
        new Stock(companyName, stockRating, stockPrice, numberShares);
     }
    }
}

So, can any buddy help me to design this problem in better way as requirements are given above. If there is a sample program related to my title of the problem, please share the link. I am very new to design thinking.

using helper classes Versus using service classes inside my asp.net mvc web application

I am working on asp.net mvc-5 web application, and i am separating my code into View & Model & Controller classes, i also add a repository class, so i do not directly initiate my context object inside the action methods, instead i initiate the context object from repository and reference the repository from the action methods.

But seems i can add an extra layer to my MVC application by either adding helper classes to my Controller classes, or adding a new service classes.

so not sure when to use Repository Vs Service Classes Vs Helper Classes.. i can find many articles and documentations about these approaches ,, but can not find specific mvc-related documentations which list when to use each approach inside asp.net mvc??

Print the reverse of an arrow pattern in Python

Right now this code gives me:

*
 *
  *
   *

And I can't seem to figure out how to get the arrow finish off (in other words reversing the first print):

*
 *
  *
   *
   *
  *
 *
*

--

columns = int(input("How many columns? "))

while columns <= 0:
    print ("Invalid entry, try again!")
    columns = int(input("How many columns? "))

x = 1
for x in range(columns):
        for x in range(x):print(" ", end="")
        print("*")

Concerning the Web application architecture what's the difference between domain classes and business classes?

I want to architect my asp.net web form application like this :

1-DB
2-Data Access Layer(Using ORM[EF])
3-Repository/Unit Of Work (Pattern)
4-Business Layer
5-Service Layer
6-UI

Right now my primitive solution looks like this :

Just two class libraries :

  • DAL (Data Access Layer) where my EF resides in.
  • Domain Classes (auto generated) with their equivalent partial classes.

enter image description here


My questions concerning this design :

  1. Should I put my business logic in a new layer or just in the domain classes layer where each business belong to the related domain class Or put my business logic in the code behind of my web pages ?
  2. Could some one clarify what's the difference among those terminologies in the design perspective (POCO,Domain Class,BusinessClass)?

how can i design a single registration page with both email and mobile number verification in it?

I am trying to design a page wherein the user has to get his Email ID as well as cellphone number verified. I will be using OTP for both email and cell number verification. Here is the basic design - enter image description here

I personally feel that this page may have complex functionality to be implemented in the back end as well as it might make a user experience perhaps uncomfortable. Any suggestion?

Software design : Hiding the system from the user through packages

For Software Design class, we are required to design and implement a Bug Tracking system which undergoes several iterations.

We are taught to disconnect the back end (the bug tracking system) from the front end (UI) using a controller layer. We understood that if someone were to use our (back end) software and were to create a UI for it, (s)he should only be able to access the system via the controller layer. In other words, the classes in the software should be invisible.

Currently we are enforcing this by grouping our classes in packages and using the default/package access modifier.

I was wondering if this is the way to go or if there's a documented design pattern to achieve this encapsulation of front- and back-end? Are there any textbook examples on this?

How to print triangle pattern in java

Below are the snippet of the code. i want to print pattern like that.

1
2*3
4*5*6
7*8*9*10
7*8*9*10
4*5*6
2*3
1

Code

public class Pattern2 {

    public static void main(String[] args) {
        int p=1;
        for(int i=1;i<=4;i++){

            for(int j=1;j<=i;j++)
                System.out.print(""+p++);
            //p++;
            System.out.println("");

        }
       for(int i=4;i>=1;i--){
           //System.out.print("iii");
            int n=4;
            for(int j=1;j<=i;j++)

                System.out.print(p-n+j-1);
            n--;

            //n++;
            //System.out.println(p);
            System.out.println("");
        }
    }
}

dimanche 28 février 2016

Ways to implement Null Object Pattern

Till now I have seen everywhere that the steps to create Null Object Pattern, for example in BST to remove null checks, are as follows:

  1. Create an interface Node

  2. Create two classes implementing the interface Node. One of which will be real_Node and other will be null_Node.

  3. Using those classes, null checks can be removed in BST class while creating the tree.

Now I want to know that, are there other ways to do this, e.g., Can we implement Null Object Pattern without interface using only classes, i.e. in the above step (1.) can we use Node class instead of Node interface

How does this module pattern in Javascript work? [duplicate]

This question already has an answer here:

I am learning about module patterns, a bit confused about how they behave.

So, I have this simple module,

var testModule = (function() {

    //private counter
    var counter = 0;
    return {
        //public methods
        incrementCounter: function () {
            console.log(counter++);
        },
        resetCounter: function () {
            counter = 0;
        }
    };
}());

From what I have understood till now(and please correct me if I am wrong), the above function will be invoked immediately(because of the parentheses).

When it runs, it returns an object, which contains only the public methods defined.

So, in the end, after executing the above function our code will look something like this internally (Please, please correct me if I am wrong. this is only my understanding of its behaviour)

testModule_ = {
    incrementCounter: function () {
        return counter++; 
    },
    resetCounter: function () {
        console.log("counter value prior to reset: " + counter);
        counter = 0;
    }
};

The thing which I don't understand is, when we access the public methods as testModule.incrementCounter() or testModule.resetCounter(), how do they get the value of the counter, as testModule now doesn't have counter?

I can see it gets the value for the first time, as when that anonymous function was self invoked, it did increment counter and reset the values. But what about second time, from where it gets the value of counter?

I hope I am clear. Thanks in advance.

Client-side added behavior

'm trying to design a system where a class would be defined in a project, be referenced in another and have new functionalities in the latter. Is there a pattern for this?

Context: I have a game that has items in a common project. Both the server and client reference this same project so I can have the item StaffItem in both the server and client, making it easier to serialize and deserialize between the two. The problem is, I can't redefine the StaffItem class in the client, since it will change the server's perspective of this class. I'm trying to find a nice way to add, for instance, the rendering to the client-side view of the class (added code for textures and all that).

I'm almost at the point of giving up and simply putting the rendering code in the common project, and stubbing it for the server. Any pointers (hehe) would be appreciated.

Nested decorators methods

I'm now studying the decorator pattern, here some example code (PHP) :

abstract class component{

  public function drawShape(){};

}

class concreteComponent extends component{

   public function drawShape(){//code};

}

class decoratorComponent extends component{

  private $component;

  public function __construct($component){ $this->component=$component; }

  public function drawShape(){

      $this->component->drawShape();

  }

}

class borderDecorator extends decoratorComponent{

  public function drawShape(){

    $this->drawBorder();
    $this->component->drawShape();

  }

  public function setBorder(){};
  public function drawBorder(){};

}

class bgColorDecorator extends decoratorComponent{

  public function drawShape(){

    $this->drawBgColor();
    $this->component->drawShape();

  }

  public function setbgColor(){};
  public function drawBgColor(){};

}

Ok, now:

$test=new concreteComponent();
$border=new borderDecorator($test);
$border->setBorder(10);
$bgColor= new bgColorDecorator($border);
$bgColor->setBgColor(#000);

Now I have a component decorated with a #000 bg color and a 10(some unit) border.

With

$bgColor->drawShape(); 

it means drawBgColor + drawBorder + drawShape and all right, BUT:

How can I modify or remove the border??

$bgColor-> ???

The bgColor class can't access directly the border methods...

Thanks

syntax for the module pattern in Javascript

I am learning module pattern in Javascript, and have come across these two ways to create a module:

var Module = (function () {
  // code
})();

var Module = (function () {
 // code
}());

is there a significant difference in these two approaches? if not, which is considered the better practice? Thanks.

the right design approach for creating different User classes

I am trying to create chat app that will have different users:simple user, vip users and etcetera.

all types of users will have the data that simple user have, like:name,password,email and so on however all the other users type have uniqe options only to them.

I thought to create class SimpleUser that will have the basic functionality that achieved by using private variables, getters/setters,and so on, while all other user types will have their own classes that extends the SimpleUser class and add their uniqe functionality.

but after I seen this article Do subclasses inherit private fields? its just doesn't seems the right approach.

I am not sure that using Interface to provide optional functionality will help, because i still have private variabels in each user type that I access using getters/setters.

also currently I am cheking in every screen what the type of the user (in order to choose the rigth options for him), its seems clunky, is there a way to check the type of the user only once (when the user logs in) and in all screens simply use his uniqe functions?

  • what is the correct way to design my classes?

  • is their one solution for both my problems?

Use MVP "Passive" to centralize UI code

I have two applications, each providing the same business services to different set of users. Still there are variances in business validations and user interface.

Regarding UI:-

  • UI is based on Asp.Net Web forms
  • Applications include pages with different layout
  • Applications shares almost same functionality.

I plan to use MVP pattern to centralize the common code as possible.

Projects are Common, App1, App2.

  • Common: includes
    1. IUpdateView : Common API goes here
    2. UpdatePresenter : Centralized code goes here.


  • App1: includes

    1. IUpdateViewApp1 : IUpdateView

      Specialized API is added to IUpdateViewApp1

    2. UpdatePresenterApp1 : UpdatePresenter
      Specialized code goes here UpdatePresenterApp1

    3. UpdatePage.aspx : IUpdateViewApp1
      The page creates the presenter and passes it self as IUpdateViewApp1

Is there a simpler \ better solution to centralize the code of UI in such case.

How to go about solving this (Design patterns)

I have a billing system in which different type of customers have different type of discount schemes. And for a given bill, a net payable amount should be generated based on the type of the customer and the product.

And there are few rules too. Like :

•If the user is an employee of the store, he gets a 30% discount

•If the user is an affiliate of the store, he gets a 10% discount

•If the user has been a customer for over 2 years, he gets a 5% discount.

•For every $100 on the bill, there would be a $ 5 discount (e.g. for $ 990, you get $ 45 as a discount).

•The percentage based discounts do not apply on groceries ...

I had few Ideas in my mind. 1st bet is to think about a decorator pattern :

Customer <<Interface>>     

|                       
CustomerImpl  



DiscountDecorator <<AbstractClass>> imp Customer

 |             |            |           |
AffiDiscount   StoreEmp   OverTwoYears   AnyOtherDisc
               Discount     Discount       Discount
Items  { 
//? ? :/
}

But then the Discounts are dependent on Items as well.

What are my options?

  • extend Customer Interface with an Item Interface to keep track on type of item?
  • Pass List of Items to the discount classes. ... How to properly have co-relation with Customer and Item classes so that I can decorate them together?

samedi 27 février 2016

Which design patterns should I investigate for translating models?

I am writing a program that reads data from Model A into another Model B, and vice versa. For example, let's say model A contains class Cat, and model B contains class Kitty. Cat is roughly equivalent to Kitty, but there is some translation required. My code will need to do that translation.

A caller of my code should be able to invoke something like, mycode.push(cat), or Cat cat = mycode.pull();

What design patterns are recommended for this scenario?

ASP.NET MVC is from "Make it Very Complicated"?

I am too stupid for such complex architecture...

ASP.NET MVC, Model, View, Controller, ViewModel, Entity Framework, Bootstrap, JavaScript, Razor, Repository pattern, Unit of Work, Unit test…and many more – the list of “things” that I have read and learn about in the last few months.

First, I am not considering myself a well experimented programmer, started with VBA, after Visual Basic, then C# on Windows and Web (ASP.NET web forms). Small/medium apps for my work that are ok and some used even today after years…

Now because I want to use that new technologies I have started to learn about them:

And the “nightmare begins”….i just want to learn one concept/pattern whatever (MVC), not to get crazy and try to complicate things and feel that my brain will explode soon. The guru’s speak about “KISS”, “DRY” ,“Patterns” and “Good practices” etc., if I don’t use this … I am a nobody, without that I am a bad programmer. They tell me about “Unit tests”, and UML and Entity Framework …. Really!!!!???

In real life 80% of the applications are not so big, so complex! In general, ASP.NET apps are just CRUD apps in a way or another. Why we like to complicate things in this manner? I don’t understand, maybe I am too stupid for “MVC” concept.

99% of the courses/videos out there start simple, with the promise that you will learn this MVC concept quick and easy. They start to explain the basic concepts and you are very happy because you finally, finally …finally understand!!! Noooo don’t be a dreamer is not so simple: the instructor/author change his mind and start complicate things allot… and begin to tell you that is not good to pass Model directly to View (via Controller) no..no.. is a bad thing and explain how you need to add another “thing” … View Model.. and you start to feel pain in your head. You start to learn, to find the need and use of this View Model and … they tell that you need another “thing” AutoMaper in order to map your ViewModel objects with your Model Objects. Then… Entity Framework and Code First with migrations and….finally you think that you managed all and you are with your head ready to explode, but happy…you feel that have learned something…

You think this is over?!! NO! The guru’s/the men that know all/the best of the best … look at you with arrogance and ask you: “what? you don’t use Repository pattern or other many "...patterns", with Unit of Work…you are a loser/a beginner”. And you look in the mirror and you are ashamed that your small web app (that works fine, do what she need to do) is not good, she needs some “patterns” and Unit of Test…and ..and..and…

And i start and add many of what guru’s tell me to add…and after some time my app is so complex and use so many “pattrerns” and “frameworks” and “good practices” and other “guru stuff”, that is so hard to manage and I am LOST!!!

I just wanted to make a CRUD app in MVC, to learn this new concept, that allow me to collect some data via web, app that in ASP.NET webform “time” and ADO.NET, was so easy to do… But NOOO that webform is not good anymore…is bad, very bad…violate the golden rule of “stateless” http protocol and don’t have that “separation of concern”. I have web form apps from 2004 that work so fine even now, no problem!

I don’t know what to say, maybe my brain has a limit and I can’t manage such complex architectures, but I don’t see that “KISS” here, that “DRY”… I just see Make it Very Complicated or write much more code, I see only more work and too much complexity! This is my point after months of reading/videos/courses…

Sorry for my bad English, hope you understand me

All the best to you!

Protect a set_state() function in State Pattern

I want to create a Switch, which can take on two states: TurnedOn and TurnedOff.

Let's say I have this basic setup:

class SwitchState  // Abstract Class for the State Interface
{
public:
    virtual ~SwitchState(void) { /* */ }
    virtual void flip(Switch* swtch) = 0;
};

class TurnedOn: public SwitchState  // First State class
{
public:
    ~TurnedOn(void) { /* */ }
    void flip(Switch* swtch);
};

class TurnedOff: public SwitchState  // Second State class
{
public:
    ~TurnedOff(void) { /* */ }
    void flip(Switch* swtch);
};

class Switch  // This will be the State Context
{
public:
    Switch(Light* light): _state(new FlippedDown{light}) { /* */ }
    void flip(void);  // This will change the _state data member

protected:
    SwitchState* _state{};
};

So I can make a Switch object, call switch.flip(). This member function will look like this:

void Switch::flip(void)
{
    this->_state->flip(this);
}

Which will then in turn call:

void TurnedOff::flip(Switch* swtch)
{
    swtch->_state = new TurnedOn{};  // ERROR: _state is protected!
}

I see no way to set the _state of the Switch class without either exposing _state or creating a setter.

But if I'd do this, I could just set the state of the Switch without calling flip().

Is there some clever and/or established way to circumvent this?

Converting DTO to Entity Subclass

My current situation is that I have an abstract model, in which many other models inherit from. The API consumes a "DTO" object, that is essentially one big object that contains all of the possible fields for each subclass, due to the client calling the service. I've created a solution for this, but it feels like it has some bad "smells". Here is an example of the setup:

public abstract class Person {
    public Long id;
    public Long name;
}

public class Employee extends Person {
    public Date startDate;
}

public class Student extends Person {
    public Double gpa;
}

public class PersonDTO {
    public Long id;
    public String name;
    public Date startDate;
    public Double gpa;
    public String type;
}

I want to convert the DTO to its concrete subclass with initialization. I've solved that by creating a factory and overriding a method in each of the subclasses:

public class PersonFactory {

    public Person getInstance(String type) {
        if (type.equals("Student")) {
            return new Student();
        } else if (type.equals("Employee")) {
            return new Employee();
        }

        return new Person();
    }
}

public class Student extends Person {

    public Double gpa;

    /**
     * Initializes the additional fields in the subclass
     * from the PersonDTO.
     */
    @Override
    public void initialize(PersonDTO dto) {
        this.gpa = dto.gpa;
    }
}

So the calling class will do the following:

public Person createPerson(PersonDTO dto) {
    Person person = new PersonFactory().getInstance(dto.type);
    person.name = dto.name;
    person.id = dto.id;
    person.initialize(dto);
}

To put this into perspective a little more, the model superclass (in this example, Person) has about 15 fields, and the subclasses can have up to 5 or 6, making using a constructor cumbersome. I feel like having the initialize method is a bad practice, and couples the Person class to the DTO class (which I'd like neither class to know about the other).

Ideally, I'd like to create a Mapper or Translator class, that will translate the DTO into the concrete subclass, but I keep running into the following issue with initializing the common fields:

public class PersonMapper implements Mapper<PersonDTO, Person> {

    public Person map(PersonDTO dto) {
        if (person.type.equals("Student")) {
            Student person = new Student();
            setupCommonFields(person, dto);   // required to call this method
            person.gpa = dto.gpa;             // inside of every block
            return person;
        } else if (person.type.equals("Employee")) {
            Employee person = new Employee();
            setupCommonFields(person, dto);
            person.startDate = dto.startDate;
            return person;
        }

        return person;
    }

    private void setupCommonFields(Person person, PersonDTO dto) {
        person.id = dto.id;
        person.name = dto.name;
    }
}

This seems like a clearly simple problem to solve, but I can't seem to come up with the most perfect solution. Is there a better-designed solution for this?

Javascript scope issue in higly customizable plugin pattern

I'm trying to build a Javascript plugin. It will be a slider/carousel with the ability to add options and actions for every single slide. I know that there are already similar plugins around, but first of all I want to make some practice in building a plugin and then I think it might be easier to extend it the way I want, should I need it.

It's my first attempt in building a Javascript plugin and after having read about different design patterns I thought that this would fit my needs: http://ift.tt/1512vDg

So, my html would be something like this:

<div class="container">
  <div class="item" data-step-in="stepin" data-step-out="stepout">item</div>
  <div class="item" data-step-in="stepin2" data-step-out="stepout2">item</div>
  <div class="item" data-step-in="stepin3" data-step-out="stepout3">item</div>
</div>

Ideally I want to call the plugin on the container element and have it set all the options for each element:

$('.container').slider();

The basic plugin structure is:

(function(window, $) {
  var Plugin = function(elem, options) {
    this.elem = elem;
    this.$elem = $(elem);
    this.options = options;
    this.items = {};
  };

  Plugin.prototype = {
    defaults: {
      message: 'Hello world!',
      itemsClass: '.item'
    },
    init: function() {
      this.config = $.extend({}, this.defaults, this.options);

      $(this.config.itemsClass).each(function(i, obj) {
        console.log(i, obj);
        this.items[i][item] = obj;    <--- problem!
      });

      return this;
    },
  };

  Plugin.defaults = Plugin.prototype.defaults;

  $.fn.slider = function(options) {
    return this.each(function() {
      new Plugin(this, options).init();
    });
  };

  window.Plugin = Plugin;
})(window, jQuery);

In the init function I thought to iterate over the items, and store them, with all the options, in a global object. This is where I fail. Inside the each cycle this refers to a single item of the iteration. So, from here, how shall I refer to this.items inside the constructor? What's the best approach here? Is the pattern wrong for this use?

I Know Dependency Injection but is it a software design pattern?? or kind of a desing pattern or its a desing principle?

I Know Dependency Injection but is it a software design pattern? or kind of a design pattern or its a kind design principle?. and also why it is not included in Design Patterns: Elements of Reusable Object-Oriented Software book.

Used and Unused db connection objects

I encountered a question where in we have a set of say DB connections and multiple users simultaneously request for them.

I must be able to provide them the Conn object from a pool of existing connectios, and once they are done using it, put it back into the same pool of available connections.

The approach I could think of was to have 2 sets for each used and unused connections and keep moving objects back and forth.

I am somehow not convinced it's the best way to do this.

Can anyone pls suggest a nicer approach? I was wondering if we could mark the connection obj as in use or something so that we can do away with these two sets?

vendredi 26 février 2016

What is the goal of the java.nio.file.CopyOption interface?

I'm confused about the design of JDK7 nio package (which I use often). Take for example Files.copy, which takes instances of CopyOption's which is an empty interface, e.g. implemented by StandardCopyOption:

public enum StandardCopyOption implements CopyOption {
    REPLACE_EXISTING
    COPY_ATTRIBUTES,
    ATOMIC_MOVE;
}

public interface CopyOption {
}

What is the idea behind such a design? I mean, even though the CopyOption interfaces is passed to Files.copy, Files.copy has still a compile-time dependency on StandardCopyOption (see source-code of Files.copy).

SVG: Polygon pattern fill doesn't work with Chrome

I'm working on a project that essentially generates a SVG image dynamically. I noticed that when it generates a polygon with a bitmap pattern fill, it doesn't fill that polygon in Chrome, but it does work as expected in Firefox. Here is a stripped down example:

<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <svg version="1.1" viewBox="0 0 12347 10442" preserveAspectRatio="none" width="350pt" height="296pt" style="border: none;">
            <svg x="0" y="0" width="12347" height="10442" viewBox="0 0 12347 10442" preserveAspectRatio="none">
                <polygon points="8748,2151 10124,2151 10124,2293 8748,2293 8748,2151" fill-rule="evenodd" fill="url(#pat)"></polygon>
                <defs>
                    <pattern id="pat" x="0" y="0" width="8" height="8" patternUnits="userSpaceOnUse">
                        <image x="0" y="0" width="8" height="8" xmlns:xlink="http://ift.tt/PGV9lw" xlink:href="data:image/bmp;base64,Qk1uAAAAAAAAAD4AAAAoAAAACAAAAAgAAAABAAEAAAAAAAgAAAASCwAAEgsAAAAAAAAAAAAA////ABGAAADdAAAAdwAAAN0AAAB3AAAA3QAAAHcAAADdAAAAdwAAAAAAAAAAAAAAAAAAAAAAAAA="></image>
                    </pattern>
                </defs>
            </svg>
        </svg>
    </body>
</html>

I can't quite figure out why it doesn't work, or what I'm doing wrong. I think this may be the same question as SVG Pattern Doesn't Show on Page but I am using a data url that embeds the image, so I'm not even referencing any external resources.

I'm grateful for any hints as I haven't been able to figure out how to get this to work.

Understanding Decorator Pattern

This pattern is used to modify the functionality of an object at runtime without using inheritance or composition:

public interface Car {
   public void assemble();
}

    public class BasicCar implements Car {
@Override
public void assemble() {
System.out.print("Basic Car.");
}
}



 public class CarDecorator implements Car {
protected Car car;
public CarDecorator(Car c){
this.car=c;
}
@Override
public void assemble() {
this.car.assemble();
}
}

public class SportsCar extends CarDecorator {
public SportsCar(Car c) {
super(c);
}
@Override
public void assemble(){
car.assemble();
System.out.print(" Adding features of Sports Car.");
}
}

public class LuxuryCar extends CarDecorator {
public LuxuryCar(Car c) {
super(c);
}
@Override
public void assemble(){
car.assemble();
System.out.print(" Adding features of Luxury Car.");
}
}

public class DecoratorPatternTest {
public static void main(String[] args) {
Car sportsCar = new SportsCar(new BasicCar());
sportsCar.assemble();          //1                           
System.out.println("\n*****");
Car sportsLuxuryCar = new SportsCar(new LuxuryCar(new BasicCar()));
sportsLuxuryCar.assemble();   //2
}
}

output is:

Basic Car. Adding features of Sports Car.


Basic Car. Adding features of Luxury Car. Adding features of Sports Car.

because:

//1
@Override
    public void assemble(){
    car.assemble();                                        --> Basic Car.
    System.out.print(" Adding features of Sports Car.");   --> Adding features of Sports Car.

//2
@Override
    public void assemble(){
    car.assemble();                  --> LuxuryCar   -->   Basic Car.
    System.out.print(" Adding features of Sports Car.");   --> Adding features of Sports Car.

Also in CarDecorator if you comment this.car.assemble(); you get the same result because it is not used we don't have an istance of CarDecorator in the test class.

Am I right?

Java Need Better design pattern for step based execution

I have bulk list of values need to find their details from different sources by following simple rules like

  1. find at source1 if not found goto source2 till sourceN.
  2. If couldn't find at any source then apply some defaults.

at each source I may find some values, what ever the values are not found at that particular source I need to search them at another source I need to continue this till I find details for all values.

so trying to find better design and algorithm to implement this.

Any answers really will really helpful.

javascript module design pattern

I'm wondering what's the difference between this module declaration

( function( window, undefined ) {

  function MyModule() {
      this.myMethod = function myMethod() {
    };

    this.myOtherMethod = function myOtherMethod() {
      alert( 'my other method' );
    };

  }
    window.MyModule = MyModule;

   } )( window );

and this other one

var myModule = {
   myMethod: function () {
      console.log( 'my method' );
  },
   myOtherMethod: function () {
      console.log( 'my other method' );
  }
};

it could be helpful a proper OO programming analogy (if there's one it fits) :)

Where is MVC Pattern in the Agile Stack?

I developed a Java web application for the validation and the exchange of orders with a CRM Solution, but that's not important.

The important thing is I tried to follow the principles of good programming, so Agile Development, trying to think with different "hats" on the various stages of the development. After everything I decided to write a document for my own, trying to understand what I did, and if I could've done it better. I tried to separate the themes regarding analysis and design, but I can't really understand how should I "define" some of the steps I made.

For example, starting from the beginning, reading lot of documents I arrived to understand the conceptual classes for the domain model, and thene I draw my UML diagram with the interactions, and everything has gone fine.

The next step was to draw the interactions between the conceptual classes for some of the use cases, trying to define responsibilities for each of the classes. Until now we're still talking of analysis right?

The next step, maybe to "big", was to define the web pattern to use, and I decided to work with MVC pattern. The problem is now, as all of the conceptual classes become beans, and we build a huge "framework" of classes on the top... Controller, Services, Dao, Model business... Where should we place the choice of the MVC Pattern? Is it analysis? Is it already design? I would go for the second, but it makes me thing my analisys step was way too short and I forgot something in the middle.

N-th but last question: when shoud classes that I never mentioned in the analysis stage come into play? For my example, a Validator class that works to clean my orders and that was obviously not included in my domain model be exposed? At what level of my design stage?

Thanks in advance.

BLL Return String Or DTO

I'm confused how to return the result from the business layer. Sometimes I need to return the message if it does not pass the criteria. For example:

public SalesDTO GetSalesByPrescriptionNo(string prescriptionNo)
{
    int count = unitOfWork.SalesRepository.GetNumberOfPrescriptionUsed(prescriptionNo);
    if (count > 5)
        // I cannot return string/error information 
        // since the function is return SalesDTO type
        return "Cannot used anymore";

    var sales = unitOfWork.SalesRepository.GetSalesByPrescriptionNo(prescriptionNo);
    var salesDTO = Mapper.MapToDTO(sales);
    return salesDTO;
}

Based on the good OOP/OOD implementation, how should I handle the multiple result from the BLL?

Thanks in advanced.

Command pattern with dependencies

I'm an old VB6 developer and am trying to learn some OOP methods. I am working on a Winforms application that has multiple objects that live for the life of the application, such as logging, audio, and socket connections to applications running on other machines. Certain things like a button press or socket message received can trigger actions that do things with one or more of these objects. For example, when a user clicks a Login button, I might want to log it to a file, open a socket connection, play audio to the user, and start up the microphone. It looks like the Command pattern might do what I want, but how do I pass the dependencies cleanly when there are so many? So it might look like:

Public Interface ICommand
    Sub Execute()
End Interface

Public Class LoginCommand
    Implements ICommand

    Protected _Receiver As LoginCommandReceiver

    Public Sub New(Receiver As LoginCommandReceiver)
        _Receiver = Receiver
    End Sub

    Public Sub Execute() Implements ICommand.Execute
        _Receiver.Login()
    End Sub
End Class

Public Class LoginCommandReceiver
    Protected _Logger As LogManager
    Protected _Gateway As IGatewayConnection
    Protected _Audio As IAudioPlayer
    Protected _VR As IVREngine

    Public Sub New(Logger As LogManager, Gateway As IGatewayConnection, Audio As IAudioPlayer, VR As IVREngine)
        _Logger = Logger
        _Audio = Audio
        _Gateway = Gateway
        _VR = VR
    End Sub

    Public Sub Login()
        _Logger.LogEvent("Starting login")

        _Audio.PlayRingtone()
        _Gateway.Connect()
        _VR.Start()

        _Logger.LogEvent("Login complete")
    End Sub
End Class

So now the constructor for the LoginCommandReceiver is getting messy, even in this simple example. I thought about putting the required dependencies into a container class. The constructor can then look like:

Public Sub New(Container As ApplicationContainer)
    With Container
        _Logger = .Logger
        _Audio = .Audio
        _Gateway = .Gateway
        _VR = .VR
    End With
End Sub

I actually have that container class built (without the Command pattern) but the container class is getting pretty big (almost 30 objects), and it doesn't seem right to pass that huge thing all over to classes that only need a fraction of what it contains. Service locator pattern seems appropriate but I'm reading that should be avoided.

I also thought about making each step of the process its own command, like LogCommand, PlayRingtoneCommand, GatewayConnectCommand, and VRStartCommand. Then each subcommand only needs to know about one of the application-level objects. For example, playing the ringtone only needs to know about the audio object:

Public Class PlayRingtoneCommand
    Implements ICommand

    Protected _Receiver As PlayRingtoneCommandReceiver

    Public Sub New(Receiver As PlayRingtoneCommandReceiver)
        _Receiver = Receiver
    End Sub

    Public Sub Execute() Implements ICommand.Execute
        _Receiver.PlayRingtone()
    End Sub
End Class

Public Class PlayRingtoneCommandReceiver
    Protected _Audio As IAudioPlayer

    Public Sub New(Audio As IAudioPlayer)
        _Audio = Audio
    End Sub

    Public Sub PlayRingtone()
        _Audio.PlayRingtone()
    End Sub
End Class

Now each command will have a single object in its constructor, which is cleaner. But somewhere, somebody still has to know about all the objects in order to create the list of commands. Outside of making this giant container, the only other time I have all objects instances together is at program startup when I'm wiring everything together. Do I need to create instances of all command types at that point? There could be a lot of them. Or is there some other design that will make this cleaner?

what kind of design pattern should be used in this example?

An inexperienced developer created the following object model. Adding new instruments turned out to be complicated with this design, because the space shuttle needs to know all the instruments. It updates their states by explicitly invoking the appropriate methods (e.g. updateXY() in GPS). Every new instrument requires changing the SpaceShuttle class. Improve this design using a design pattern. Draw a UML class diagram to explain your improved design.

class Diagram

Does the "Open for extension, closed for modification" principle make any sense?

It looks to me like Bob Martin needed something starting with O to make SOLID and found in some old book this (possibly useless) Open/Closed principle.

How can Open/Closed co-exists with the Single Responsibility, that states a class should have a single reason for change?

If I want to follow Open/Closed in a long living system, am I supposed to have a chain of dozen classes, each extending the previous?

Good practice / design pattern to resolve the nested if else?

Currently I have a code like this:

for (each item) {
   if (item == 'x') { 
      print
   }
   if (item == 'y) {
      print
   } 
}

Now, I there is an additional requirement - I want the same checks but instead of printing, I need to insert in DB.

ie

for (each item) {
   if (item == 'x') { 
      insertDB
   }
   if (item == 'y) {
      insertDB
   } 
}

This has duplicated code, so flags come to my thought.

for (each item) {
   if (item == 'x') { 
      if (insertDB) {
          insertDB
      } else {
          print
      }
   }
   if (item == 'y) {
      if (insertDB) {
         insertDB
      } else {
         print
      }
   } 
}

This has clearly caused a lot of if-else clutter. My Object oriented programming tells me a new idea.

for (each item) {
   if (item == 'x') { 
      obj.doItemXAction();
   }
   if (item == 'y) {
      obj.doItemXAction();
   } 
}

Object obj = new PrintObj();
Object obj = new DBInsertObj();

Code looks much cleaner. But, given what I could think off, can anyone point me to exact design pattern which deals in situations like this ?

Difference between "template" tags, "content" tags and custom element tags in HTML

I am beginning to learn about web components and polymer. I understand that there are mechanisms to separate content from presentation which is important in dynamically presenting content. I also understand that the "content" tag helps do so by selecting what contents (say, those within certain HTML tags or ids or classes, etc.) needs to be presented. But, I feel that the use of template tag is also in separating content from presentation and so is the use of custom element tags while the presentation/rendering is completely taken care of by JavaScript.

But we have 3 different types of tags all doing the same thing: defining content in a more structured way for ease of presentation. Could we combine some of their mechanisms into fewer tags?

It would be great if an explanation could be given, of the roles of template tags, content tags and custom-element tags, in relation to the programming idioms and design patterns followed in Web Engineering.

ImportError with PyInstaller (using module pattern.de)

I’m using a module named pattern.de (http://ift.tt/1l8DYGf) to implement a tool for text mining. To make it available for my colleagues I wanted to convert it into a standalone application. That for I’m using PyInstaller. When I run the final executable file I get the following ImportError

Traceback (most recent call last):
  File "<string>", line 4, in <module>
ImportError: No module named pattern.de
test returned -1
LOADER: OK.
LOADER: Cleaning up Python interpreter.

To make it easier to find a solution I reduced my script to the crucial part:

from pattern.de import parse, split

This is what I entered to start PyInstaller:

pyinstaller --onedir --name=test --hiddenimport pattern.de --debug "C:\Users\BBlag\PycharmProjects\LDA\test.py"

As you can see I added pattern.de explicitly as hiddenimport. But while PyInstaller runs it shows me that it is not able to find the module:

108 INFO: Analyzing hidden import 'pattern.de'
1215 ERROR: Hidden import 'pattern.de' not found

I’m pretty new to programming so please excuse if this question is trivial. I have been wondering if it could be connected to the fact, that the module itself (when it is being downloaded and installed) is called simply ‘pattern’. ‘Pattern.de’ is used to import the german version of the package. That’s why I also tried to hiddenimport ‘pattern’. When I do so, I don’t receive the above mentioned error from PyInstaller (here it finds the right module), but when executing the final application I get the following similar error:

Traceback (most recent call last):
  File "<string>", line 4, in <module>
ImportError: No module named de
test returned -1
LOADER: OK.
LOADER: Cleaning up Python interpreter.

The application obviously is missing the ‘de part’ here. What am I doing wrong?

CommandHandler and EventHandler order

I am new about CQRS and want to learn work order of the pattern. My command handler and command are like this:

public interface ICommandHandler<in TCommand> where TCommand : ICommand
{
    void Handle(TCommand command);
}

When I cerate a Work a command handler is working.

public class CreateWorkCommandhandler : ICommandHandler<CreateWork>
{
    public void Handle(CreateWork command)
    {
        Save to database...            
    }
}

And I do not call command handlers in controller classes. I use a CommandExecuter to call commands by type.

public class CommandExecuter
{

    public static void ExecuteCommand<TCommand>(TCommand command) where TCommand : ICommand
    {
        var handlerType = typeof(ICommandHandler<>).MakeGenericType(command.GetType());

        var handlers = serviceLocator.GetAll(handlerType);

        foreach (var handler in handlers)
            ((dynamic)handler).Handle((dynamic)command);
    }
}

I want to send email and send sms and another things after work created. But I can not do these steps in Handle(CreateWork command) because of separated architecture.

I think these steps are events, is this true? So I need event and event handler types.

public interface IEventHandler<in TEvent> where TEvent : IEvent
{
    void Handle(TEvent event);
}

Where can I populate the events? In CommandExecuter or CommandHandler I need multiple events for an event. for example:

public class WorkCreated:IEvent{}

Send sms, send email.

What is a provider in OOP?

While working on legacy code in Java I often see references to some provider method/classes which confuses me.

I know that we can have Factories whenever we need to do some complex object construction.

What are use cases in which we prefer to chose provider over factories?

jeudi 25 février 2016

What speaks against static fields?

I have two cases in our tool where I have some difficulties in my integration tests with static fields. In the application these fields are no problem. In my tests I create basically a new application with each test method. When I run these in one test run, you can imagine, there will be some problems. First let me show two such cases.

Case 1

class SomeClass
{
    private static IService service;

    public static void Initialize(IService service)
    {
        SomeClass.service = service;
    }

    public void DoSomthing()
    {
        service.Foo();
    }
}

Basically objects of this class will be created in huge numbers. To be able to use the IService object it is stored as an static field.

Case 2

abstract class BaseClass
{
    private static readonly Lazy<SpecificClass> specificClass = new Lazy<SpecificClass>(() => new SpecificClass());

    public static SpecificClass SpecificClass
    {
        get { return specificClass.Value; }
    }
}

class SpecificClass : BaseClass
{

}

This is even more troublesome for my tests, because even if I create a complete new application, when the SpecificClass was used in the first test it is the same object in the second test.

I know, that tests typically show design flaws, but I cannot see one here. The only argument for removing these static fields I can think of is, that my tests do not work otherwise.

So my question now, why is it in these to cases considered bad code to use the static fields or is it not?

Factory's claims and passing it arguments to initialize objects it creates

Factory pattern brings two main things to the table:

  • Detaches client side code from exact implementation details of classes.
  • Centralize code creation so if the creation logic changes, it is changed only in the factory instead of possible 20 files.

But what if I want to pass specific arguments to the constructor to initialize it properly? This would come from user or current state of the application. Wouldn't this kind of defeat the 2nd point?

class AnimalFactory
{
public:
    createAnimal(type, string nickName)
    {
        if (type == 0)
            return new Dog(nickName);
        else if(type == 1)
            return new Cat(nickName);
    }
}

The above is how I have seen in examples, but is the following equally good factory, perhaps even more preferable since its more readable and pass one less argument?

class AnimalFactory
{
public:
    createDog(string nickName)
    {
        return new Dog(nickName);
    }

    createCat(string nickName)
    {
        return new Cat(nickName);
    }
}

Java design pattern: Factory vs Singleton? in case of Multithread

It is advisable to create new object wisely and use the same Object instance instead of creating a new one. I am not very much confident in deciding the solution for creation of object in following scenario. There is a SOAP service class which has several method that is responsible for multiple customer. Please see below a template,

Public class SOAPService {          
            public Object getProductList(String CustId, String endPoint){
                SOAPStub stub = new SOAPStub(endPoint);
                Object productList = stub.getProductList();
                return productList;
            }
            public Object getProductInfo(String CustId, String productId, String endPoint){
                SOAPStub stub = new SOAPStub(endPoint);
                Object productInfo = stub.getProductList(productId);
                return productInfo;
            }
    }

Now I have introduce a factory method to create Object for each of the customer and put it in a map but i am confused when multiple thread of a single customer would access the service class. Wouldn't the behavior of object be like a singleton OR which might cause any deadlock issue OR make the thread to wait ?Please enlighten me on this.

    Public class SOAPService {
        private Map<String, SOAPStub> map = new HashMap<String, SOAPStub>();
        public SOAPStub getSOAPObject(String CustId, String endPoint){
            if(map.containsKey(CustId))
                return map.get(CustId);
            else{
                SOAPStub stub = new SOAPStub(endPoint);
                map.put(custId, stub);
                return stub;
                }
        }
        public Object getProductList(String CustId, String endPoint){
            SOAPStub stub = getSOAPObject(CustId, endPoint);
            Object productList = stub.getProductList();
            return productList;
        }

        public Object getProductInfo(String CustId, String productId, String endPoint){
            SOAPStub stub = getSOAPObject(CustId, endPoint);
            Object productInfo = stub.getProductList(productId);
            return productInfo;
        }
    }

Should there be any logic on the activity class?

I was recently reading about design patterns and especially about low coupling and delegation.

I was wondering, whether there should be any logic on the Activity class or if it only serves the view.

E.g. I have an activity called BattleActivity and that is supposed to work as some kind of session between two players. A lot of Push Notifications happen there, also the class works as an Observer, so there is a lot of comminication going on there.

Right now I am trying to figure out what logic could I move to a separated object(and whether I should) and then just work with the activity.

Example of one of my methods on the activity:

private void postCastedSpell(final int spellId) {
        Call call = StaticGlobalContainer.api.postSpellToBattle(Integer.parseInt(battleId), Integer.parseInt(MainActivity.CURRENT_USER_ID), spellId, 100);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Response<User> response, Retrofit retrofit) {
                User user = response.body();
                if (response.code() == 202) {
                    // 200
                    Log.i("Posting spell to battle", "Success");
                    Boolean affectedUserIsOpponent = isUserOpponent(user);
                    if (affectedUserIsOpponent && user.currentHp<1){
                        StaticGlobalContainer.battleOnResult(Constants.WON, getApplicationContext());
                    }else {
                        updateBattleLog(affectedUserIsOpponent, user, spellId);
                    }
                    // TODO: do something here
                } else {
                    // 404 or the response cannot be converted to User.
                    Log.e("Posting spell to battle", "Error:" + response.errorBody());
                }
            }

            @Override
            public void onFailure(Throwable t) {
                Log.i("HttpRequest-Post spell", "Failure");
            }
        });
    }

How to add patterns or stripes to SSRS data cells instead of a color

IN SSRS: I can only add Solid color fills to the data cells inside a matrix. How do I add Stripes or Patterns as background fill instead of a solid color. Is there a particular color code like '#xxxx' for stripes? There are certain rows in my report that need to have stripes or patterns as backgrou fill.

Thanks

nodejs mysql design pattern for function - conditional statement with iteration, change the values

I have two node mysql statements to retrieve data.

//one query
pool.getConnection(function(err, connection) {
connection.query('select * from tablejohn' , function(err, rows, fields) {  
infoCleanup(rows,"rows[i]");
} });


//2 queries (multiqueries in one statement)
pool.getConnection(function(err, connection) {
connection.query('select count(*)  as Companycount from tablejohn WHERE elif in (3,4);select * FROM tablejohn WHERE  elif in (3,4)', function(err, rows, fields) {
infoCleanup(rows,"rows[1][i]");
} });

to iterate and change the values I've created a function for this

var infoCleanup = function(rows,type){

if (type=="rows[i]"){
//iterate and change the value
for(var i=0;i<rows.length; i++)
rows[i].a = toTittleCase(rows[i].a);
rows[i].b = toTittleCase(rows[i].b);
rows[i].c = toTittleCase(rows[i].c);
}

else if(type=="rows[1][i]"){
//iterate and change the value
for(var i=0;i<rows[1].length; i++)
rows[1][i].a = toTittleCase(rows[1][i].a);
rows[1][i].b = toTittleCase(rows[1][i].b);
rows[1][i].c = toTittleCase(rows[1][i].c);
}

}

For now I have been using the above infoCleanup(rows,type) function and from there set a conditional statement.

The question how can I improve my infoCleanUp function for a better maintainable code (i.e design pattern ,oop etc)?

As you can see the execute statement( "iterate and change the value") for both conditional do the same things, only different is either variable rows[i] or variable rows[1][i] . So I guess we dont have conditional statement in this case and reduce line of code.

Revealing module pattern template

I have the following that works fine for one page but I want to make it available for 2 more pages:

 var dynamicPropertyOverviewController = (function(){

    var currentPage = $('#dynamicPropertyOverview');

    function init(){
        if(checkMobileAndTabletVisibility.isTabletView()){
            if(dynamicPropertyController.isDynamicPropertyOverviewWithAvailability(currentPage)){
                dynamicPropertyController.addSearchModalMobileTrigger();
                if(dynamicPropertyController.isSearchBarNotHidden()){
                    dynamicPropertyController.hideSearchBarDisplayPill(currentPage);
                }
            }
        }
        else{
            dynamicPropertyController.addSearchBarDesktopTrigger();
        }
    }

    return{
        init: init
    }

})();

"currentPage" var will determine where this init is going to be applied.

This is just to have a better idea of where all these functions come from:

    var dynamicPropertyController = (function() {

        var searchBarModalTrigger = 'js-open-mobile-search';

        function isDynamicPropertyOverviewWithAvailability(page){
            return page.length && !$('.property-not-available').length;
        }

        function hideSearchBarDisplayPill(page){
            page.addClass('hide-search-form');
        $('.check-prices').addClass('display-pill');    
    }

    function addSearchModalMobileTrigger(){
        $('.edit-search-link').removeClass('display-searchBar').addClass(searchBarModalTrigger);
    }

How can I make

    function addSearchBarDesktopTrigger(){
        $('.edit-search-link').removeClass(searchBarModalTrigger).addClass('display-searchBar');
    }

    function isSearchBarNotHidden(){
        return !$('.hide-search-form').length;
    }

    return {
        isDynamicPropertyOverviewWithAvailability: isDynamicPropertyOverviewWithAvailability,
        hideSearchBarDisplayPill: hideSearchBarDisplayPill,
        addSearchModalMobileTrigger: addSearchModalMobileTrigger,
        addSearchBarDesktopTrigger: addSearchBarDesktopTrigger,
        isSearchBarNotHidden: isSearchBarNotHidden
    }

})();

How can I make "dynamicPropertyOverviewController" so that I can just pass one variable and use it across 3 different pages?

Instantiate an extended class or its parent (depending on circumstances)

Let's say I have a class named Human in ProjectA. It is instantiated in the CreatureBuilder class of the same project.

Now I want to create a new class called Cyborg in a different project, i.e. in ProjectB. ProjectB has ProjectA in its imports, but ProjectA knows nothing about ProjectB.

Cyborg extends Human, and must also be instantiated by CreatureBuilder of ProjectA (so, Cyborg is located in ProjectB, I call CreatureBuilder from ProjectB to instantiate Cyborg, but CreatureBuilder is located in ProjectA, as well as my Human class).

I need a logic to create a Human when CreatureBuilder is instantiated from ProjectA, and to create a Cyborg when CreatureBuilder is instantiated from ProjectB.

I think it is achievable by creating an interface with a getCreature() method in ProjectA. This method will be overridden in ProjectB to return new Cyborg and then pass it back to CreatureBuilder of ProjectA. Any other suggestions? What do you think is the best workaround? Can I use reflection API instead?

Cheers!

Two ways of Singleton design

I'm trying to learn about the Singleton design pattern and I found two different ways of only creating 1 instance.

public class Singleton {
   private static Singleton instance; // attributes omitted
   private Singleton() {
    // omissions
   }

public static Singleton instance() {
    if (instance == null) {
        instance = new Singleton();
    }
    return instance;
}
// other methods omitted
}


public class Singleton {
   private static int bound = 1;
   public Singleton() {
    if (bound == 0) {
        throw new RuntimeException(
        "Singleton: No more objects must be created");
    }
    bound--;
}
}

Which is preferred to use and why? Are they equally as good?

Design-pattern/solution for logically similar functions without code dupplication

I am looking for an elegant solution for the following (generic) problem. I want to implement several protocols to access files. Let's say ftp and tftp. More may be added in the future. Right now i'm doing:

get_file(filename):
  # some generic code for opening the file etc.
  if mode == 'ftp':
    get_file_ftp(filename)
  else:
    get_file_tftp(filename)
  # some generic code for closing the file etc.

get_file_ftp(filename):
  # ftp-specific code

get_file_tftp(filename):
  # tftp-specific code

Same for put_file(), ls() and a dozen more funtions. As code grows, this is starting to get ugly. So my question is: Is there a more clever way to get the job done? Is thera a design pattern that makes sense for this use case? If so, how would i accomplish this in Python?

browser asks to resend data when page is reloaded

I am writing an application using struts2. I am facing a problem in the login part. When a login is performed,it will redirect to the index.jsp page.Now the problem arises. The problem is when after loggin in, index.jsp is reloaded, browser asks me resend data. I dont know why it is happening? here is my struts.xml code for authenticate action:-

<action name="authenticate" class="com.action.LoginAction">  
    <result name="success">index.jsp</result>
    <result name="failure">loginerror.jsp</result> 
</action>

and here is code for the login action class:-

public String execute() {
    if(sessionMap.containsKey("project_user")){
        return "success";
    }

    Project_User project_User=Login.checkCredentials(email_id,password);

    if(project_User!=null) {
        sessionMap.put("project_user", project_User);
        return "success";
    } else
        return "failure";
}

also when index.jsp comes, the url area of browser remians unchanged, the link in url field of browser still shows the action name like:- localhost:8084/Tek-Hub/authenticate/ if anyone knows about it plzzz help me. Thanxx

Python: OOP methods to make code re-usable and readable?

I have a python script, which creates custom filters for dataframes in pandas. These dataframes contain eventlogs with three columns, client, event, and next (event). client has recurring values, which on every occurance (might) have different values of event and next. I want to find all rows containing a value of client corresponding to filter values of (either of) the other two columns to either single them out, or leave them out. This is captured by a FilterType enumerator, which can be 0 or 1 for selecting values (select), or leaving them out (hide).

Right now, I've created three sample filters (Filter_HasEvent, Filter_EventToNext, and Filter_EventFirst), which respectively find all client's if for any occurence of client the given value of event is attained, a given combination of event and next is attained, or if the given value of event occurs as the first event for client.

I know dataframes have a filter function of their own, however, I would also like to apply multiple filters to the same dataframe using both unions and intersections. Hence, why I create a boolean mask for the dataframe, which can be combined, before application.

Now, for my question: By using classes, I currently have to initiate a filter for every value of event, and combination of event and next there is. What's more, the filter type is now selected for each filter using an if-elseconstruction. This becomes increasingly illegible if I want to add more filter types. Is there a nicer (i.e. more oop) way of defining these filters and implementing the different types, e.g., using decorators or design patterns?
Another issue I have, is that when I add more filters (e.g., filter_EventLast), I have to implement all filter types separately for this filter, because they are not reusable. Ideally, I would like to make a template, which would redirect to the appropriate filter, depending on the input received, like in Java. Is this possible?

Below is the sample code, what it looks like now:

import abc
from enum import Enum

import numpy as np
import pandas as pd

np.random.seed(64951)
client = [j for j in range(10) for i in range(10)]
event = pd.Series(np.random.choice(range(10), len(client)))
next = event - event.diff(-1)
rand_df = pd.DataFrame({
    'client': client, 
    'event': event, 
    'next': next
})


class FilterType(Enum):
    select = 0
    hide = 1


class FilterTemplate(object):
    def __init__(self, value, filter_type):
        self.value = value
        self.filter_type = filter_type
        self.mask = None

    @abc.abstractmethod
    def getMask(self, df):
        raise Exception('Method needs to be implemented!')

    @abc.abstractmethod
    def apply(self, df):
        raise Exception('Method needs to be implemented!')


class Filter_HasEvent(FilterTemplate):
    def __init__(self, value, filter_type):
        super().__init__(value, filter_type)

    def getMask(self, df):
        client_in_event = df[df.event == self.value].client.unique()
        if self.filter_type == FilterType.select:
            self.mask = df.client.isin(client_in_event)
        elif self.filter_type == FilterType.hide:
            self.mask = ~df.client.isin(client_in_event)
        return self.mask

    def apply(self, df):
        return df[self.getMask(df)]


class Filter_EventToNext(FilterTemplate):
    def __init__(self, value, next_value, filter_type):
        super().__init__(value, filter_type)
        self.next_value = next_value

    def getMask(self, df):
        client_in_eventtonext = df[(df.event == self.value) & (df.next == self.next_value)].client.unique()
        if self.filter_type == FilterType.select:
            self.mask = df.client.isin(client_in_eventtonext)
        elif self.filter_type == FilterType.hide:
            self.mask = ~df.client.isin(client_in_eventtonext)
        return self.mask

    def apply(self, df):
        return df[self.getMask(df)]


class Filter_EventFirst(FilterTemplate):
    def __init__(self, value, filter_type):
        super().__init__(value, filter_type)

    def getMask(self, df):
        client_unique = pd.Series(sorted(df.client.unique()), index=sorted(df.client.unique()))
        client_has_event_first = client_unique[df.groupby('client').event.first() == self.value]
        if self.filter_type == FilterType.select:
            self.mask = df.client.isin(client_has_event_first)
        elif self.filter_type == FilterType.hide:
            self.mask = ~df.client.isin(client_has_event_first)
        return self.mask

    def apply(self, df):
        return df[self.getMask(df)]

filter1 = Filter_HasEvent(1, FilterType.hide)
mask1 = filter1.getMask(rand_df)
filter2 = Filter_EventToNext(1, 2, FilterType.hide)
mask2 = filter2.getMask(rand_df)

print(filter1.apply(rand_df))
print('')
print(rand_df[mask1 | mask2])

observer design pattern in rest aplications

I'm trying to learn design patterns, and I have come with the Observer pattern. I think I understand the concept itself, but I don't see when to use it.

I try to explain myself. I work mostly with web applications, so, stateless applications. Normally, the client makes a petition from the browser (for example, update a record). then the operation is completed.

Let us suppose that I want to notify some persons every time a record is updated. It seems to me the perfect scenario for the Observer patter, but when I think of it, it will end something like:

  • user makes petition of update.
  • get all the persons that have to be notified.
  • put all the persons that have to be notified in the observer.
  • make the update. (that also will make the notification for the observer pattern).

but... doing it this way, I have to iterate all the persons that I want to notify twice!

And because its a stateless application, I have to go and get all the persons than needs to be notified every time!

I don't know if the observer pattern is more useful for other types of applications, but I can only think of this pattern in a static form, I mean, making the Observer static.

I know I'm losing something, it's a common and accepted pattern, everyone accept it as a valid solution for this concrete problem. What I am not understanding?

mercredi 24 février 2016

Good approch to design project that uses different type of Databases in single project

Suppose that my project uses 3 different databases MySql, Redis, Cassandra. I want to generalized my design so that

  1. It will return respective database client based on input type at run time (similar to factory design pattern)

  2. In Future, i can easily add or replace DB without much code changes

Something like this, suppose at run time if i want to read/update mysql db my design should return mysql db connection form connection pool, now i want to do same for Redis so based on input it should return Redis connection from connection pool.

Can any one please suggest me the best approach that i should follow to design my project?

Abstract factory pattern and HikariCP

I'm currently using a pool connection(Hikari) and an abstract factory pattern to implement my MySQL queries in Java like this:

MySqlFactoryDAO.java

public class MySqlFactoryDAO extends FactoryDAO {

   public static HikariDataSource connPool_;

   public static Connection createConnection() throws SQLException {

      if (connPool_ == null) {
         // Load database configuration
         PropertiesFile props = FactoryConfig.getConfig().getDatabaseProperties();

         connPool_ = new HikariDataSource();
         connPool_.setJdbcUrl(props.getString(Params.DB_URL,""));
         connPool_.setUsername(props.getString(Params.DB_USER,"root"));
         connPool_.setPassword(props.getString(Params.DB_PASSWORD,"root"));
      }
      return connPool_.getConnection();
   }

   //-------------------------------------------------------------------------

   public ProductDAO getProductDAO() {
      return new ProductMySQLFactoryDAO();
   }
}

ProductMySQLFactoryDAO.java

public class ProductMySQLFactoryDAO implements ProductDAO {

   public int insertProduct(String name) {  
      ...
      Connection conn = MySqlFactoryDAO.createConnection();
      ...
   }    
}

I was wondering if this code is thread safe and I think that there is a problem at the time of initialization of coonPool_. I have read things like "Initialization-on-demand_holder_idiom" in wikipedia but I am not sure about it. Does anyone have a better implementation of this to solve this problem or just a better new one?

How to construct a sequence with a pattern in R

I would like to construct a sequence with length 50 of the following type: Xn+1=4*Xn*(1-Xn). For your information, this is the Logistic Map for r=4. In the case of the Logistic Map with parameter r = 4 and an initial state in (0,1), the attractor is also the interval (0,1) and the probability measure corresponds to the beta distribution with parameters a = 0.5 and b = 0.5. (The Logistic Map is a polynomial mapping (equivalently, recurrence relation) of degree 2, often cited as an archetypal example of how complex, chaotic behaviour can arise from very simple non-linear dynamical equations). How can I do this in R? Thank you very much!

Why are singletons worse than having many references to the same object?

In this link: http://ift.tt/Xwl1Wz it says:

Singletons frequently are used to provide a global access point for some service. True, they do this, but at what cost? They provide a well-known point of access to some service in your application so that you don't have to pass around a reference to that service. How is that different from a global variable? (remember, globals are bad, right???) What ends up happening is that the dependencies in your design are hidden inside the code, and not visible by examining the interfaces of your classes and methods. You have to inspect the code to understand exactly what other objects your class uses. This is less clear than it could be.

I'm trying to understand what the difference is between this and having a reference to our object in many locations. If we have a reference held somewhere else, then couldn't our object be modified in some totally different location, say by some other thread, and be just as hard to reason about?

java command pattern example with Runnable class : Is Receiver missing?

From Examples of GoF Design Patterns in Java's core libraries question, it was quoted that

"All implementations of java.lang.Runnable" are examples of Command pattern.

As per my understanding of Command pattern,

Client calls Invoker => Invoker calls ConcreteCommand => ConcreteCommand calls Receiver method, which implements abstract Command method.

Have a look at this working example

Command pattern UML diagram from this article is shown as below.

enter image description here

Have a look at this code:

public class ThreadCommand{
    public static void main(String args[]){
        Thread t = new Thread(new MyRunnable());
        t.start();
    }
}
class MyRunnable implements Runnable{
    public void run(){
        System.out.println("Running:"+Thread.currentThread().getName());
    }
}

  1. ThreadCommand is Client
  2. Runnable interface is Command
  3. MyRunnable is ConcreteCommmand
  4. Thread is Invoker with start() method calling ConcreteCommand implementaiton ( which calls run() method)

Is Receiver missing here? Or MyRunnable plays combined role of ConcreteCommand and Receiver?

Thanks in advance.

Pattern for commonly used Underscore.js iteratees

I'm working on a financial analysis tool using Underscore.js and Underscore-contrib.

I'm often repeating low-level arithmetical primitives. For example, simple summation of an Array:

code-a.js:

arr_a = [20, 15, 7];
arr_b = [19, 19, 19];

_.reduce(arr_a, function(memo, x) { return memo + x; }, 0);
# => 42
_.reduce(arr_b, function(memo, x) { return memo + x; }, 0);
# => 57

I thought about creating a named function to eliminate duplication of the iteratee definition:

code-b.js:

function sum(memo, x) {
  return memo + x;
}

arr_a = [20, 15, 7];
arr_b = [19, 19, 19];

_.reduce(arr_a, sum, 0);
# => 42
_.reduce(arr_b, sum, 0);
# => 57

Then moved on to wrap the reduce call to DRY this out even further:

code-c.js:

function sum(memo, x) {
  return memo + x;
}
function accumulate(vector) {
  _.reduce(vector, sum, 0);
}

arr_a = [20, 15, 7];
arr_b = [19, 19, 19];

accumulate(arr_a);
# => 42
accumulate(arr_b);
# => 57

To me, this smells like it's headed for a mixin:

lib-a.js:

_.mixin({
  accumulate: function (vector) {
    _.reduce(vector, function(memo, x) {
      return memo + x;
    }, 0);
  }
});

code-d.js:

arr_a = [20, 15, 7];
arr_b = [19, 19, 19];

_.accumulate(arr_a);
# => 42
_.accumulate(arr_b);
# => 57


Using a mixin gets the job done well. My question is: Are there any other patterns (specific to Underscore.js) for reusing iteratees without using mixins? I don't have an issue using mixins if that's "the" [only] pattern, I'm just asking if there are any other tactics to solve the problem of callback reuse.

For example, code-b.js demonstrates one possible alternative — simply create the iteratee as a named function (perhaps exported from a module to avoid the need for Hungarian-esque naming conventions).

Two java maven projects with MVC design: how can they share the same "M" classes?

I develop a JavaEE app in two separate maven projects:
- one project is the API
- the other is a JSF app where calls are made to the API of the 1st project.

They both share the same Model (the classes describing my data structure).

How can I have these 2 projects to share the same Model? Should I create a third Maven project, which will contain these common classes, and this 3rd project will be a dependency for the 2 projects? It seems a bit heavy handed. Is there a better design?

Is there a name/pattern for a container that holds business entities?

I find myself often implementing a class that acts as a glorified container for my business entities. Usually i just suffix that class with "model", which is very undescriptive and broad.

An example (python):

class MyBusinessEntity:
    pass

class MyBusinessEntityModel:
    def __init__(self):
        self.entities = []

    def create_entity(self):
        self.entities.append(MyBusinessEntity())

    # Implement the rest of the CRUD operations

This class will act as my main data repository and will most likely use some kind of data access object for persistant storage.

Does this kind of class have a name? I came across the Repository Pattern, but i don't know if that's really the thing i am looking for.

How to design the API, which has to enable or disable at runtime without restarting the server

I have a requirement for Design auditing system, which has to integrate with our application(ear). Suppose auditing is required for a particular time(Not a fixed time), we need to enable or otherwise disable at runtime without restarting the server.

Please suggest me the best approach to design this Auditing API system.

mardi 23 février 2016

Distributed Publish Subscribe in Cluster Pre Akka 2.4

I'd like to use the Distributed Publish Subscribe (DPS) pattern in an Akka remote cluster. That's as easy as using its provided by Akka implementation but if your system is constrained to use Akka versions below 2.4.0 that is not an option.

There is a Roland Kuhn's answer in SO explaining that it is legit to subscribe a remote Actor to another Actor's EventBus.

Using that, I think DPS can be implemented as follows:

  1. Subscribe all cluster members to MemberUp events in the cluster.
  2. Whenever a MemberUp is detected:

    a. Send a subscription request message to it. And use the answer (subscription acknowledgment) sender to subscribe the recently joined Actor to the local EventBus

    b. The recently joined Actor will receive the message sent at (a) and subscribe the sender to its EventBus

The question is: Do you any other pattern which could improve this approach?

Some people suggest using BroadcastRoutingLogic. Or Broadcast messages. However, in my use case, Actors can join or leave the cluster at any time.

Define regex of interceptor of Flume's source to filer logs in a file

I would like to use interceptor to filter one log file (event file), this log file contains logs of the whole system and I only want to filter log line (event line) having
com.threesixone.analytic.service.ActionLogAspect, and only want to get the json part of the log line,

Can anyone help me with the regex of interceptor, I have difficulties in understanding the pattern to filter.

Below is example of one log line:

2015-11-04 11:09:30,383 INFO : com.threesixone.analytic.service.ActionLogAspect - {"page":"PRODUCT_LIST","controller":"ProductController","product":{"productID":10004,"category":"321","sportCategories":["32"],"name":"Men pullover","gender":"Men","sport":"Running","retailPrice":239.0,"sellPrice":239.0,"sellQuantity":0,"taxablePrice":0.0,"origin":"361° Sports","stockQuantity":1000,"subTotal":0.0},"browser":"Chrome-43.0.2357.130","action":"VIEW","timestamp":1446610170382,"customerType":"GUEST","sessionId":"1et7dn6qbbfui1xszk627pz0p9"}

Should serialization logic be in the entity or other class

Where should object serialization logic (the mapping of fields into XML or JSON names and values) be placed? Inside each entity object OR into a different set of classes only concerned with serialization? Any other best practices out there that relate to this question?

For example:

class Person {
    String name;
}

Some people go about it this way:

class Person {
    String name;
    public String toJson () {
      // build JSON, use 'name' field
    }
}

But if we also needed toXML(), toCSV(), toXYZ() keeping that direction would create horribly polluted code and break the Single Responsibility Principle which is already broken even with a single toJson method, IMHO.

Another option and this is what I typically do:

interface Serializer {  public String toJson (); }

class PersonJsonSerializer implements Serializer {
    private Person p;
    public PersonJsonSerializer (Person p) { this.person = p; }
    public String toJson () {
      // build JSON, use p.name
    }
}

then a factory hands out Serializers depending on entity types:

class JsonSerializerFactory {
    public Serializer getSerializer (Object o) {
        if (o instanceof Person) {
            return new PersonJsonSerializer ((Person)o);
        }
        else if (o instanceof Account) {
            return new AccountJsonSerializer ((Account)o);
        }
        // ... etc
    }
}

There would also be XMLSerializerFactory, CSVSerializerFactory, and so forth.

However, most of the times people want to have full control over the serialization and would not buy into it and prefer to have toJson methods inside each class. They would claim is way simpler and less error prone.

What is the preferred way to go, and are there better alternatives to implement a solution to this problem?

Implement copy constructor with bridge pattern c++

I'm studying c++ and trying to implement the bridge pattern, when this happens, I have My implementation file with constructors:

 SystemImpl::SystemImpl() {
    this->name = "";
    this->value = 0.0;
    this->maxValue = DBL_MAX;
}

SystemImpl::SystemImpl(const SystemImpl& sys) {
    this->name = sys.name;
    this->value = sys.value;
    this->maxValue = sys.maxValue;
}

And now, I'm creating the interface that use this implementation, where imps is my pointer to implementation class:

System::System() {
    imps = new SystemImpl();
}

System::System(const System& sys) {
    imps = new SystemImpl(sys);
}

The fisrt constructor work's fine, but the second, that's a copy constructor, shows no matching function for call to ‘SystemImpl::SystemImpl(const System&)’

What's wrong?

Deciding on Design pattern [on hold]

I am new to C# and I am self learning with the web and several books. My question is about design pattern for a WinForm I am developing to log and predict alcohol by volume and other brewing data,as well as store recipes for making mead. I am having a hard time understanding what path to take but know that a structured program is a happy one.

So the program would:

1) Create and manipulate mead recipes as they are ongoing and fermenting.

2) Store mead recipes after completion for later brewing info.

3) Create labels for bottles.

4) Print out recipes and Entry forms for competitions.

I have written the logic part of the code and the GUI already. I just don't know how to assemble all the parts correctly and save the object(s) to sql or local drive. What design pattern most suits these needs?

Design Pattern for Data Structure with Methods to Populate It?

I have a data structure in Java that I am populating via different methods. One method populates it from an API, another method populates it from parsing some HTML, another populates it a different way, etc. Basically, a method for every data source that could populate it. What I'm wondering is, what design patterns are available in Java for this? What's the best/cleanest OOP approach to this problem?

E.g.,

public class Data {
    private String foo;
    private List<String> bar;
    private Map<String, Integer> baz;

    public Data (String foo, List<String> bar, Map<String, Integer baz) {
        this.foo = foo;
        this.bar = bar;
        this.baz = baz;
    }

    // Setters and Getters here, etc
}


public class FacebookParser {
    private Document dom;

    public static Data parse(Document dom) {
        // Parse document
        // Create Data object
        return Data;
    }
}

public class TwitterParser {
    private Document dom;

    public static Data parse(Document dom) {
       // Parse Twitter
       Data d = new Data(stuff from twitter);
       return d;
    }
}

Is there any command design for scalable market products?

I searched a lot about any command way for creating scalable design UML for products in the market issues but I didn't fond anyway for making my project scalable in the future as easy I can. I have a lot of type of products same "Car, Motor, Bicycle,..." each car has a lot of sublist of types, each type has special attribute so I need to put each one in class but in future if I need to add any item I need to add class to my code that will be so hard way and complex special if I have a lot of types of products. is there any way to make my design more flexible.(ANY EXAMPLE DESIGN PATTERN OR ARTICLE). Note: my project that I create will be the android app.

Is it possible to get an existing DbContext in EF?

I need to abstract transaction from data layer. In business layer I want to do:

IModify modification = modification.Get();
using (ITransaction transaction = Transaction.Get())
{
    try
    {
        modification.Modify(); //do some changes
        transaction.Commit();  
    }
    catch 
    {
        transaction.Rollback();
    }
}

In data-layer:

public class EFDBModification : IModify
{
     public void Modify()
     { 
         using(var context = new MyDbContext())
         {
             // work with entities
             context.SaveChanges();
         }
     }
}

For old approach (TransactionScope) maybe implementation of ITransaction should be like this:

public class EFTransaction : ITransaction
{
    private TransactionScope _scope = new TransactionScope();

    public void Commit()
    { 
        _scope.Complete();
    }

    public void Rollback()
    { 
    }

    public Dispose()
    {
        _scope.Dispose();
    }
}

Now it is recommended to use Database.BeginTransaction() to start the transaction. Probably ITransaction implementation should be:

public class EFTransaction : ITransaction
{ 
    private MyDbContext _context = new MyDbContext();
    private Transaction _transactionContext;    

    public EFTransaction()
    {
        _transactionContext = _context.Database.BeginTransaction();
    }

    //implementation of interface
}

How should I transfer DbContext instance from transaction to EFDBModification object? I thought about the implementation of context as a singleton for a thread or for a webrequest but not sure about this. Or in some other way get existing DbContext. I dont want to pass it as argument to Modify() method.

What's a good way to create event listeners, so that I can listen to changes in javascript classes?

I am trying to create an MV* pattern in javascript. I have a Model class, a View class, and a Collection class.

http://ift.tt/1QwEM3I

Example Model: So for example I have a set method. If this is called and a new attribute is made somewhere here I need to announce to other parts of the code a change on this model happens.

// Model
var Model = function(model) {
  this.attributes = model; // attributes becomes the object passed in
  this.change = false; // by default set change to false
}
Model.prototype.set = function(object) {
  var key = Object.keys(object)[0]; // get first object key
  this.attributes[key] = object[key]; // set the attribute based on object value
  this.change = true; // trigger(announce) a change
  return this.attributes; // return new attributes
}
Model.prototype.get = function(attribute) {
  return this.attributes[attribute]; // return desired attribute
};

Example View: Below is a View class where I will pass the model into it.

// View
var View = function(object) {
  var self = this;
  this.object = object; // set this object to be the object argument passed in to the constructor 
  this.element = document.querySelector(object.element); // grab the DOM element desited
  this.model = object.model; // set this model to be the model passed into the constructor
  if(object.inititalize) {
    object.initialize.call(this); // initialize the view
  }
};

View.prototype.render = function() {
  this.object.render.call(this); // call render when needed
}

Implementation of the above: Here I instantiate the classes, inside the constructor for the Model I am passing in an object which will become the attributes of the Model. Then in the constructor for the View I am defining the view by passing an object to the constructor. Inside this object I also define the Model

// Implementation
var player = new Model({name: 'mike'}); // model instance

var testView = new View({
  element: '.testEl',
  model: player,
  render: function() {

    alert('rendered'); // feedback

    var self = this;
    this.element.innerHTML = this.model.get('name');

    // artificially change the model
    setTimeout(function() {
      self.model.set({
        name: 'Billy'
      });
    }, 5000);

  }
}); // view instance


var Start = function() {
  testView.render();
};

Start();

My Question: Now that the View has a model how can I structure this code so that I can add event listeners? When there is a change on the model in this example model.set() is called and it should announce a change, or publish a change and whatever is subscribed to that should be aware of it.

Is possible to get original image from edited by Photoshop or other program?

I have very interesting question. What you think is it possible get original image from image which has been changed by Photoshop,Drawing(Windows) or other program?

In example lets say I have image of circle (black borders 5px) with white background inside and outside of this circle. Than I open it in some image editor and put yellow color inside circle, so now we have yellow circle with black border and white background around of course. So if I made this change (drawing circle to yellow color) is this change somewhere in data of this images saved? I have get this idea, cause theres no problem to save gps tracking to image, so I thoungt maybey its possible to save change like this (with color) and then open the file and get this change back or see what has been changed on this image.

Thank´s for your time! Have a nice day.