jeudi 30 avril 2015

Design pattern approach for operations with shared dependencies

I've been approaching a scenario, where I can't seem to quite encapsulate the logic required for a design pattern. Here's the scenario...

The ubiquitous task example:

  • I have a Task with multiple Steps to completion.
  • Each Step has a status of complete, process, fail.
  • A fail is a hard stop, task is removed.

Step 1: (no parent, two children depend on Step 1 being completed)

Steps 2 & 3: (Require Step 1 to be completed, 2 & 3 can be completed in any order)

Step 4: (Requires Step 2 & 3 to be completed)

I've approached initially the chain of command, but was unable to adapt the sibling steps. Is this situation better described by another pattern? Or adapting the chain of command to mesh with strategy?

Thanks

Design pattern for class with nested generic types

I can't find a good solution for the following problem:

I'm writing a traffic simulator. It should support various types of engines, for example a Queue-based engine and a Cellular Automata-based engine.

The simulator consists of Links and on these Links are Vehicles. Depending on the engine, there can be various properties, that the links and the vehicle need. So i came up with the following design, the abstract classes are the base and implement most of the functionality, the concrete classes do the rest:

public abstract class Vehicle {
    //Implement common logic
}

public abstract class Link<V> where V : Vehicle {
    public List<V> Vehicles {get;set;}
    //Implement common logic
}

public abstract class TrafficSimulator<L,V> where L : Link<V>, V : Vehicle {
    public List<L> Links {get;set;}
    //Implement common logic
}


public class QueueTrafficSimulator : TrafficSimulator<QueueLink<QueueVehicle>, QueueVehicle>> {
    //Implement queue-specific logic
}


public class CATrafficSimulator : TrafficSimulator<CALink<CAVehicle>, QueueVehicle>> {
    //Implement ca-specific logic
}

It works, but I have the feeling that it's too complicated. And it gets even uglier, if I want to use the simulator as a generic parameter for another class (it does work though):

public abstract class FlowBuilder<T,L,V>
        where T : TrafficSimulator<L,V> 
        where V : Vehicle
        where L : Link<V> {

    public T Build() {
        // Do Stuff
        foreach(var link in T.Links) {
            // Do Stuff
            DoInternalStuff(link);
        }
    }
    protected abstract void DoInternalStuff(L link);
}

public class QueueFlowBuilder : FlowBuilder<QueueTrafficFlow, QueueLink, QueueVehicle> {

    protected override void DoInternalStuff(QueueLink link) {
        // Internal setup of QueueLink
    }
}

Do you have any suggestions on how to improve this design? I'm thinking of the classical design pattern but cant find a suitable match for this.

Implement user permissions in a App

I'm working in a app where I get some user permissions from the back-end.

each of these permissions are relative to one or more Views in my App.

For this I'm creating a map with all possible permissions and their relative views.

public static final Map<String, List> ALL_PERMISSIONS = new HashMap<String, List>() {{
        put("Change-maps", new ArrayList<Integer>() {{
            add(R.id.button_change_view);
        }});
        put("Stores-info-view", new ArrayList<Integer>() {{
            add(R.id.details_fragment);
        }});
        put("Competitors-layer", new ArrayList<Integer>() {{
            add(R.id.switch_concorrentes);
        }});
        put("Context-routes", new ArrayList<Integer>(){{
            add(R.string.route_end);
            add(R.string.route_origin);
            add(R.string.route_remove);
        }});
    }};

Right now I'm having all the Views visible then I iterate for all views and disable then.

private void runPermissions() {
    Resources resources = getResources();
    for(Map.Entry<String, List> entry : disableFunc.entrySet()){

        if(entry.getValue() instanceof List) {
            for(Object itemToDisable : entry.getValue()){
                String resorceType = resources.getResourceTypeName((int)itemToDisable);
                if(itemToDisable instanceof Integer && !resorceType.equals("string")){
                    disableView((int) itemToDisable);
                }
            }
        }
    }
}

One thing that I should be doing different is that would be better to disable everything, than enable just the Views relative to the keys that I received from the back-end;

Another thing is about the Strings. For a dialog that I use in other part of the application, I use to pass an array of string to and ArrayListAdapter to then generate the Dialog items.

 @Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    final Resources resource = getResources();

    builder.setItems(mOptions, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            String selectedOption = mOptions[i];

            if(selectedOption.equals( resource.getString(R.string.coordenates) )){
                    mListener.onGetCoordenateListener(clickedLocation);
            } else if(selectedOption.equals( resource.getString(R.string.report_point) )) {
                    mListener.onReportPointListerner(clickedLocation);
            } else if(selectedOption.equals( resource.getString(R.string.route_origin) )) {
                    mListener.onPutOrigemDaRotaListener(clickedLocation);
            } else if(selectedOption.equals( resource.getString(R.string.route_end) )) {
                    mListener.onPutFimDaRotaListener(clickedLocation);
            } else if(selectedOption.equals( resource.getString(R.string.route_remove) )) {
                    mListener.onClearRote();
            }


        }
    });

    return builder.create();
}

Right now I'm not controlling these String's.

I thought too about implement a Functional interface, (just a interface with a method), than instead of using a Map of <String, List> I would use a Map of <String, FunctionalInterface>. So for each key I would implement the method (run or something like this) that would be called when iterating the map.

Is there some tips about how to control user access in a App ?

Resuming: I get a list of Keys from the back-end, to each key I'll have one or more view to enable, other than View there are some Strings that I use in ArraysAdapter's

PS: I'm really interesting about Patterns or Solutions to controlling user permissions in android application.

Container for precompiled GUI Blocks

so here's my problem. I have a (large and growing) set of single-window applications written in C++ with a QT GUI. Basically each of these programs is used to connect with a different hardware device and consists of a couple of input parameters and a "Connect Button" and is around 300x400px in size. Note: I can access, modify and compile these applications.

What I want now is another (QT) application that allows me combine multiple of those applications above into a single window. I'm thinking like an "Add new Device"-button where I can select one of the existing applications and then it's added to the 'container'.

I don't want to have duplicate code, so I don't want to copy the code from all the applications and include it to one large application. All the application logic should remain within those little programs. Then I want to compile them and only provide those compiled files to the Container-Applications.

Is there a design pattern for something like that? Is there a way to have a common base ui-class (implementing QWindow or something like that) to achieve this behavior with QT?

Thanks in advance. Kind regards

Is calling service from controller a violation of MVC?

I have seen many code references online they use services directly in the Controller.

public class PersonController : Controller
{
   public ActionResult Index(int personId)
   {
       Person personDataModel = null;
       using(var service = new Personservice())
       {
          personDataModel = service.GetPerson(personId);
       }

       var personVM = MapPersonDataModelToViewModel(personDataModel);

       return View("Index",personVM);
   }
}

As per MSDN, Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI.

Where is the mention of Service? I know people talking about Service layer pattern or SOA architecture. But still is this a violation. A violation for convenience?

For some reason, if I want to do away with services. Then I'll end up changing the controller. And have to build my model. Instead I'm suppose to change only the Model.

I feel Model should have the intelligence to serve the request from Controller either by calling external service or by itself.

public class PersonController : Controller
{
   public ActionResult Index(int personId)
   {
       var personVM = PersonModel.GetPerson(personId);

       return View("Index",personVM);
   }
}

public class PersonModel
{
   public PersonVM GetPerson(int personId)
   {
      Person personDataModel = null;
       //Can either do this
       using(var service = new Personservice())
       {
          personDataModel = service.GetPerson(personId);
       }

       //Or can do this
       personDataModel = GetPersonDataModel(personId);

      var personVM = MapPersonDataModelToViewModel(personDataModel);

      return personVM;
   }
}

I know PersonModel needs re-factoring but that's not the point.

Am I missing something. Please share your valuable thoughts.

Compton pattern error

I am using Voyager 14.04.4. I want to set Compton properly to watch tear-free movies and TV shows. I copied my old conf file into correct folder (from my previous Xubuntu version). I have set Compton to autostart (added "compton -b" to auto-start apps). The problem is, Compton doesnt seem to work properly, whenever I try to run "compton -b" in Terminal, I am getting "Pattern "": PCRE regular expression study failed: (null)". Window tweak compositor is set to off. Compton was installed through "sudo apt-get install compton". Please help!

Autofac Repository Pattern and Unit Of Work

I have searched a little bit and I am confused.

Should I have a repository for each entity or one generic repository for all of them ?

I use Autofac. Generic repository and unit of work class can share same context. Therefore, Does unit of work class have to have generic repository ? Is this anti pattern ?

Can I use extension classes or service layer instead of using other repositories for extension methods which is not shared on generic repository?

First Approach uses a repository and a service for each entity. Unit of work class does not have repositories. Therefore, you should create each repository instead of just creating one unit of work class in caller constructor.

HomeController(IUnitOfWork unitOfWork, IUserRepository userRepository,IOrderRepository orderRepository,IBalanceRepository balanceRepository)

Second Approach uses just a generic repository. It uses extension classes instead of using one repository for each entity. Unit of work class has generic repositories.Therefore, you can just create a unit of work class on caller class constructor.

public HomeController(IUnitOfWork unitOfWork)

In this approach we use one generic class for repositories but we create an object for each entity. If this approach is fine how can I implement it with Autofac ?

Third Approach uses one generic repository and one object for generic repository. It uses generic methods instead of generic class. But generic repository has unit of work class instead of opposite.

public HomeController(IUnitOfWork unitOfWork,IGenericRepository repository)

Which approach should I use ?

Object with attributes of any type with easy storage and iteration

I have an "object" with different attributes stored as key/value. The key is a string and the value can be any basic type. My first idea was using a template class:

template <class T>
class Attribute {
public:
    Attribute<T>(const std::string& key, T value) :
        m_key(key),
        m_value(value)
    {
    }

    ~Attribute(){}

    T getValue() const
    {
        return m_value;
    }

    std::string getKey() const
    {
        return m_key;
    }
private:
    std::string m_key;
    T m_value;
};

But now the problem is that in my object class, I have to declare fields and overload functions for each possible attribute type:

class MyObject {
public:
    MyObject(int value) :
        m_value(value)
    {
    }

    ~MyObject()
    {
    }

    int getValue() const
    {
        return m_value;
    }

    void addAttribute(Attribute<int> attribute)
    {
        m_intAttributes.push_back(attribute);
    }

    void addAttribute(Attribute<double> attribute)
    {
        m_doubleAttributes.push_back(attribute);
    }

    const std::list<Attribute<int> >& getIntAttributes() const
    {
        return m_intAttributes;
    }

    const std::list<Attribute<double> >& getDoubleAttributes() const
    {
        return m_doubleAttributes;
    }

private:
    int m_value;
    std::list<Attribute<int> > m_intAttributes;
    std::list<Attribute<double> > m_doubleAttributes;
};

Moreover, iterating through the attributes is not very comfortable and looking for an attribute of a given name is very difficult:

void showMyObject(const MyObject& myObject)
{
    std::list<Attribute<int> > intAttributes;
    std::list<Attribute<int> >::const_iterator itInt;
    std::list<Attribute<double> > doubleAttributes;
    std::list<Attribute<double> >::const_iterator itDouble;

    std::cout << "Value in myObject " << myObject.getValue() << std::endl;

    intAttributes = myObject.getIntAttributes();
    for(itInt = intAttributes.begin() ; itInt != intAttributes.end() ; itInt++)
    {
        std::cout << itInt->getKey() << " = " << itInt->getValue() << std::endl;
    }

    doubleAttributes = myObject.getDoubleAttributes();
    for(itDouble = doubleAttributes.begin() ; itDouble != doubleAttributes.end() ; itDouble++)
    {
        std::cout << itDouble->getKey() << " = " << itDouble->getValue() << std::endl;
    }
}

FYI, my main function looks like this:

int main(int argc, char* argv[])
{
    MyObject object(123);

    object.addAttribute(Attribute<double>("testDouble", 3.23));
    object.addAttribute(Attribute<double>("testDouble2", 99.654));
    object.addAttribute(Attribute<int>("testInt", 3));
    object.addAttribute(Attribute<int>("testInt2", 99));

    showMyObject(object);

    return 0;
}

I guess if we want to guarantee type safety, there must be somewhere list of functions with the right return type in the signature (getTYPEAttributes in my example).

However, I was wondering if a more elegant solution exists and if a design pattern I'm not aware of could help me to handle this problem correctly.

Correct use of Model in Presenter with MVP-VM Design Pattern

I am self-studying the Model View Presenter View Model Design Pattern in preparation to joining a new project, which will be using the pattern with WinForms (NOT WPF).

In my research I am seeing different uses of the pattern when comes to using Presenter. Some sites I have seen pass in via the constructor the ViewModel object as well as the view, another passes in the model as an interface plus the view, and finally another just the view with instantiation of the model in the presenter class.

With different ways being shown, my question is this, what is the correct implementation of the presenter, should be like MVP with view and model being passed, or doesn't matter what style is being used?

Thanks

Presenter, View, extendable objects

I faced problem in code architectures. I have object, movie (movie has name, and list of pictures) and I have nested views for example:

view1 -> view2

In view1 presenter loads movie by id, receiving movie(id,name). And another presenter in view2 loads list of pictures by movie id and view2 only know about this pictures.

But know I need to show new view from view1 (view1 does not know anything about images yet), and so there is several ways:

  • load all data from main view (view1) using presenter in view1 and pass it to view2
  • create method in view2 for getting list of images by call from view1
  • extend movie model class or convert movie to movieEx (for example) and add list of images to it after loading.

What do you think about most appropriate solution?

Java - Getting derived words from a given root in a file

I'm working on a project of Word Sense Disambiguation and I want to find all the occurrences in a file of a given root e.g. the root is "love" the programme will give us all the words in the file that is derived from "love" like lovely, loved... I did some work but I didn't get what I want!

`

package partenn1;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Partenn1 {

    public static void main(String[] args) {
        int c=0;
        String w = "tissue";

        try (BufferedReader br = new BufferedReader(new FileReader("D:/Sc46.txt")))
        {
            String line;
            while ((line = br.readLine()) != null)
            {
                String[] WrdsLine = line.split(" ");

                boolean findwrd = false;
                for( String WrdLine : WrdsLine )
                {
                    for (int a=0; a<WrdsLine.length; a++)
                    {
                        if ( WrdsLine[a].indexOf(w)!=0)
                        {
                            c++; //It's just a counter for verification of the numbre of the occ.
                            findwrd = true; 
                        }
                    }

                }
            }
            System.out.println(c);
        }
        catch (IOException e) {}
    }
}

`

Strategy pattern or function pointer

In C++ I rather use function pointer to enable special behavior to be selected at runtime in my programme. In Java there are no function pointers and I am obliged to use either the strategy pattern or reflection (or another pattern).

What is the best way to implement this operation especially in C++?

Writing API: what a handle should be

Let's suppose we're writing a library implementing some API. The lib creates some resources (connections/internal data structures/whatever) and returns a handle which then is used to make further calls.

What are recommended ways to represent a handle?

  • Should it be a raw pointer to some internal data structure allocated while creating a session?

  • If it is the case, how do I secure the lib in case API functions are called after close method which deallocates the data handle has pointed to?

If handle is an abstract number (like key in "handle"->"obj" map), won't it affect performance?

What other approaches are possible? Which one should I choose?

If anybody has worked on API's, could you share your experience on the subject?

The question is too wide and abstract, but currently I'm working on very similar task and just don't know how to tackle the problem.

I've been looking through sqlite3 sources, their handle is just a pointer to dynamically allocated structure, they set some magic numbers while opening connection and closing it and checking validity of a handle consists in checking those magic numbers. Is it safe enough?

A matter of good looking code (Related to passing methods as a parameter)

I've been reading up on delegate and passing methods as a parameter in C#, simply because my "OCD" is gnawing me when I look at this code:

 public static T GetSingleItem<T>(string query, params object[] args) where T : new()
{
    using (var db = new SQLiteConnection(DbPath))
    {
        db.Trace = true;
        return db.Query<T>(query, args).FirstOrDefault();
    }
}

public static List<T> GetItems<T>(string query, params object[] args) where T : new()
{
    using (var db = new SQLiteConnection(DbPath))
    {
        db.Trace = true;
        return db.Query<T>(query, args);
    }
}

public static void Insert(object obj)
{
    using (var db = new SQLiteConnection(DbPath))
    {
        db.Trace = true;
        db.Insert(obj);
    }
}

public static void Update(object obj)
{
    using (var db = new SQLiteConnection(DbPath))
    {
        db.Trace = true;
        db.Update(obj);
   }
}

You shouldn't take this question too serious. I know it's not on the top shelf of urgent problems, but I would anyway want to ask the question as it would be nice to know a solution for this.

Question: Is there a way to encapsulate the using statement and the db.Trace in one method and then simply call the rest of the methodcontent e.g. db.Update(obj) from their specific methods?

The obvious problem with passing a partial method as a parameter e.g.

public static T Runner<T>(Func<T> funcToRun)

Is that I'm calling db.Update() from the object instantiated by the using statement.

Any smart solutions to this pattern?

What pattern to use to make chain of convertors?

Okay, I need to make chain of convertors, for example, I have a 3D vector: Vec3 and:

Vec3->[Projector]->Vec2->[Rotator]->Vec2->[Moduler]->float->[Processor]->bool

[Projector], [Rotator] and others are convertors. Convertor can have any type as input, and any type as output. And I'll build it as lib, and end user should be able to make his own convertor and add it to chain.

I've thought about double dispatch:

struct Value;

struct Convertor
{
    virtual void Convert(Value& value);
}


struct Value
{
    virtual void ConvertMe(Convertor& conv)
    {
         conv->Convert(*this);
    }
}

It allows me to give user freedom to subclass Value, but problem is: Convertor should have overload of void Convert(SpecificUserValue& value). Which is not possible with built library.

Is it possible to do such thing? If so, how?

Thank you!

How to refactor a singleton class and avoid doing the same mistakes again

I've started a small application in WPF and used a Singleton class to handle all the application logic. Plus I had a few ObservableCollections there that are binded to DataGrids on the View.

The problem: what was supposed to be a small program started to grow in functionality and the code is now too hard to maintain, reuse and there is a high level of code coupling.

And so I've started to move the code to other classes. For example, I've a class that just handles the File readings. I've made this class static because I just run those methods once (when I need to import data to a database), and when they are finished I don't need those objects anymore and just forget that they exist.

Now I'm considering doing the same for other methods, like the ones that retrieve data form the database.

My doubt is if that is that the correct way to solve the problem? I'm afraid that the use of a static classes will be like a multiplication of singletons.

Replacing troublesome global variable - are singletons acceptable?

I've inherited an old piece of software which makes extensive use of Global variables, which is seeing the usual issues associated with them.

A lot of these Globals I've managed to remove through passing them in (via constructor or method) however one variable (ID) is so ingrained in the application that passing it between objects and methods will become unmaintainable.

To attempt to mitagate this I have replaced ID with a method that can defensively check / provide ID wherever needed, as long as this is a singleton (via IOC container) this will work. I am however very concerned this is going to turn into a anti-pattern.

My questions are:

  • Should I attempt to inject my singleton removing the Global nature of ID (pretty unmaintainable)?

  • Should I use the much rejected 'service' pattern with IOC meaning I reference it directly within methods?

  • Is this actually an acceptable time to use singletons?

This is very much a proof-of-concept at this point but I'd much rather do things properly.

MVP: multiple Views one Place

I am currently working on a web application that should implement the MVP design pattern, and I'm a little bit confused:

  1. The app will only have one Place to show composed by three smaller Views, there's no possibility to go in another Place just to interact with the Views(selecting something from one View will require the other two Views to load some different data and let them the possibility to edit it), is it a good idea to use MVP in this case?
  2. Supposing I will continue using the MVP design pattern, is it correct to have only one Place in which I will have three different Views(Activities)?The question rises because all the web applications that I looked over usually have One Place-One Activity relation and it makes sense because when you surf to another page, it represents another Place with its own Activity(not my case).
  3. Furthermore how should I let the Presenters of each View interact with one another? As I need for example on a ClickEvent in the first View, to announce the other two Views that they should load some data depending on the selected item? Should I use only one Presenter to take care of all the business logic in the end?

mercredi 29 avril 2015

Would you rather to use Facade or Factory for task based solutions desi

Lets assume you want to create a system or user generated task based on the things that needs to be done in your company (Example : send a job for Sales dept to schedule a meeting with vendor) . You may have a queue of tasks waiting for the creation process(User creates the first task, then System generates other tasks for other departments) based on the user request or you may have a simple task for a department to accomplish a single job.

Would you rather to use Facade , Factory or ?

Thanks in advance

What is the appropriate regular expression for this pattern?

I have a text file that contains a course catalog of all CS courses. The actual course itself is pretty simple to find because it is in the beginning of the line and begins with the course. The prerequisite is a bit trickier for me though. I can find the line that has the prerequisites but the prereq courses can be one or multiple and separated by commas and "and". There is also sometimes a line after the prereq sentence that contains other course names but not the prereq itself. Here is a sample of what the prereq file looks like:

CS 4213. Computing for Bioinformatics. (3-0) 3 Credit Hours.
Prerequisite: CS 1173 or another programming course. Emphasizes computing tasks common in bioinformatics: variables, flow control, input/output, strings, pattern matching, arrays, hash tables, functions, access to databases, and parsing data from queries for common bioinformatics tasks. SQL, XML, and BioPerl. May not be applied to the 24 hours of required electives for computer science majors, but may be included for a computer science minor.
CS 4313. Automata, Computability, and Formal Languages. (3-0) 3 Credit Hours.
Prerequisites: CS 3341 and CS 3343. Discussion of abstract machines (finite state automata, pushdown automata, and Turing machines), formal grammars (regular, context-free, and type 0), and the relationship among them.
CS 4353. Unix and Network Security. (3-0) 3 Credit Hours.
Prerequisite: CS 3433. A technical survey of the fundamentals of computer and information security. Issues include cryptography, authentication, attack techniques at both the OS and network level, defense techniques, intrusion detection, scan techniques and detection, forensics, denial of service techniques and defenses, libpcap, libdnet and libnet programming.
CS 4363. Cryptography. (3-0) 3 Credit Hours.
Prerequisites: CS 3341, CS 3343, and CS 3433. A course in pure and applied cryptography, with emphasis on theory. Topics may include conventional and public-key cryptosystems, signatures, pseudo-random sequences, hash functions, key management, and threshold schemes.
CS 4383. Computer Graphics. (3-0) 3 Credit Hours.
Prerequisites: CS 2121, CS 2123, CS 3341, and CS 3343. An introduction to two- and three-dimensional generative computer graphics. Display devices, data structures, mathematical transformations, and algorithms used in picture generation, manipulation, and display.
CS 4393. User Interfaces. (3-0) 3 Credit Hours.
Prerequisite: CS 3443. Study of advanced user interface issues. User interface design, human factors, usability, GUI programming models, and the psychological aspects of human-computer interaction.
CS 4413. Web Technologies. (3-0) 3 Credit Hours.
Prerequisites: CS 3421 and CS 3423. Fundamentals of Web and component technology: markup languages, layout design, client and server side programming, database and Web integration.
CS 4593. Topics in Computer Science. (3-0) 3 Credit Hours.
Prerequisite: Consent of instructor. Advanced topics in an area of computer science. May be repeated for credit when topics vary.
CS 4633. Simulation. (3-0) 3 Credit Hours.
Prerequisites: CS 3341 and CS 3343. Design, execution, and analysis of simulation models, discrete event simulation techniques, input and output analysis, random numbers, and simulation tools and languages.
CS 4713. Compiler Construction. (3-0) 3 Credit Hours.
Prerequisites: CS 3341, CS 3343, CS 3841, and CS 3843. An introduction to implementation of translators. Topics include formal grammars, scanners, parsing techniques, syntax-directed translation, symbol table management, code generation, and code optimization. (Formerly titled “Compiler Writing.”).

This is what I have right now:

Pattern p = Pattern.compile("^(CS [0-9][0-9][0-9][0-9]).*");
        Pattern p2 = Pattern.compile("^Prereq.* ([A-Z]* [0-9][0-9][0-9][0-9]).*");
        while ((line = br.readLine()) != null) {
            Matcher m = p.matcher(line);
            if (m.find()) {
                System.out.println(m.group(1));
            }
            Matcher m2 = p2.matcher(line); 
            if (m2.find()){

                System.out.println("Prereq: "+m2.group(1)+", Occurrences: "+m2.groupCount());
                //System.out.println(line);
            }
    }

And so far this gets all the courses and the first prerequisite or none if there are no prereqs for the course.

CodeIgniter PaymentWall Response body does not match the expected pattern: OK

Pingback wasn't successful. Reason: Response body does not match the expected pattern: OK

Signature base string uid=currency=type=0ref=369e67e903ca0b2261cd342575b8979e

Signature = MD5(Signature base string) 2aa9f1c847d1492b18cd017cdf78290b

this is model.donate.php

<?php

in_file();

class Mdonate{
    protected $registry, $db, $config;
    private $vars = array();
    protected $hash_item = '';
    protected $paypal_ipn_url = 'http://ift.tt/rDmnwQ';
    protected $paypal_ipn_url_ssl = 'www.paypal.com';
    protected $req = 'cmd=_notify-validate';
    protected $post = array();
    protected $paypal_response;
    public $order_details = array();
    protected $pw_ip_white_list = array('174.36.92.186', '66.220.10.3', '174.36.92.186', '174.36.96.66', '174.36.92.187', '174.36.92.192', '174.37.14.28');
    protected $pw_reason_list = array(0     => 'Invalid Reason',
                                      1     => 'Chargeback',
                                      2     => 'Credit Card fraud',
                                      3     => 'Order fraud',
                                      4     => 'Bad data entry',
                                      5     => 'Fake / proxy user',
                                      6     => 'Rejected by advertiser',
                                      7     => 'Duplicate conversions',
                                      8     => 'Goodwill credit taken back',
                                      9     => 'Cancelled order',
                                      10    => 'Partially reversed transaction');

    public function __construct(){
        $this->registry = registry::getInstance();
        $this->db = $this->registry->db;
        $this->config = $this->registry->config;
    }

    public function __set($key, $val){
        $this->vars[$key] = $val;
    }

    public function __get($name){
        return $this->vars[$name];
    }

    public function __isset($name){
        return isset($this->vars[$name]);
    }

    public function get_paypal_packages(){
        return $this->db->query('SELECT id, package, reward, price, currency FROM dmncms_donate_paypal_packages WHERE status = 1 ORDER BY orders ASC')->fetch_all();
    }

    public function check_package($id){
        $count = $this->db->snumrows('SELECT COUNT(id) as count FROM dmncms_donate_paypal_packages WHERE id = '.$this->db->escape($id).' AND status = 1');
        return ($count == 1);
    }

    public function insert_paypal_order($reward, $price, $currency){
        $this->hash_item = md5($_SESSION['name'].$price.$currency.uniqid(microtime(),1));
        $stmt = $this->db->prepare('INSERT INTO dmncms_donate_paypal_orders (amount, currency, credits, account, hash) VALUES(:amount, :currency, :credits, :account, :hash)');
        return $stmt->execute(array(':amount'   => $price, ':currency'  => $currency, ':credits'    => $reward, ':account'  => $_SESSION['name'], ':hash'   => $this->hash_item));  
    }

    public function get_paypal_data(){
        return array('email' => $this->config->load_xml_config('donate|pp_email'), 'item' => $this->hash_item, 'user' => $_SESSION['name']);
    }

    public function gen_post_fields($data){
        $data_array = explode('&', $data);
        foreach($data_array as $value){
            $value = explode ('=', $value);
            if(count($value) == 2)
                $this->post[$value[0]] = urldecode($value[1]);
        }
        foreach($this->post as $key => $value) {        
            $this->req .= "&".$key."=".urlencode($value);
        }
    }

    public function post_back_paypal_fsock(){
        $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";  
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Host: ".$this->paypal_ipn_url_ssl."\r\n";
        $header .= "Content-Length: " . strlen($this->req) . "\r\n";
        $header .= "Connection: close\r\n\r\n";
        $fp = fsockopen('ssl://'.$this->paypal_ipn_url_ssl, 443, $errno, $errstr, 30);
        if(!$fp){
            $this->writelog('PayPal sent fsockopen error no. '.$errno.': '.$errstr.'','Paypal');
            return false;
        } 
        else{
            fputs($fp, $header.$this->req);
            while(!feof($fp)){
                $this->paypal_response = fgets($fp, 1024);
            }
            fclose($fp);
        }
        return true;
    }

    public function post_back_paypal_curl(){
        $request = curl_init();
        curl_setopt_array($request, array(CURLOPT_URL => $this->paypal_ipn_url,
                                          CURLOPT_POST => TRUE,
                                          CURLOPT_POSTFIELDS => $this->req,
                                          CURLOPT_RETURNTRANSFER => TRUE,
                                          CURLOPT_HTTPHEADER => array('Connection: Close'),
                                          CURLOPT_SSL_VERIFYPEER => TRUE,
                                          CURLOPT_SSL_VERIFYHOST => 2,
                                          CURLOPT_FORBID_REUSE => TRUE,
                                          CURLOPT_CAINFO => APP_PATH.DS.'data'.DS.'cacert.pem'));
        $this->paypal_response = curl_exec($request);
        if(curl_errno($request)){
            $this->writelog(curl_error($request), 'Paypal');
            return false;
        }
        curl_close($request);
        return true;
    }

    public function validate_paypal_payment(){
        if(stripos($this->paypal_response, "VERIFIED") !== false){
            if(!$this->check_email()){
                return false;   
            }
            if(!$this->check_order_number()){
                return false;
            }
            switch($this->vars['payment_status']){
                case 'Completed':
                    if($this->vars['tax'] > 0){
                        $this->vars['mc_gross'] -= $this->vars['tax']; 
                    }                   
                    if($this->vars['mc_gross'] == $this->order_details['amount']){
                        if($this->vars['mc_currency'] == $this->order_details['currency']){
                            if($this->check_completed_transaction()){
                                return false;
                            }   
                            if($this->check_pending_transaction()){
                                if($this->update_transaction_status()){
                                    return true;
                                }
                            }
                            else{
                                if($this->insert_transaction_status()){
                                    return true;
                                }
                            }
                        }
                    }
                break;
                case 'Pending':
                    if($this->vars['tax'] > 0){
                        $this->vars['mc_gross'] -= $this->vars['tax']; 
                    }
                    if(!$this->check_completed_transaction() && !$this->check_pending_transaction()){
                        $this->insert_transaction_status();
                    }
                break;
                case 'Reversed': case 'Refunded':
                    $this->decrease_credits($this->order_details['account'], $this->order_details['credits']);
                    $this->update_transaction_status();
                    if($this->config->load_xml_config('donate|pp_punish_player') == 1){
                        $this->block_user($this->order_details['account']);
                    }
                break;
            }
        }
        if(stripos($this->paypal_response, "INVALID") !== false){
            $this->writelog('PayPal sent [status: INVALID] [transaction id: '.$this->vars['txn_id'], 'Paypal');
        }
    }

    private function check_email(){
        if(strtolower($this->vars['receiver_email']) != strtolower($this->config->load_xml_config('donate|pp_email'))){
            $this->writelog('PayPal sent invalid reciever email: '.$this->vars['receiver_email'].'', 'Paypal');
            return false;
        }
        return true;
    }

    private function check_order_number(){
        $count = $this->db->snumrows('SELECT COUNT(id) AS count FROM dmncms_donate_paypal_orders where hash = '.$this->db->escape($this->vars['item_number']));
        if($count == 1){
            $this->order_details = $this->db->query('SELECT amount, currency, account, credits FROM dmncms_donate_paypal_orders where hash = '.$this->db->escape($this->vars['item_number']))->fetch();
            return true;
        }
        else{
            $this->writelog('PayPal sent invalid order [transaction id: '.$this->vars['txn_id'].']', 'Paypal');
            return false;
        }
    }

    private function check_completed_transaction(){
        $count = $this->db->snumrows('SELECT COUNT(id) AS count FROM dmncms_donate_paypal_transactions where transaction_id = '.$this->db->escape($this->vars['txn_id']).' and status = \'Completed\'');
        if($count > 0){
            return true;
        }
        return false;
    }

    private function check_pending_transaction(){
        $count = $this->db->snumrows('SELECT COUNT(id) AS count FROM dmncms_donate_paypal_transactions where transaction_id = '.$this->db->escape($this->vars['txn_id']).' and status = \'Pending\'');
        if($count > 0){
            return true;
        }
        return false;
    }

    private function update_transaction_status(){
        $stmt = $this->db->prepare('UPDATE dmncms_donate_paypal_transactions SET status = :status WHERE transaction_id = :trans_id');
        return $stmt->execute(array(':status' => $this->vars['payment_status'], ':trans_id' => $this->vars['txn_id']));
    }

    private function insert_transaction_status(){
        $stmt = $this->db1->prepare('INSERT INTO dmncms_donate_paypal_transactions (transaction_id, amount, currency, acc, credits, order_date, status, payer_email) VALUES (:trans_id, :gross, :currency, :account, :credits, :time, :payment_status, :payer_email)');
        return $stmt->execute(array(':trans_id' => $this->vars['txn_id'], ':gross' => $this->vars['mc_gross'], ':currency' => $this->vars['mc_currency'], ':account' => $this->order_details['account'], ':credits' => $this->order_details['credits'], ':time' => time(), ':payment_status' => $this->vars['payment_status'], ':payer_email' => $this->vars['payer_email']));
    }

    public function reward_user($acc, $credits){
        $stmt = $this->db->prepare('UPDATE bg_user SET cash = cash + :credits WHERE bg_user = :account');
        $stmt->execute(array(':account' => $acc, ':credits' => str_replace('-', '', $credits)));
    }

    private function decrease_credits($acc, $credits){
        $stmt = $this->db1->prepare('UPDATE bg_user SET cash = cash - :credits WHERE bg_user = :account');
        $stmt->execute(array(':credits' => str_replace('-', '', $credits), ':account' => $acc));
    }

    private function block_user($acc){
        return;
    }

    public function validate_ip_list(){
        return (in_array($_SERVER['REMOTE_ADDR'], $this->pw_ip_white_list));
    }

    public function validate_pw_signature(){
        return (md5('uid='.$this->vars['uid'].'currency='.$this->vars['currency'].'type='.$this->vars['type'].'ref='.$this->vars['ref'].$this->config->load_xml_config('donate|pw_secretkey')) == $this->vars['sig']);
    }

    public function validate_pw_payment(){
        if(!$this->check_reference()){
            if($this->log_pw_transaction()){
                return true;
            }
        }
        else{
            if($this->vars['type'] == 2){
                $this->change_pw_transaction_status();
                if($this->vars['reason'] == 2 || $this->vars['reason'] == 3){
                    $this->block_user($this->vars['uid']);
                }       
                $this->decrease_credits($this->vars['uid'], $this->vars['currency']);   
            }
        }
    }

    private function check_reference(){
        $count = $this->db->snumrows('SELECT COUNT(uid) AS count FROM dmncms_donate_paymentwall WHERE uid = '.$this->db->escape($this->vars['uid']).' AND ref = '.$this->db->escape($this->vars['ref']).'');
        if($count > 0){ 
            return true;
        }
        return false;
    }

    private function log_pw_transaction(){
        $prepare = $this->db->prepare('INSERT INTO dmncms_donate_paymentwall (uid, currency, type, ref, reason, order_date) VALUES (:uid, :currency, :type, :ref, :reason, :time)');
        return $prepare->execute(array(':uid' => $this->vars['uid'], ':currency' => $this->vars['currency'], ':type' => $this->vars['type'], ':ref' => $this->vars['ref'], ':reason' => 'Complete', ':time' => time()));
    }

    private function change_pw_transaction_status(){
        $stmt = $this->db->prepare('UPDATE dmncms_donate_paymentwall SET currency = :currency, reason = :reason, order_date = :order_date WHERE uid =:uid AND ref = :ref');
        $stmt->execute(array(':currency' => $this->vars['currency'], ':reason' => $this->pw_reason_list[$this->vars['reason']], ':order_date' => time(), ':uid' => $this->vars['uid'], ':ref' => $this->vars['ref']));
    }

    public function writelog($logentry, $lgname) {
        $log = '['.$_SERVER['REMOTE_ADDR'].'] ['.(isset($_SESSION['name']) ? $_SESSION['name'] : 'Unknown').'] '.$logentry.'';
        $log_name = APP_PATH.DS.'logs'.DS.$lgname.'_'.date("m-d-y").'.txt';
        $logfile = @fopen($log_name, "a+");
        if($logfile){
            fwrite($logfile, "[".date ("h:iA")."] $log\r\n");
            fclose($logfile);
        }
    }
}

This is view.paymentwall.php / http://ift.tt/1HSEL9w - im using it for pingback adress

<?php 
    if(load::get('errors') != false){
        foreach(load::get('errors') as $errors){
            echo '<div class="notification-box notification-box-error">'.$errors.'</div>';
        }
    }
    if(load::get('pw') == false || load::get('pw') == 0){
        echo '<div class="notification-box notification-box-error">This donation method is disabled.</div>';
    }
    else{
        echo '<div style="/* border: 1px dotted black; *//* -webkit-border-radius: 5px; */-moz-border-radius: 5px;/* border-radius: 5px; */margin-top: 10px;    padding: 10px;    height: auto;    background: rgba(55, 52, 55, 1);    box-shadow: 0 0 4px rgba(0,0,0,.6), 0 1px 1px rgba(0,0,0,.5), inset 0 0 0 1px rgba(255,255,255,.015), inset 0 1px 0 rgba(255,255,255,.05);    -webkit-border-radius: 5px;    -moz-border-radius: 5px;    border-radius: 5px;    /* margin-left: -38px; */    z-index: 1;">
                <div style="padding: 2px; text-align: center;"><iframe src="http://ift.tt/1ErtieI'.load::get('pw_apikey').'&uid='.$_SESSION['name'].'&widget='.load::get('pw_widget').'" width="'.load::get('pw_w_width').'" height="'.load::get('pw_w_height').'" frameborder="0"></iframe></div>
              </div>';
    }
?>

Creating and Implementing an interface using Python?

I have two (2) questions: Firstly, how do I create the FlyBehavior interface using Python? Secondly, how do I implement the FlyBehavior interface in the FlyWithWings class, using Python (see below)? I'm learning Design Patterns by Head First and I want to rewrite the following Java classes using Python

public abstract class Duck {

    // Reference variables for the 
    // behavior interface types
    FlyBehavior flyBehavior;
    QuackBehavior quackBehavior;

    public Duck() {
    }

    // Delegate to the behavior class
    public void performFly(){
        flyBehavior.fly();
    }

    // Delegate to the behavior class
    public void performQuack(){
        quackBehavior.quack();
    }
}

Here is the interface that all flying behavior classes implement

public interface FlyBehavior {
    public void fly();
}

Here is the flying behavior implementation for ducks that do fly

public class FlyWithWings implements FlyBehavior {
    public void fly(){
    System.out.println("I'm flying");
    }
}

Here is what I have so far using Python. Below is my Python abstract Duck class

import abc

class Duck:
    __metaclass__=abc.ABCMeta


    FlyBehavior FlyBehavior;
    QuackBehavior QuackBehavior;

    @abc.abstractmethod
    def __init__():
        return

    @abc.abstractmethod
    def performFly():
        return

    @abc.abstractmethod
    def performQuack():
        return

Here is where I'm stuck trying to create the interface, and trying to implement the interface.

django: loading content to main view

I have written a small django app to manage museum artwork. The app has a map and one view that reloads content every time the user clicks a marker on the map.

Currently, the content of this view is split into several templates that are received as html after a "load" request is sent. I then update the div in the main view with the received html:

// museumPk is the django primary key corresponding to the map marker
$.get("tabs/artists", { "id" : museumPk }, function (html) {
    insert("#artists", html);
});

$.get("tabs/nearby", { "id" : museumPk }, function (html) {
    insert("#nearby", html)
});

$.get("museum", { "id" : museumPk }, function (html) {
    insert("#museum-description", html)
});

For completeness, here's the "museum" template I send after the request is made; this will get inserted in the #museum div:

<a class="thumbnail pull-left" href="{{ museum.åwebsite }}">
    <img src="{{ museum.image.image.url }}" class="media-object" style="width:50px; height:50px;">
</a>
<div class="media-body">
    <h4 class="media-heading">{{ museum.title }}</h4>
    <p>{{ museum.description }}</p>
</div>

My question: is this really the correct way I should be handling things? Is there a less jquery intensive solution? Is there any way to avoid these multiple calls to insert html into my main view, and instead package things in one request?

Is n:1 observable:observer with generics possible in java? ( observer pattern )

I would like to listen your opinions about applying observer pattern.

My goal is to implement one concrete observer class that can listen multiple observable.

If I develop each different observer like below, then it would be simple like below.

public class ConcreteObserver implements EventObserverA , EventObserverB {

    updateEventA(EventA event) {}
    updateEvetnB(EventB event) {}

}

In this case, I should write many different observer/observable classes/interfaces with almost same code snippet inside.

To avoid hassle like above, I'd like to generify observer/ but as you guys know multiple inheritance rule does not allow code like below.

public class ConcreteObserver implements Observer<EventA> , Observer<EventB> {

    update(Observer<EventA> event) {}
    update(Observer<EventB> event) {}

}

Because I have at least double digit Observable events to observe in one concrete observer, I want to avoid implementing every observer/observable pair separately if possible.

I might guess there could be a better pattern for this case than observer pattern, since observer pattern is designed for n:1 observer:observable while my case needs 1:n observer:observable .

Do you guys have any idea/suggestion for this case?

DAO Design Pattern vs DBUnit Code

I am not sure if my DAO or DBUnit Test needs some refactoring. Can somebody please guide on the situation that I am facing?

I have a DAO that gets some data from the DB by getting a Connection object and then it closes all the resources(ResultSet, Statement and Connection).

I am testing this DAO using DBUnit framework where I am doing two DB operations in this DBUnit Test here: 1) Creating a table and then loading data from XML dataset file 2) Testing the actual getDataById(int id) method present in the DAO

The problem is that my second getDataById(id) method is not able to get a DB connnection object because my DAO already closed it while performing step 1 above.

The code snippet that actually releases all the resources is shown below.

DAO.java (Code snippet)

public void releaseResources(ResultSet rs, Statement stmt, Connection cn) {
        System.out.println("rs = " + rs);
        System.out.println("stmt = " + stmt);
        System.out.println("cn = " + cn);
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (cn != null) {
                cn.close();
            }
        } catch (SQLException ex) {
            System.out.println("Exception while closing DB resources rs, stmt or cn......." + ex);
        }
    }

Hence in order to get my DBUnit tests to work I had to overload the above releaseResources() method so that it does not close the connection object which could be used in my getDataById(int id) unit test. Shown below.

**DAO.java (Code snippet with overloaded method) **

//OVERLOADED JUST TO GET DBUNIT TESTS WORKING !!! :(
public void releaseResources(Statement stmt) {
    System.out.println("\nReleasing db resources now.... 1111");
    System.out.println("stmt = " + stmt);
    try {
        if (stmt != null) {
            stmt.close();
        }
    } catch (SQLException ex) {
        System.out.println("Exception while closing DB resources stmt......." + ex);
    }
}

I am not sure if this is right design. Can somebody please guide on as how can I improve this?

Complete code is shown below for further reference.

StateDaoTest.java

public class StateDaoTest {

    protected static Connection connection;
    protected static HsqldbConnection dbunitConnection;
    protected static StateDao dao = new StateDao();

    @BeforeClass
    public static void setupDatabase() throws Exception {
        Class.forName("org.hsqldb.jdbcDriver");
        connection = DriverManager.getConnection("jdbc:hsqldb:mem:my-project-test;shutdown=true");
        dbunitConnection = new HsqldbConnection(connection, null);
    }

    @Before
    public void createTable() throws SQLException {
        dao.setConnection(connection);
        dao.createTables();
    }

    protected IDataSet getDataSet(String name) throws Exception {
        InputStream inputStream = getClass().getResourceAsStream(name);
        assertNotNull("file" + name + " not found in classpath", inputStream);
        Reader reader = new InputStreamReader(inputStream);
        FlatXmlDataSet dataset = new FlatXmlDataSet(reader);
        return dataset;
    }

    @AfterClass
    public static void closeDatabase() throws Exception {
        System.out.println("\ninto the closeDatabase() method...");
        System.out.println("connection = " + connection);
        System.out.println("dbunitConnection = " + dbunitConnection);
        if (connection != null) {
            connection.close();
            connection = null;
        }
        if (dbunitConnection != null) {
            dbunitConnection.close();
            dbunitConnection = null;
        }
    }

    @Test
    public void testGetStateById() throws Exception {
        IDataSet setupDataSet = getDataSet("/states.xml");
        DatabaseOperation.CLEAN_INSERT.execute(dbunitConnection, setupDataSet);
        State state = dao.getStateById(1);
        assertNotNull(state);
        assertEquals("Pennsylvania", state.getName());
        assertEquals("PA", state.getStateCode());
        assertNotNull(state.getTaxPct());
        assertEquals("Y", state.getActive());
    }

}

StateDao.java

public class StateDao {

    private Connection connection;

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    //added for dbunit tests
    public void createTables() throws SQLException {
        String sql = "CREATE TABLE states (stateId INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1), "
                + "stateCd VARCHAR(10), name VARCHAR(20), taxPct NUMERIC, active CHAR(1))";
        Statement stmt = null;
        try {
            stmt = connection.createStatement();
            stmt.execute(sql);
        } finally {
            releaseResources(stmt);
        }
    }

    public State getStateById(long id) {
        String sql = "SELECT * FROM states WHERE stateId = " + id;

        Statement stmt = null;
        ResultSet rs = null;
        State state = null;

        System.out.println(sql);

        try {
            stmt = connection.createStatement();
            rs = stmt.executeQuery(sql);
            while (rs != null && rs.next()) {
                String stateId = StringUtils.defaultString(rs.getString("stateId"));
                String stateCd = StringUtils.defaultString(rs.getString("stateCd"));
                String name = StringUtils.defaultString(rs.getString("name"));
                String taxPct = StringUtils.defaultIfEmpty(rs.getString("taxPct"), "0");
                String active = StringUtils.defaultString(rs.getString("active"));
                state = new State(new Integer(stateId), stateCd, name, new BigDecimal(taxPct), active);
                System.out.println("state = " + state);
            }
            System.out.println("state = " + state);
        } catch (SQLException ex) {
            System.out.println("Exception whiile fetching data for a state......." + ex);
        } finally {
            releaseResources(rs, stmt, connection);
        }
        return state;
    }

    public void releaseResources(ResultSet rs, Statement stmt, Connection cn) {
        System.out.println("\nReleasing db resources now....2222");
        System.out.println("rs = " + rs);
        System.out.println("stmt = " + stmt);
        System.out.println("cn = " + cn);
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (cn != null) {
                cn.close();
            }
        } catch (SQLException ex) {
            System.out.println("Exception while closing DB resources rs, stmt or cn......." + ex);
        }
    }

    //added for dbunit tests
    public void releaseResources(Statement stmt) {
        System.out.println("\nReleasing db resources now.... 1111");
        System.out.println("stmt = " + stmt);
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException ex) {
            System.out.println("Exception while closing DB resources stmt......." + ex);
        }
    }  

}

How to have buttons persist through views while maintaining same functionality

I'm just getting into ios development and I'm wondering how to accomplish this.

Say for example I have 3 screens - I want each of those screens to have the same 1 button that links to the same place whether you tap it on screen 1 2 or 3.

Is there a way to accomplish this without having a separate method for each view controller?

Also if a solution is too much to type out, are there any good references/guides I can look at for this?


Edit: Another example in case it is a bit confusing - having a login button in the same position across 5 different screens that all take you to the same login screen

How to handle python objects built from a web API that have references to each other?

I'm building a client library for a web API that exposes some objects like this:

# objs/foo/obj_id_1
{id: "foo_id_1"
 name: "your momma"
 bar: "bar_id_2"}

# objs/bar/obj_id_1
{id: "bar_id_2"
 name: "puh-lease"
 foo: "foo_id_1"}

So, objects of type foo have a reference to objects of type bar and vice versa.

In my python client library, I build python objects out of this API data. A Foo instance will have a bar attribute containing a Bar instance instead of just the id of the bar and a Bar instance has a reference to a Foo instance in the foo attribute.

My python classes have save and refresh methods that POST or GET from the web API, and they do this for sub-objects. For example, if I call a_foo.refresh(), this will also automatically call a_foo.bar.refresh().

The above is a very simplified example, and there might be many different classes all referring to the same instance of bar or foo or any of the many other types of objects we get.

I think my question is actually two questions:

  1. What is a good design or strategy to ensure that when I build an object from api data that all of its references to other objects point to the same object if I've already built that object from previous api requests?
  2. When I call save or refresh what's a good design or strategy to prevent an infinite loop when two or more objects refer to each other?

HTML+CSS template, please explain

Can someone explain how to create html+css template responsive. Like in this image. Mby some generator or something. I don't know anything about css or html. I just need this template for my to do list in this summer.

http://ift.tt/1DBfaMe

P.s. - The grey sidebars are backgroung image.

Thanks for any help, Gurkis.

Grails design pattern for parallel queries using dynamic finders

Problem: We're querying our database with a lot of entries. The overall application performance is okay. But I think it could be better if our bottleneck, querying a special table, could be done parallel.

We are using for that dynamic finders like:

Object.findAllByObjectCollectionAndParentIsNullAndDeletedByUserIsNull(objectCollection, [sort: 'attr1.number', fetch: [objectType: 'eager']])

I think about this solution: Dividing the query into 2 steps.

  1. The first step loads only the Ids in a sorted way.
  2. The second step (could be done in parallel threads) loads the objects itself by the id and inserts it into the resultset.

I already googled for some hints about that, but find nothing.

  1. Is it possible, that it makes no sense?
  2. Or is there already a adequate solution in grails standard/extensions?
  3. If it makes sense and there is no solution: Can someone give me a hint implementing it? But, we need the ids in that sorted manner, explained in the example.

We're using grails 2.3.11, hibernate:3.6.10.13 with jdk 1.7 under it.

How to choose design pattern

I am learning Design Pattern and I have a question.

For example, here is the first design.
Shape
Shape->Red Circle
Shape->Blue Circle
Shape->Red Square
Shape->Blue Square
...

Second design
Shape
Shape->Circle
Shape->Square
Shape->Circle->Red Circle
Shape->Circle->Blue Circle
Shape->Square->Red Square
Shape->Square->BlueSquare
...

I know that different designs should fit different situations, and I would like to ask the strength and weakness for these two designs. For example, the complexity of code and the independence of different part of code.

JavaScript scopes confusion with namespaces

I playing around with namespaces convention and attached code which confusing me a little bit.

MYOBJECT = {
     prop1: (function(){
         console.log(this.prop2); 
         // returning undefined as the window property
     })(),
     prop2: function(){
         console.log(this.prop2); 
         // returning prop2 function as the MYOBJECT  property
     },    
 }
 MYOBJECT.prop2();

JSFIDDLE

If I understand this situation, that mean when function is invoked, MYOBJECT is not initialized yet so this in that case is window (but I am not sure why it is window). That mean I cannot access prop2 from prop1 when prop1 is auto invoking function.

Of course I can create MYOBJECT.init where I will invoke all necessary functions, but I feel that this solution making mess in the code and forcing me to unnecessary repetations:

MYOBJECT = {
     init: function(){
         this.prop1();
         this.prop2();
     },
     prop1: (function(){
         console.log(this.prop2);
     }),
     prop2: function(){
         console.log(this.prop2);
     },
 }
 MYOBJECT.init();

It will be really nice to make it work like that:

MYOBJECT = {
    prop1: (function(){
         console.log(this.prop2);
    })(),
    prop2: (function(){
         console.log(this.prop2);
    })(),
}

But as established, it will not work.

Because in my system I am creating a lot of similar objects I want to automate initialization process, I had and idea to use a class which will do it for me:

AutoInit = function(properties){
    this.init(properties); 
}
AutoInit.prototype.init = function(properties){
    var key;
    for(key in properties){
        // it will init only properties starts with '_'
        if(properties.hasOwnProperty(key) && key.indexOf('_') === 0){
            properties[key]();
        }
    }
}


MYOBJECT = new AutoInit({
    _prop1: function(){
        console.log(this._prop2);
    },
    _prop2: function(){
        console.log(this._prop1);
        // public        
    },
});

JSFIDDLE

It works but It is not really fast solution, I am looking for something better but I cannot find.

My purpose is to have a namespaces structure where I will be able to use auto invoking functions which all of them will have access to another properties of the namespace. Any help will be appreciated.

Use of ValueObjects

I am developing with Entity Framework (Database First and Code First). Most of the time, I am using entities in my domain models, mapped to dedicated tables. In DDD, there is the concept of ValueObjects, that should have no identity and should be immutable. Based on your experience with DDD, how do you use ValueObjects ? Is that a concept that emerges from creating the model (for instance, when it deals with read-only data, parameters...) or is there any strategic behaviour that is expected or deductible from stating that an object should be designed like a ValueObject (or not), or should be immutable (or not) ?

Many thanks,

I have to design a shopping cart

I have to implement a shopping cart where i can add an item and on top of it add some accessories for example TV is an item and HDMI cable as its accessory.

I can also add or remove the accessories as and when wanted . Which design pattern i should consider for this?

I thought of decorator for adding accessories on top of item.But in decorator once i added i cannot remove an element.

Design patterns: exposing notifications using a protocol

I have got several types of a logic controller class that handle the communication with a remote resource. To do so each class uses an instance of a network controller class that deals with the connection details: connects to a resource, sends data, receives data. The logic controller classes are notified of data changes from the network controller class using notifications. So in my current solution each logic controller class registers for the notifications and implements specific functions to deal with them differently.

However, if I want to do proper code engineering, I wonder whether it would be more robust to use protocols and delegation.

I wonder if I could define which methods the logical controller classes need to implement in order to receive the notification. However I am not sure if this makes sense and is correct because I do not want inheritance here.

Any suggestion?

mardi 28 avril 2015

In Java, how do I call the method of a overridden class from an instance of the overriding class

I am new to Java Inheritance. Please see the code for my parent class called Term:

public class Term {

  public String value;
  public void setValue(String value)
  {
    this.value=value;
  }

  public String getValue()
  {
    return value;
  }

}

Now class OperatorTerm extends Term

public class OperatorTerm extends Term {

  public static Operator type;

  public static boolean equals(String value)
  {
    String regex="(\\++)|(-+)|\\*|/";
    boolean isOperand=value.matches(regex);
    return isOperand;
  }

  public void assignType(String value)
  {
    if(value.equals("+"))
      type=Operator.ADD;
    else if(value.equals("-"))
      type=Operator.SUBTRACT;
    else if(value.equals("*"))
      type=Operator.MULTIPLY;
    else if(value.equals("/"))
      type=Operator.DIVIDE;
    else if(value.equals("++"))
      type=Operator.INCREMENT;
    else
      type=Operator.DECREMENT;
    }
  }

I am creating an OperatorTerm object like this in another class:

public static Term getTerm(String termValue)
{
  Term newTerm=null;
  if(ValueTerm.equals(termValue))
    newTerm=new ValueTerm();
  else if(ReferenceTerm.equals(termValue))
    newTerm=new ReferenceTerm();
  else if(OperatorTerm.equals(termValue))
  {
    newTerm=new OperatorTerm();
  }
  return newTerm;
}

In the last elseif statement, I want to do the following newTerm.assignType. assignType is a method in the OperatorTerm class but it is not present in the Term class. I am unable to do so, and I am wondering if someone can guide me on how can I use newTerm to access the methods of OperatorTerm class

I am creating an object of the overridden class using

Whats the point of the interface?

I have this code where I am using the proxy pattern:

static void Main() {

    Driver d = new Driver(16);
    Driver d2 = new Driver(26);

    ICar p = new ProxyCar(d);
    ICar p2 = new ProxyCar(d2);

    Console.WriteLine(p.DriveCar());
    Console.WriteLine(p2.DriveCar());
}

}

interface ICar
{
    string DriveCar();

}

public class ProxyCar : ICar
{
    Driver driver;
    ICar realCar;
    public ProxyCar(Driver driver)
    {
        this.driver = driver;
        realCar = new Car();
    }



    public string DriveCar()
    {
        string result;

        if (driver.Age <= 16)
            result= "Sorry, the driver is too young to drive.";
        else
            result = realCar.DriveCar();

        return result;
    }
}


public class Car:ICar
{
    public string DriveCar()
    {
        return "Driving car!";
    }


}

public class Driver
{
    private int _age;

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }

    public Driver(int age)
    {
        _age = age;
    }
}

But I cant see the reason to use this Interface ICar. I could just use the code like this without the interface and it will work just fine:

static void Main() {

    Driver d = new Driver(16);
    Driver d2 = new Driver(26);

    ProxyCar p = new ProxyCar(d);
    ProxyCar p2 = new ProxyCar(d2);

    Console.WriteLine(p.DriveCar());
    Console.WriteLine(p2.DriveCar());
}

}

public class ProxyCar 
{
    Driver driver;
    Car realCar;
    public ProxyCar(Driver driver)
    {
        this.driver = driver;
        realCar = new Car();
    }



    public string DriveCar()
    {
        string result;

        if (driver.Age <= 16)
            result= "Sorry, the driver is too young to drive.";
        else
            result = realCar.DriveCar();

        return result;
    }
}


public class Car
{
    public string DriveCar()
    {
        return "Driving car!";
    }


}

public class Driver
{
    private int _age;

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }

    public Driver(int age)
    {
        _age = age;
    }
}

So why should I use the ICar interface?

Why use "getObject" method when writing a Factory class?

Typically a Factory class contains a method like getObject.

Thereby

class Factory
{
    private $type;

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

    function getObject()
    {
        //example for brevity only to show use of $type variable
        if ($this->type) $object = new $type();
        return $object;
    }
}

Question: Why not return object straight via constructor?

class Factory
{
    function __construct($type)
    {
        if ($type) $object = new $type();
        return $object;
    }

}

Derived class dependant function

I have base class DataProcessor. It is base class for calculators of position in some coordinate system. So, for example, it can have descendants like: SphericDataProcessor, CartesianDataProcessor. There is base class CookedDataCatalogue, which is base class for containers of some objects' positions. So every DataProcessor should be able put it's data to every CookedDataCatalogue. I can imagine something like this:

class CookedDataCatalogue
{
    virtual void Transform(DataProcessor* dp) = 0;

    virtual void PutData(???) = 0;
}


class CookedDataCatalogue1 : public CookedDataCatalogue
{
    void Transform(DataProcessor* dp) override
    {
        dp->TransformTo(this);
    }
}

class CookedDataCatalogue2 : public CookedDataCatalogue
{
    ...
}

class CookedDataCatalogue3 ...

class DataProcessor
{
    virtual void Process() = 0;

    virtual void TransformTo(CookedDataCatalogue1* c) = 0;
    virtual void TransformTo(CookedDataCatalogue2* c) = 0;
    virtual void TransformTo(CookedDataCatalogue3* c) = 0;
}

But I don't like it. First of all void Transform(DataProcessor*) migrates from base class to all children. Second, if I build it as library, other user can not add his own CookedDataUserCatalogue, because he can't add another void TransformTo(CookedDataUserCatalogue). Third, I don't know how to write function PutData(), because every Catalogue uses his own data to contain. Should it be templated?

What is a solution? Is there any programming pattern, that I missed?

Generic design mixed with curiously recurring template pattern. C++

Consider this kind of problem. I have a Base class and three classes derived from Base. For instance: DerivedA, DerivedB and DerivedC. Each derived class has its unique container. Hence DerivedA has std::vector<int>, DerivedB has std::set<int> and DerivedC has std::map<int, std::string>. And I want an interface in Base to access the container of derived class on which it is currently pointed to.

Base* d1 = new DerivedA;
for(std::vector<int>::iterator iter = d1->begin(); iter != d1->end(); ++iter)
{
     //processing
}

I tried to wrap each container to separate class and keep a pointer of their base in the Base class.

class CollA;

template<class T>
class traits;

template<>
class traits<CollA>
{
  public:
  typedef vector<int> container; 
};


template<class T>
class Coll
{
  public:
    typedef typename traits<T>::container container;
    typename container::iterator begin() const
    {
    }
};


class CollA : public Coll<CollA>
{
  typedef traits<CollA>::container container;
  public:
    container::iterator begin()
    {
      return V.begin();
    }
    private:
    vector<int> V;
};

class Base
{
  public:
    Base()
    {
    }
    // what to do here? I must keep a pointer to Coll; But Coll itself is a template
};

Suggest me something. I am kind of lost in this horrible design.

Refactor method in Java: What pattern should I apply?

I developed an application in Java and I am refactoring it. I've just realized that I have several methods that perform almost the same action, and they have similar names as well:

RestrictedPersonServiceImpl.canViewPersonDetails

RestrictedPersonServiceImpl.isSubjectRestrictedToWorker

RestrictedPersonServiceImpl.isAnySubjectRestricted 

RestrictedPersonServiceImpl.isSubjectRestricted 

RestrictedPersonServiceImpl.isAnySubjectOfSubgroupRestrictedToWorker

I am pretty sure that it has to be a programming pattern to apply to deal with this situation. The solution that came to my mind before is to merge all of these methods in one and determining the behaviour by a parameter.

Is there a better choice?

Thanks everyone.

Cache handling with RXJava

I'm trying to implement this workflow with rxJava but i'm sure if i'm misusing or doing stuff wrong.

  • User asks to login
  • If a loginResult is available in cache then "emit" the cached LoginResult
  • Else actually perform the request to the webservice and cache the result if everything is successfull
  • If an error occurs retry at most 3 times and if there is a 4th time then purge the cache.

Here is my full snippet of code.

public class LoginTask extends BaseBackground<LoginResult> {
  private static CachedLoginResult cachedLoginResult = new CachedLoginResult();
  private XMLRPCClient xmlrpcClient;
  private UserCredentialsHolder userCredentialsHolder;

  @Inject
  public LoginTask(XMLRPCClient client, UserCredentialsHolder userCredentialsHolder) {
    this.xmlrpcClient = client;
    this.userCredentialsHolder = userCredentialsHolder;
  }

  @Override
  public LoginResult performRequest() throws Exception {
    return UserApi.login(
        xmlrpcClient,
        userCredentialsHolder.getUserName(),
        userCredentialsHolder.getPlainPassword());


  }

  @Override
  public Observable<LoginResult> getObservable() {
    return cachedLoginResult.getObservable()
        .onErrorResumeNext(
            Observable.create(
                ((Observable.OnSubscribe<LoginResult>) subscriber -> {
                  try {
                    if (!subscriber.isUnsubscribed()) {
                      subscriber.onNext(performRequest()); // actually performRequest
                    }
                    subscriber.onCompleted();
                  } catch (Exception e) {
                    subscriber.onError(e);
                  }
                })
            )
                .doOnNext(cachedLoginResult::setLoginResult)
                .retry((attempts, t) -> attempts < 3)
                .doOnError(throwable -> cachedLoginResult.purgeCache())
        );
  }


  private static class CachedLoginResult {
    private LoginResult lr = null;
    private long when = 0;

    private CachedLoginResult() {
    }

    public boolean hasCache() {
      return lr != null && when + TimeUnit.MILLISECONDS.convert(30, TimeUnit.MINUTES) < System.currentTimeMillis();
    }

    public void setLoginResult(LoginResult lr) {
      if (lr != null) {
        if (this.lr == null) {
          this.lr = lr;
          this.when = System.currentTimeMillis();
        }
      }
    }

    public void purgeCache() {
      this.lr = null;
      this.when = 0;
    }

    public Observable<LoginResult> getObservable() {
      return Observable.create(new Observable.OnSubscribe<LoginResult>() {
        @Override
        public void call(Subscriber<? super LoginResult> subscriber) {
          if (!subscriber.isUnsubscribed()) {
            if (hasCache()) {
              subscriber.onNext(lr);
              subscriber.onCompleted();
            } else {
              subscriber.onError(new RuntimeException("No cache"));
            }
          }
        }
      });
    }
  }
}

Since i wan't able to find any similar examples and i started "playing" with rxjava just 1 day ago i'm unsure of my implementation.

Thank you for your time.

Is there any existing Java Design Pattern for writing JUnit?

I want to implement JUnit testing framework from scratch for already existing project so that I would like to follow some design pattern

  1. Is there any design pattern exists for junit?
  2. Is JUnit implemented by design pattern?
  3. If not, Is there any anything to considered when implementing junit from scratch?

Is Parallel.ForEach obsolete. old, out of fashion?

Good day,

Parallel execution can be achieved through multiple ways. From strictly manual "multithreading" to using various "helpers" created by Microsoft. One of those helpers is the Parallel class.

One of my colleagues is insisting that Parallel.ForEach (or Parallel class overall) is "old" and shouldn't be used. Instead, he says, one should use async operations. In other words you should use Task.WhenAll() instead of ParallelForEach() .

When asked why not use ParallelForEach(), when this is exactly what was needed - multiple expensive operations executed in parallel, he replied that ParallelForEach is old and that Microsoft recommends using async/await wherever possible.

I searched all over MSDN and Stackoverflow and everywhere I could but I couldn't find anything pointing at the necessity of using async/await instead of .Parallel. While you often can achieve similar results by interchanging these tools it doesn't mean that Parallel.ForEach is obsolete. Or does it?

Anyone has a link to some "best practices" or "recommendations" by a reputable body (MSDN?) that would say that Parallel.ForEach is being phased out and one needs to stick with creating, running and awaiting tasks?

Please do not post answers related to Parallel VS Async for this is not the question. The question is: Since you can make tasks run in parallel using async/await WhenAll (WaitAll etc), does it make Parallel class obsolete, old, or not fashionable in .NET 4.5 onward?

Database: A design pattern for category features

I work for a system which has these tables:

products , categories , features

User wants to add some feature like color dynamically.

Which of this following ways are true?

First one:

Product             category                feature
----------------    ----------------        ----------------------------
pro_id (PK)         cat_id (PK)             feature_id (PK)
pro_name            cat_name                fea_name
cat_id (FK)         feature_id (FK)

We add a feature like color, then in category we choose that feature and add it to category table. Then we access for all product in that category.

But there is a pleonasm. Because when two category wants to have color feature, we must repeat feature_id column in category table.

Second one:

Product             category                name_feature
----------------    ----------------        ----------------------------
pro_id (PK)         cat_id (PK)             name_feature_id (PK)
pro_name            cat_name                cat_id (FK)
cat_id (FK)                                 color
                                            ...

When we enter a category, we create a table for that category. For example laptop category with color feature. We create a table called laptop_feature with features in column.

Which way is good? (Categories is limited)

design pattern to use utility app connecting to internet

This may be a generic question but still i need suggestion/guidance on which design pattern or architecture to follow for developing this app.

The app is for premium users(for iPhone) on airport and will be able to access the internet at higher speed and on multiple devices simultaneously. I'm planning to go for Singleton,Factory,MVC patterns and client-server architecture for the app. What-all things do i need to re-think and then design the app or are above patterns sufficient to go ahead ?

thanks

In abstract factory pattern the main abstract factory class, Does it always have to be an abstract class?

All the example i see of Abstract factory Pattern They use an abstract class to give the Abstraction for factories.
Is it always required to use abstract class?

Given the circumstances we can happily use Interface.
If we use interface does it going to violate the Design principle?

Example I was Reading

Tutorials Point
oodesign

how to parse a particular output like in rows as the output comes in a clubbed way in python?

when i run the below code the ouptut comes as such. I need the output to show in rows AND only the values under the caption.

Desired output:

caption : 3PAR
          3PAR

Actual output:

('Caption                          DeviceID             Model                            Partitions  Size         \r\r\n3PARdata VV SCSI Disk Device     \\\\.\\PHYSICALDRIVE19  3PARdata VV SCSI Disk Device     0           1069286400   \r\r\nHP P2000 G3 FC SCSI Disk Device  \\\\.\\PHYSICALDRIVE1   HP P2000 G3 FC SCSI Disk Device  1           49993251840  \r\r\nHP HSV360 SCSI Disk Device       \\\\.\\PHYSICALDRIVE7   HP HSV360 SCSI Disk Device       4           1069286400   \r\r\nHP HSV360 SCSI Disk Device       \\\\.\\PHYSICALDRIVE27  HP HSV360 SCSI Disk Device       0           1069286400   \r\r\nHP HSV360 SCSI Disk Device       \\\\.\\PHYSICALDRIVE5   HP HSV360 SCSI Disk Device       0           1069286400   \r\r\nHP P2000 G3 FC SCSI Disk Device  \\\\.\\PHYSICALDRIVE23  HP P2000 G3 FC SCSI Disk Device  1           49993251840  \r\r\n3PARdata VV SCSI Disk Device     \\\\.\\PHYSICALDRIVE13  3PARdata 

Code:

p5=subprocess.Popen("rsh -l Administrator 10.10.11.37 \"wmic diskdrive list brief\"",stdout=subprocess.PIPE, shell=True)


result = p5.communicate()
status = p5.wait()
print(result),

What would be the correct design here (encapsulation, polymorphism, inheritance)?

Assuming I have an interface and 3 or 4 classes that implement the interface. Now let's say I have another method but it is relevant only for one or two implementing classes.

So as I see it there are two approaches

  1. Declare the method in the interface, implement in all the classes. In classes that the method is not relevant - throw "not supported" exception.
  2. Declare the method only in the implementing classes where relevant but then you have to downcast the instance from interface type to the specific type in order to call the method. So would be your design here and why?

lundi 27 avril 2015

DDD Bounded Contexts with Onion Architecture

I have the following Onion Architecture framework.

  • Domain
    • Entities - For my domain entities
    • Interfaces - For my domain interfaces
    • Services - For my domain services
  • Infrastructure
    • Data - For Fluent NHibernate persistence
    • Interfaces - For infrastructure interfaces
    • Logging - Just an interface for logging in case I want to switch out my logging library to something else.
    • Dependency Resolution - Most of my IoC registrations goes in here.
  • Services
    • Interfaces - Application service interfaces goes in here, they will get implemented in the UI project.
  • Tests
    • Infrastructure Tests - For testing infrastructure services etc.
    • Domain Tests - For testing domain models and services
  • Web
    • UI - User interface project where I implement application services, user interface, etc ...

With Domain Driven Development one would identify the Bounded Contexts. Most of the literature on the internet states that each Bounded Context needs to be abstracted into their own project or namespace.

  1. Is my approach then incorrect for having all my Domain Models in one project and all my Domain Services in another project? Does it really matter not having different bounded context's in different namespaces or projects?
  2. If you have a Model A which is used my Bounded Context A, but Bounded Context B, Bounded Context C, etc also needs to use the exact same Model A, Do you allow them to use that exact same model, or do you create a new model for each Bounded Context?

I am new to DDD so sorry if this question is a dumb question. I find myself understanding something better if I ask a question and get a good explanation as an answer.

Any Help will be much appreciated.

What is the correct regular expression for finding specific pattern in these lines?

So I have one large file that contains a bunch of weather data. I have to allocate each line from the large file into its corresponding state file. So there will be a total of 50 new state files with their own data.

The large file contains ~1 million lines of records like this:

COOP:166657,'NEW IBERIA AIRPORT ACADIANA REGIONAL LA US',200001,177,553

Although the name of the station can vary and have different number of words.

This is the regular expression I am using:

Pattern p = Pattern.compile(".* ([A-Z][A-Z]) US.*"); 
Matcher m = p.matcher(line);

When I run my program there are still instances of lines in which the pattern could not be found.

This is my program:

package climate;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This program will read in a large file containing many stations and states,
 * and output in order the stations to their corresponding state file.
 * 
 * Note: This take a long time depending on processor. It also appends data to
 * the files so you must remove all the state files in the current directory
 * before running for accuracy.
 * 
 * @author Marcus
 *
 */

public class ClimateCleanStates {

    public static void main(String[] args) throws IOException {

        Scanner in = new Scanner(System.in);
        System.out
                .println("Note: This program can take a long time depending on processor.");
        System.out
                .println("It is also not necessary to run as state files are in this directory.");
        System.out
                .println("But if you would like to see how it works, you may continue.");
        System.out.println("Please remove state files before running.");
        System.out.println("\nIs the States directory empty?");
        String answer = in.nextLine();

        if (answer.equals("N")) {
            System.exit(0);
            in.close();
        }
        System.out.println("Would you like to run the program?");
        String answer2 = in.nextLine();
        if (answer2.equals("N")) {
            System.exit(0);
            in.close();
        }

        String[] statesSpaced = new String[51];

        File statefile, dir, infile;

        // Create files for each states
        dir = new File("States");
        dir.mkdir();


        infile = new File("climatedata.csv");
        FileReader fr = new FileReader(infile);
        BufferedReader br = new BufferedReader(fr);

        String line;
        System.out.println();

        // Read in climatedata.csv
        // Probably need to implement ClimateRecord class
        final long start = System.currentTimeMillis();
        while ((line = br.readLine()) != null) {
            // Remove instances of -9999

            if (!line.contains("-9999")) {



                        Pattern p = Pattern.compile("^.* ([A-Z][A-Z]) US.*$"); 
                        Matcher m = p.matcher(line);
                        String stateFileName = null;

                        if(m.find()){
                            //System.out.println(m.group(1));
                            stateFileName = m.group(1);
                        } else {
                            System.out.println("Could not find abbreviation");
                        }

                        /*
                        stateFileName = "States/" + stateFileName + ".csv";
                        statefile = new File(stateFileName);

                        FileWriter stateWriter = new FileWriter(statefile, true);
                        stateWriter.write(line + "\n");
                        // Progress reporting
                        System.out.printf("Writing [%s] to file [%s]\n", line,
                                statefile);
                        stateWriter.flush();
                        stateWriter.close();
                        */





            }
        }
        System.out.println("Elapsed " + (System.currentTimeMillis() - start) + " ms");
        br.close();
        fr.close();
        in.close();

    }

}

Factory Pattern to build many derived classes

I have a factory object ChallengeManager to generate instances of a Challenge object for a game I'm building. There are many challenges. The constructors for each Challenge class derivation are different, however there is a common interface among them, defined in the base class.

When I call manager.CreateChallenge(), it returns an instance of Challenge, which is one of the derived types.

Ideally, I would like to keep the code for the object construction inside the derived class itself, so all the code related to that object is co-located. Example:

class Challenge {}

class ChallengeA : Challenge {
  public static Challenge MakeChallenge() {
    return new ChallengeA();
  }
}

class ChallengeB : Challenge {
  public static Challenge MakeChallenge() {
    return new ChallengeB();
  }
}

Now, my ChallengeManager.CreateChallenge() call only needs to decide the class to call MakeChallenge() on. The implementation of the construction is contained by the class itself.

Using this paradigm, every derived class must define a static MakeChallenge() method. However, since the method is a static one, I am not able to make use of an Interface here, requiring it.

It's not a big deal, since I can easily remember to add the correct method signature to each derived class. However, I am wondering if there is a more elegant design I should consider.

What is the Meteor pattern for file inclusion called?

I really like the Meteorjs style of automagically importing every file in your project in a specified order. Does that style of coding have a name? Sandbox, openbox, open coding?

Detect interesting patterns machine learning

I am starting work with a machine learning project for data risk management. Assume we have 1 million unstructured text documents, with some meta data like Data Owner for each text.(We can do any assumption)

One of the goal is to detect interesting patterns. But I do not really know what does this requirement mean. Could anybody tell me this? or give some related key words? (not ask for implementation) it's a quite open question. Hope interesting ideas!!

Android - How to manage multiples user levels and types

I have project be used by different group then user.

For example: one group is secretary user, another is the admin user, medical user.

Currently my code this so below:

 if(App.getInstance().getCustomer().isAdmin())
        replaceFragment(R.id.view_main,new AdminFragment);
 if(App.getInstance().getCustomer().isMedical())
        replaceFragment(R.id.view_main,new MedicalFragment);

My question is, what is the way more sophisticated to accomplish this control

Design feedback

Can you please give me a feedback about this design implementation ?

Suppose i need to calculate a salary of an Employer, this salary is depending on something called : REGIME, the REGIME is either newRegime or OldRegime.

Suppose the calculation should be as following :

If (newRegime) then Salary = 10; If (oldRegime) then Salary = 30 if 30 is superior then newRegime.

I tought about this implementation :

An interface : SalaryBusiness

    public interface SalaryBusiness {

    double getSalary();
}

A Class SalaryCalculator :

public class SalaryCalculator implements SalaryBusiness {

// Some shared fileds, useful for the calculation....

// A public constructor
 public SalaryCalculator()
{
}

protected SalaryCalculator(Object anObject)
{

// the anObject is useful to init the shared fileds 
initFields(anObject)
}
//Method that creat a Regime 
public final SalaryCalculator getRegimeCalculator(Object anObject)
{
if (newRegimeCalculator.equals(anObject.getRegime))
{
return new newRegimeCalculator(anObject);
}else {

NewRegimeCalculator newRegimeCalcultor = new NewRegimeCalculator(anObject); 
OldRegimeCalculator oldRegimeCalculator = new OldRegimeCalculator(anObject);
oldRegimeCalculator.setTauxNr = newRegime.getSalary();
return oldRegimeCalculator
}

@override
public double getSalary()
{
return 0.0d;
}

}

// Child classes : NewRegimeCalculator / OldRegimeCalculator

    public class NewRegimeCalculator extends SalaryCalculator {

       // Special fileds...

       // Procted constructor 
       proctected NewRegimeCalculator(Object anObject) {
       super(anObject);
    }

    @override 
    public double getSalary()
    {
    double salary = 0.0d;
      //Traitements....
     return salary;
    }
}



public class OldRegimeCalculator extends SalaryCalculator {

       // Field holding the newRegime salary
       double tauxNr = 0.0d;
       // Special fileds...

       // Procted constructor 
       proctected OldRegimeCalculator(Object anObject) {
       super(anObject);
    }

    @override 
    public double getSalary()
    {
    double salary = 0.0d;
      //Traitements....
     if (tauxNr>salary)
     {
return tauxNr;
}
else {
return salary;
}
    }

// The Client using the design

public classWantToGetTheSalary {

Object anObject;
double salary;
   SalaryCalculator regimeCalculator = new SalaryCalculator().getRegimeCalculator(anObject);

//Here is our salary 
salary = regimeCalculator.getSalary();


}

I am sorry if this is hard to read, i would so greatful if you can give me some feedback, whats the prons & cons of this implementation ? is it worth to get on production ? is it a just crap code ? does it respect the SOLID Principles ?.... Thank you in advance :)