Search Results

Search found 42264 results on 1691 pages for 'template method pattern'.

Page 11/1691 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Template approach for a PHP application

    - by Industrial
    Hi everyone, We're in the middle of making a new e-commerce related PHP application and we have come to the point where we have started to think about how we should solve templating for our customers needs. What we would like to do is offer our customers the possibility of uploading/modifying templates to suit their company:s profile. The initial thought is that we shall not reinvent the wheel, so instead letting our customers upload their templates with FTP, so there will be basic HTML skills required. For those customers that want to modify/customize template and doesnt have the knowledge, we offer that service as well. I know that there's a number of issues to solve before this could be considered safe, like preventing XSS and writing scripts that check through each uploaded file for potential security threats and so on. Of course, there are some part that probably will be to complex for the customer to modify by themselves, so maybe this approach won't apply to all<< template files in the frontend application. But besides that, what would be a good way to handle this?

    Read the article

  • Undefined template methods trick ?

    - by Matthieu M.
    A colleague of mine told me about a little piece of design he has used with his team that sent my mind boiling. It's a kind of traits class that they can specialize in an extremely decoupled way. I've had a hard time understanding how it could possibly work, and I am still unsure of the idea I have, so I thought I would ask for help here. We are talking g++ here, specifically the versions 3.4.2 and 4.3.2 (it seems to work with both). The idea is quite simple: 1- Define the interface // interface.h template <class T> struct Interface { void foo(); // the method is not implemented, it could not work if it was }; // // I do not think it is necessary // but they prefer free-standing methods with templates // because of the automatic argument deduction // template <class T> void foo(Interface<T>& interface) { interface.foo(); } 2- Define a class, and in the source file specialize the interface for this class (defining its methods) // special.h class Special {}; // special.cpp #include "interface.h" #include "special.h" // // Note that this specialization is not visible outside of this translation unit // template <> struct Interface<Special> { void foo() { std::cout << "Special" << std::endl; } }; 3- To use, it's simple too: // main.cpp #include "interface.h" class Special; // yes, it only costs a forward declaration // which helps much in term of dependencies int main(int argc, char* argv[]) { Interface<Special> special; foo(special); return 0; }; It's an undefined symbol if no translation unit defined a specialization of Interface for Special. Now, I would have thought this would require the export keyword, which to my knowledge has never been implemented in g++ (and only implemented once in a C++ compiler, with its authors advising anyone not to, given the time and effort it took them). I suspect it's got something to do with the linker resolving the templates methods... Do you have ever met anything like this before ? Does it conform to the standard or do you think it's a fortunate coincidence it works ? I must admit I am quite puzzled by the construct...

    Read the article

  • struct with template variables in c++

    - by monkeyking
    I'm playing around with template, so I'm not trying to reinvent the std::vector, I'm trying to get a grasp of templateting in c++. Can I do the following template <typename T> typedef struct{ size_t x; T *ary; }array; What I'm trying to do is a basic templated version of typedef struct{ size_t x; int *ary; }iArray; It looks like its working if I use a class instead of struct, so is it not possible with typedef structs? thanks

    Read the article

  • C++ abstract class template + type-specific subclass = trouble with linker

    - by user333279
    Hi there, The project in question is about different endpoints communicating with each other. An endpoint sends events (beyond the scope of the current problem) and can process incoming events. Each event is represented in a generic object as follows: #pragma interface ... // some includes template<typename T> class Event { public: Event(int senderId, Type type, T payload); // Type is an enum Event(int senderId, Type type, int priority, T payload); virtual ~Event(); virtual int getSenderId(); virtual int getPriority(); virtual T getPayload(); void setPriority(const int priority); protected: const int senderId; const Type type; const T payload; int priority; }; It has its implementing class with #pragma implementation tag. An endpoint is defined as follows: #pragma interface #include "Event.h" template<typename T> class AbstractEndPoint { public: AbstractEndPoint(int id); virtual ~AbstractEndPoint(); virtual int getId(); virtual void processEvent(Event<T> event) = 0; protected: const int id; }; It has its implementing class too, but only the constructor, destructor and getId() are defined. The idea is to create concrete endpoints for each different payload type. Therefore I have different payload objects and specific event classes for each type, e.g. Event<TelegramFormatA>, Event<TelegramFormatB> and ConcreteEndPoint for TelegramFormatA, ConcreteEndPoint for TelegramFormatB respectively. The latter classes are defined as class ConcreteEndPoint : AbstractEndPoint<TelegramFormatA> { ... } I'm using g++ 4.4.3 and ld 2.19. Everything compiles nicely, but the linker complaints about undefined references to type-specific event classes, like Event<TelegramFormatA>::Event(....) . I tried explicit instantiation using template class AbstractEndPoint<TelegramFormatA>; but couldn't get past the aforementioned linker errors. Any ideas would be appreciated.

    Read the article

  • Re-ordering C++ template functions

    - by DeadMG
    In C++, I have a certain template function that, on a given condition, calls a template function in another class. The trouble is that the other class requires the full definition of the first class to be implemented, as it creates the second class and stores them and manages them in similar fashions. The trouble is that naturally, they fall as one class, and thus have some tight interop, except that I need them to be two classes for threading reasons. A sort of, master for all threads, one child per thread, system. Any advice on how this can be implemented?

    Read the article

  • C++ template specialization

    - by user231536
    I have a class template <typename T> class C { static const int K=1; static ostream& print(ostream& os, const T& t) { return os << t;} }; I would like to specialize C for int. //specialization for int template <> C<int>{ static const int K=2; } I want the default print method that works for int to remain and just change the constant. For some specializations, I want to keep K=1 and change the print method because there is no << operator. How do I do this?

    Read the article

  • Linq to SQL and concurrency with Rob Conery repository pattern

    - by David Hall
    I have implemented a DAL using Rob Conery's spin on the repository pattern (from the MVC Storefront project) where I map database objects to domain objects using Linq and use Linq to SQL to actually get the data. This is all working wonderfully giving me the full control over the shape of my domain objects that I want, but I have hit a problem with concurrency that I thought I'd ask about here. I have concurrency working but the solution feels like it might be wrong (just one of those gitchy feelings). The basic pattern is: private MyDataContext _datacontext private Table _tasks; public Repository(MyDataContext datacontext) { _dataContext = datacontext; } public void GetTasks() { _tasks = from t in _dataContext.Tasks; return from t in _tasks select new Domain.Task { Name = t.Name, Id = t.TaskId, Description = t.Description }; } public void SaveTask(Domain.Task task) { Task dbTask = null; // Logic for new tasks omitted... dbTask = (from t in _tasks where t.TaskId == task.Id select t).SingleOrDefault(); dbTask.Description = task.Description, dbTask.Name = task.Name, _dataContext.SubmitChanges(); } So with that implementation I've lost concurrency tracking because of the mapping to the domain task. I get it back by storing the private Table which is my datacontext list of tasks at the time of getting the original task. I then update the tasks from this stored Table and save what I've updated This is working - I get change conflict exceptions raised when there are concurrency violations, just as I want. However, it just screams to me that I've missed a trick. Is there a better way of doing this? I've looked at the .Attach method on the datacontext but that appears to require storing the original version in a similar way to what I'm already doing. I also know that I could avoid all this by doing away with the domain objects and letting the Linq to SQL generated objects all the way up my stack - but I dislike that just as much as I dislike the way I'm handling concurrency.

    Read the article

  • preg_match , pattern, php

    - by Michael
    I'm trying to extract some specific pictures from html content . Currently I have the following array [1] = Array ( [0] = BuEZm5g!Wk~$(KGrHqQH-DgEvrb2CLuOBL-vbkHlKw~~_14.JPG#!BuEZm5g!Wk~$(KGrHqQH-DgEvrb2CLuOBL-vbkHlKw~~_12.JPG|1#http://i.ebayimg.com/08#!BuEZqMQBGk~$(KGrHqQH-DoEvrKYSoPiBL-vb)WgLw~~_14.JPG#!BuEZqMQBGk~$(KGrHqQH-DoEvrKYSoPiBL-vb)WgLw~~_12.JPG|2#http://i.ebayimg.com/13#!BuEZtkw!2k~$(KGrHqYH-EYEvsh4EjJSBL-vb-bLow~~_14.JPG#!BuEZtkw!2k~$(KGrHqYH-EYEvsh4EjJSBL-vb-bLow~~_12.JPG|3#http://i.ebayimg.com/03#!BuEZ)!wEGk~$(KGrHqYH-DwEvq8Z1JuQBL-vcMOoFQ~~_14.JPG#!BuEZ)!wEGk~$(KGrHqYH-DwEvq8Z1JuQBL-vcMOoFQ~~_12.JPG|4#http://i.ebayimg.com/09#!BuEZ1IQEGk~$(KGrHqEH-D0EvqwClvviBL-vcclJwg~~_14.JPG#!BuEZ1IQEGk~$(KGrHqEH-D0EvqwClvviBL-vcclJwg~~_12.JPG|5#http://i.ebayimg.com/17#!BuEZ4FQCWk~$(KGrHqUH-DMEvS+,FRj5BL-vco)Qgg~~_14.JPG#!BuEZ4FQCWk~$(KGrHqUH-DMEvS+,FRj5BL-vco)Qgg~~_12.JPG|6#http://i.ebayimg.com/17#!BuEZ7FQEWk~$(KGrHqYH-EYEvsh4EjJSBL-vc1v2Hg~~_14.JPG#!BuEZ7FQEWk~$(KGrHqYH-EYEvsh4EjJSBL-vc1v2Hg~~_12.JPG|7#http://i.ebayimg.com/12#!BuEZ-c!Bmk~$(KGrHqQH-CYEvr5z9)NVBL-vdC,)Mg~~_14.JPG#!BuEZ-c!Bmk~$(KGrHqQH-CYEvr5z9)NVBL-vdC,)Mg~~_12.JPG|8#http://i.ebayimg.com/20#!BuE,CNgCWk~$(KGrHqIH-CIEvqKBurmhBL-vdRBe3!~~_14.JPG#!BuE,CNgCWk~$(KGrHqIH-CIEvqKBurmhBL-vdRBe3!~~_12.JPG|9#http://i.ebayimg.com/24#!BuE,FN!EWk~$(KGrHqUH-C0EvsBdjbv0BL-vdeFkD!~~_14.JPG#!BuE,FN!EWk~$(KGrHqUH-C0EvsBdjbv0BL-vdeFkD!~~_12.JPG|10#http://i.ebayimg.com/16#!BuE,IOgBmk~$(KGrHqEH-EMEvpym7mSLBL-vdqI6nw~~_14.JPG#!BuE,IOgBmk~$(KGrHqEH-EMEvpym7mSLBL-vdqI6nw~~ ) I need to extract only the pictures that start with ! and ends in 12.JPG . An example of expected result is !BuEZm5g!Wk~$(KGrHqQH-DgEvrb2CLuOBL-vbkHlKw~~_12.JPG . I have a pattern but it doesn't work for some reasons that I don't know . It is $pattern = "/#\!(.*)_12.JPG/"; Thank you in advance for any help

    Read the article

  • Database migration pattern for Java?

    - by Eno
    Im working on some database migration code in Java. Im also using a factory pattern so I can use different kinds of databases. And each kind of database im using implements a common interface. What I would like to do is have a migration check that is internal to the class and runs some database schema update code automatically. The actual update is pretty straight forward (I check schema version in a table and compare against a constant in my app to decide whether to migrate or not and between which versions of schema). To make this automatic I was thinking the test should live inside (or be called from) the constructor. OK, fair enough, that's simple enough. My problem is that I dont want the test to run every single time I instantiate a database object (it runs a query so having it run on every construction is not efficient). So maybe this should be a class static method? I guess my question is, what is a good design pattern for this type of problem? There ought to be a clean way to ensure the migration test runs only once OR is super-efficient.

    Read the article

  • Need help make these classes use Visitor Pattern and generics

    - by Shervin
    Hi. I need help to generify and implement the visitor pattern. We are using tons of instanceof and it is a pain. I am sure it can be modified, but I am not sure how to do it. Basically we have an interface ProcessData public interface ProcessData { public setDelegate(Object delegate); public Object getDelegate(); //I am sure these delegate methods can use generics somehow } Now we have a class ProcessDataGeneric that implements ProcessData public class ProcessDataGeneric implements ProcessData { private Object delegate; public ProcessDataGeneric(Object delegate) { this.delegate = delegate; } } Now a new interface that retrieves the ProcessData interface ProcessDataWrapper { public ProcessData unwrap(); } Now a common abstract class that implements the wrapper so ProcessData can be retrieved @XmlSeeAlso( { ProcessDataMotorferdsel.class,ProcessDataTilskudd.class }) public abstract class ProcessDataCommon implements ProcessDataWrapper { protected ProcessData unwrapped; public ProcessData unwrap() { return unwrapped; } } Now the implementation public class ProcessDataMotorferdsel extends ProcessDataCommon { public ProcessDataMotorferdsel() { unwrapped = new ProcessDataGeneric(this); } } similarly public class ProcessDataTilskudd extends ProcessDataCommon { public ProcessDataTilskudd() { unwrapped = new ProcessDataGeneric(this); } } Now when I use these classes, I always need to do instanceof ProcessDataCommon pdc = null; if(processData.getDelegate() instanceof ProcessDataMotorferdsel) { pdc = (ProcessDataMotorferdsel) processData.getDelegate(); } else if(processData.getDelegate() instanceof ProcessDataTilskudd) { pdc = (ProcessDataTilskudd) processData.getDelegate(); } I know there is a better way to do this, but I have no idea how I can utilize Generics and the Visitor Pattern. Any help is GREATLY appreciated.

    Read the article

  • Scheme: Mysterious void in pattern match.

    - by Schemer
    Hi. I am writing a function called annotate that uses match-lambda -- often with recursive calls to annotate. Here is one of the pattern matches: (`(lambda (,<param1> . ,<params>) ,<stmts>) `(CLOSURE ENV (,<param1> . ,<params>) (lambda (ENV) ,(map annotate (map (lambda (x) (append `(,<param1> . ,<params>) (list x))) `(,<stmts>)))))) However, when this pattern is matched this is what returns: '(CLOSURE ENV (x) (lambda (ENV) ((CLOSURE ENV (x y) (lambda (ENV) ((+ x y)))))) #<void>) Specifically I can't figure out where "void" is coming from. In fact, if I include the line: ,(displayln (map annotate (map (lambda (x) (append `(,<param1> . ,<params>) (list x))) `(,<stmts>)))) it prints: ((CLOSURE ENV (x y) (lambda (ENV) ((+ x y))))) notably without "void". If someone could tell me what the problem is it would be greatly appreciated. Thanks.

    Read the article

  • Repository Pattern Standardization of methods

    - by Nix
    All I am trying to find out the correct definition of the repository pattern. My original understanding was this (extremely dubmed down) Separate your Business Objects from your Data Objects Standardize access methods in data access layer. I have really seen 2 different implementations. Implementation 1 : public Interface IRepository<T>{ List<T> GetAll(); void Create(T p); void Update(T p); } public interface IProductRepository: IRepository<Product> { //Extension methods if needed List<Product> GetProductsByCustomerID(); } Implementation 2 : public interface IProductRepository { List<Product> GetAllProducts(); void CreateProduct(Product p); void UpdateProduct(Product p); List<Product> GetProductsByCustomerID(); } Notice the first is generic Get/Update/GetAll, etc, the second is more of what I would define "DAO" like. Both share an extraction from your data entities. Which I like, but i can do the same with a simple DAO. However the second piece standardize access operations I see value in, if you implement this enterprise wide people would easily know the set of access methods for your repository. Am I wrong to assume that the standardization of access to data is an integral piece of this pattern ? Rhino has a good article on implementation 1, and of course MS has a vague definition and an example of implementation 2 is here.

    Read the article

  • Understanding C# async / await (2) Awaitable / Awaiter Pattern

    - by Dixin
    What is awaitable Part 1 shows that any Task is awaitable. Actually there are other awaitable types. Here is an example: Task<int> task = new Task<int>(() => 0); int result = await task.ConfigureAwait(false); // Returns a ConfiguredTaskAwaitable<TResult>. The returned ConfiguredTaskAwaitable<TResult> struct is awaitable. And it is not Task at all: public struct ConfiguredTaskAwaitable<TResult> { private readonly ConfiguredTaskAwaiter m_configuredTaskAwaiter; internal ConfiguredTaskAwaitable(Task<TResult> task, bool continueOnCapturedContext) { this.m_configuredTaskAwaiter = new ConfiguredTaskAwaiter(task, continueOnCapturedContext); } public ConfiguredTaskAwaiter GetAwaiter() { return this.m_configuredTaskAwaiter; } } It has one GetAwaiter() method. Actually in part 1 we have seen that Task has GetAwaiter() method too: public class Task { public TaskAwaiter GetAwaiter() { return new TaskAwaiter(this); } } public class Task<TResult> : Task { public new TaskAwaiter<TResult> GetAwaiter() { return new TaskAwaiter<TResult>(this); } } Task.Yield() is a another example: await Task.Yield(); // Returns a YieldAwaitable. The returned YieldAwaitable is not Task either: public struct YieldAwaitable { public YieldAwaiter GetAwaiter() { return default(YieldAwaiter); } } Again, it just has one GetAwaiter() method. In this article, we will look at what is awaitable. The awaitable / awaiter pattern By observing different awaitable / awaiter types, we can tell that an object is awaitable if It has a GetAwaiter() method (instance method or extension method); Its GetAwaiter() method returns an awaiter. An object is an awaiter if: It implements INotifyCompletion or ICriticalNotifyCompletion interface; It has an IsCompleted, which has a getter and returns a Boolean; it has a GetResult() method, which returns void, or a result. This awaitable / awaiter pattern is very similar to the iteratable / iterator pattern. Here is the interface definitions of iteratable / iterator: public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { object Current { get; } bool MoveNext(); void Reset(); } public interface IEnumerable<out T> : IEnumerable { IEnumerator<T> GetEnumerator(); } public interface IEnumerator<out T> : IDisposable, IEnumerator { T Current { get; } } In case you are not familiar with the out keyword, please find out the explanation in Understanding C# Covariance And Contravariance (2) Interfaces. The “missing” IAwaitable / IAwaiter interfaces Similar to IEnumerable and IEnumerator interfaces, awaitable / awaiter can be visualized by IAwaitable / IAwaiter interfaces too. This is the non-generic version: public interface IAwaitable { IAwaiter GetAwaiter(); } public interface IAwaiter : INotifyCompletion // or ICriticalNotifyCompletion { // INotifyCompletion has one method: void OnCompleted(Action continuation); // ICriticalNotifyCompletion implements INotifyCompletion, // also has this method: void UnsafeOnCompleted(Action continuation); bool IsCompleted { get; } void GetResult(); } Please notice GetResult() returns void here. Task.GetAwaiter() / TaskAwaiter.GetResult() is of such case. And this is the generic version: public interface IAwaitable<out TResult> { IAwaiter<TResult> GetAwaiter(); } public interface IAwaiter<out TResult> : INotifyCompletion // or ICriticalNotifyCompletion { bool IsCompleted { get; } TResult GetResult(); } Here the only difference is, GetResult() return a result. Task<TResult>.GetAwaiter() / TaskAwaiter<TResult>.GetResult() is of this case. Please notice .NET does not define these IAwaitable / IAwaiter interfaces at all. As an UI designer, I guess the reason is, IAwaitable interface will constraint GetAwaiter() to be instance method. Actually C# supports both GetAwaiter() instance method and GetAwaiter() extension method. Here I use these interfaces only for better visualizing what is awaitable / awaiter. Now, if looking at above ConfiguredTaskAwaitable / ConfiguredTaskAwaiter, YieldAwaitable / YieldAwaiter, Task / TaskAwaiter pairs again, they all “implicitly” implement these “missing” IAwaitable / IAwaiter interfaces. In the next part, we will see how to implement awaitable / awaiter. Await any function / action In C# await cannot be used with lambda. This code: int result = await (() => 0); will cause a compiler error: Cannot await 'lambda expression' This is easy to understand because this lambda expression (() => 0) may be a function or a expression tree. Obviously we mean function here, and we can tell compiler in this way: int result = await new Func<int>(() => 0); It causes an different error: Cannot await 'System.Func<int>' OK, now the compiler is complaining the type instead of syntax. With the understanding of the awaitable / awaiter pattern, Func<TResult> type can be easily made into awaitable. GetAwaiter() instance method, using IAwaitable / IAwaiter interfaces First, similar to above ConfiguredTaskAwaitable<TResult>, a FuncAwaitable<TResult> can be implemented to wrap Func<TResult>: internal struct FuncAwaitable<TResult> : IAwaitable<TResult> { private readonly Func<TResult> function; public FuncAwaitable(Func<TResult> function) { this.function = function; } public IAwaiter<TResult> GetAwaiter() { return new FuncAwaiter<TResult>(this.function); } } FuncAwaitable<TResult> wrapper is used to implement IAwaitable<TResult>, so it has one instance method, GetAwaiter(), which returns a IAwaiter<TResult>, which wraps that Func<TResult> too. FuncAwaiter<TResult> is used to implement IAwaiter<TResult>: public struct FuncAwaiter<TResult> : IAwaiter<TResult> { private readonly Task<TResult> task; public FuncAwaiter(Func<TResult> function) { this.task = new Task<TResult>(function); this.task.Start(); } bool IAwaiter<TResult>.IsCompleted { get { return this.task.IsCompleted; } } TResult IAwaiter<TResult>.GetResult() { return this.task.Result; } void INotifyCompletion.OnCompleted(Action continuation) { new Task(continuation).Start(); } } Now a function can be awaited in this way: int result = await new FuncAwaitable<int>(() => 0); GetAwaiter() extension method As IAwaitable shows, all that an awaitable needs is just a GetAwaiter() method. In above code, FuncAwaitable<TResult> is created as a wrapper of Func<TResult> and implements IAwaitable<TResult>, so that there is a  GetAwaiter() instance method. If a GetAwaiter() extension method  can be defined for Func<TResult>, then FuncAwaitable<TResult> is no longer needed: public static class FuncExtensions { public static IAwaiter<TResult> GetAwaiter<TResult>(this Func<TResult> function) { return new FuncAwaiter<TResult>(function); } } So a Func<TResult> function can be directly awaited: int result = await new Func<int>(() => 0); Using the existing awaitable / awaiter - Task / TaskAwaiter Remember the most frequently used awaitable / awaiter - Task / TaskAwaiter. With Task / TaskAwaiter, FuncAwaitable / FuncAwaiter are no longer needed: public static class FuncExtensions { public static TaskAwaiter<TResult> GetAwaiter<TResult>(this Func<TResult> function) { Task<TResult> task = new Task<TResult>(function); task.Start(); return task.GetAwaiter(); // Returns a TaskAwaiter<TResult>. } } Similarly, with this extension method: public static class ActionExtensions { public static TaskAwaiter GetAwaiter(this Action action) { Task task = new Task(action); task.Start(); return task.GetAwaiter(); // Returns a TaskAwaiter. } } an action can be awaited as well: await new Action(() => { }); Now any function / action can be awaited: await new Action(() => HelperMethods.IO()); // or: await new Action(HelperMethods.IO); If function / action has parameter(s), closure can be used: int arg0 = 0; int arg1 = 1; int result = await new Action(() => HelperMethods.IO(arg0, arg1)); Using Task.Run() The above code is used to demonstrate how awaitable / awaiter can be implemented. Because it is a common scenario to await a function / action, so .NET provides a built-in API: Task.Run(): public class Task2 { public static Task Run(Action action) { // The implementation is similar to: Task task = new Task(action); task.Start(); return task; } public static Task<TResult> Run<TResult>(Func<TResult> function) { // The implementation is similar to: Task<TResult> task = new Task<TResult>(function); task.Start(); return task; } } In reality, this is how we await a function: int result = await Task.Run(() => HelperMethods.IO(arg0, arg1)); and await a action: await Task.Run(() => HelperMethods.IO());

    Read the article

  • Refactoring an ERB Template to Haml

    - by Liam McLennan
    ERB is the default view templating system used by Ruby on Rails. Haml is an alternative templating system that uses whitespace to represent document structure. The example from the haml website shows the following equivalent markup: Haml ERB #profile .left.column #date= print_date #address= current_user.address .right.column #email= current_user.email #bio= current_user.bio <div id="profile"> <div class="left column"> <div id="date"><%= print_date %></div> <div id="address"><%= current_user.address %></div> </div> <div class="right column"> <div id="email"><%= current_user.email %></div> <div id="bio"><%= current_user.bio %></div> </div> </div> I like haml because it is concise and the significant whitespace makes it easy to see the structure at a glance. This post is about a ruby project but nhaml makes haml available for asp.net MVC also. The ERB Template Today I spent some time refactoring an ERB template to Haml. The template is called list.html.erb and its purpose is to render a list of tweets (twitter messages). <style> form { float: left; } </style> <h1>Tweets</h1> <table> <thead><tr><th></th><th>System</th><th>Human</th><th></th></tr></thead> <% @tweets.each do |tweet| %> <tr> <td><%= h(tweet['text']) %></td> <td><%= h(tweet['system_classification']) %></td> <td><%= h(tweet['human_classification']) %></td> <td><form action="/tweet/rate" method="post"> <%= token_tag %> <input type="submit" value="Positive"/> <input type="hidden" value="<%= tweet['id']%>" name="id" /> <input type="hidden" value="positive" name="rating" /> </form> <form action="/tweet/rate" method="post"> <%= token_tag %> <input type="submit" value="Neutral"/> <input type="hidden" value="<%= tweet['id']%>" name="id" /> <input type="hidden" value="neutral" name="rating" /> </form> <form action="/tweet/rate" method="post"> <%= token_tag %> <input type="submit" value="Negative"/> <input type="hidden" value="<%= tweet['id']%>" name="id" /> <input type="hidden" value="negative" name="rating" /> </form> </td> </tr> <% end %> </table> Haml Template: Take 1 My first step was to convert this page to a Haml template in place. Directly translating the ERB template to Haml resulted in: list.haml %style form {float: left;} %h1 Tweets %table %thead %tr %th %th System %th Human %th %tbody - @tweets.each do |tweet| %tr %td= tweet['text'] %td= tweet['system_classification'] %td= tweet['human_classification'] %td %form{ :action=>"/tweet/rate", :method=>"post"} = token_tag <input type="submit" value="Positive"/> <input type="hidden" value="positive" name="rating" /> %input{ :type=>"hidden", :value => tweet['id']} %form{ :action=>"/tweet/rate", :method=>"post"} = token_tag <input type="submit" value="Neutral"/> <input type="hidden" value="neutral" name="rating" /> %input{ :type=>"hidden", :value => tweet['id']} %form{ :action=>"/tweet/rate", :method=>"post"} = token_tag <input type="submit" value="Negative"/> <input type="hidden" value="negative" name="rating" /> %input{ :type=>"hidden", :value => tweet['id']} end I like this better already but I can go further. Haml Template: Take 2 The haml documentation says to avoid using iterators so I introduced a partial template (_tweet.haml) as the template to render a single tweet. _tweet.haml %tr %td= tweet['text'] %td= tweet['system_classification'] %td= tweet['human_classification'] %td %form{ :action=>"/tweet/rate", :method=>"post"} = token_tag <input type="submit" value="Positive"/> <input type="hidden" value="positive" name="rating" /> %input{ :type=>"hidden", :value => tweet['id']} %form{ :action=>"/tweet/rate", :method=>"post"} = token_tag <input type="submit" value="Neutral"/> <input type="hidden" value="neutral" name="rating" /> %input{ :type=>"hidden", :value => tweet['id']} %form{ :action=>"/tweet/rate", :method=>"post"} = token_tag <input type="submit" value="Negative"/> <input type="hidden" value="negative" name="rating" /> %input{ :type=>"hidden", :value => tweet['id']} and the list template is simplified to: list.haml %style form {float: left;} %h1 Tweets %table     %thead         %tr             %th             %th System             %th Human             %th     %tbody         = render(:partial => "tweet", :collection => @tweets) That is definitely an improvement, but then I noticed that _tweet.haml contains three form tags that are nearly identical.   Haml Template: Take 3 My first attempt, later aborted, was to use a helper to remove the duplication. A much better solution is to use another partial.  _rate_button.haml %form{ :action=>"/tweet/rate", :method=>"post"} = token_tag %input{ :type => "submit", :value => rate_button[:rating].capitalize } %input{ :type => "hidden", :value => rate_button[:rating], :name => 'rating' } %input{ :type => "hidden", :value => rate_button[:id], :name => 'id' } and the tweet template is now simpler: _tweet.haml %tr %td= tweet['text'] %td= tweet['system_classification'] %td= tweet['human_classification'] %td = render( :partial => 'rate_button', :object => {:rating=>'positive', :id=> tweet['id']}) = render( :partial => 'rate_button', :object => {:rating=>'neutral', :id=> tweet['id']}) = render( :partial => 'rate_button', :object => {:rating=>'negative', :id=> tweet['id']}) list.haml remains unchanged. Summary I am extremely happy with the switch. No doubt there are further improvements that I can make, but I feel like what I have now is clean and well factored.

    Read the article

  • How to specialize a c++ variadic template?

    - by Serge
    I'm trying to understand c++ variadic templates. I'm not much aware of the correct language to use to explain what I'd like to achieve, so it might be simpler if I provide a bit of code which illustrate what I'd like to achieve. #include <iostream> #include <string> using namespace std; template<int ...A> class TestTemplate1 { public: string getString() { return "Normal"; } }; template<int T, int ...A> string TestTemplate1<2, A...>::getString() { return "Specialized"; } template<typename ...A> class TestTemplate2 { }; int main() { TestTemplate1<1, 2, 3, 4> t1_1; TestTemplate1<1, 2> t1_2; TestTemplate1<> t1_3; TestTemplate1<2> t1_4; TestTemplate2<> t2_1; TestTemplate2<int, double> t2_2; cout << t1_1.getString() << endl; cout << t1_2.getString() << endl; cout << t1_3.getString() << endl; cout << t1_4.getString() << endl; } This throws several errors. error C2333: 'TestTemplate1<::getString' : error in function declaration; skipping function body error C2333: 'TestTemplate1<1,2,3,4::getString' : error in function declaration; skipping function body error C2333: 'TestTemplate1<1,2::getString' : error in function declaration; skipping function body error C2333: 'TestTemplate1<2::getString' : error in function declaration; skipping function body error C2977: 'TestTemplate1' : too many template arguments error C2995: 'std::string TestTemplate1::getString(void)' : function template has already been defined error C3860: template argument list following class template name must list parameters in the order used in template parameter list How can I have a specialized behavior for every TestTemplate1<2, ...> instances like t1_4?

    Read the article

  • What design pattern will you choose ?

    - by MemoryLeak
    I want to design a class, which contains a procedure to achieve a goal. And it must follow some order to make sure the last method, let's say "ExecuteIt", to behave correctly. in such a case, what design patter will you use ? which can make sure that the user must call the public method according some ordering. If you really don't know what I am saying, then can you share me some concept of choosing a design patter, or what will you consider while design a class?

    Read the article

  • How to change the border on a listboxitem while using a predefined template

    - by djerry
    Hey, I'm using one of the defined wpf themes for my application, so all my controls automatically are pimped according to that theme. Now i am filling a listbox with items (usercontrols), but not all of them should be visible at all time. But when i'm setting height to 0 (of usercontrol) or setting to invisible, i get a thick grey border of the listboxitems. Can someone help me override the border of the listboxitem or show me where in the template i need to change the border, cause i just can't find it. This is the part of the template for the listboxitem: <Style d:IsControlPart="True" TargetType="{x:Type ListBoxItem}"> <Setter Property="SnapsToDevicePixels" Value="true"/> <Setter Property="OverridesDefaultStyle" Value="false"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBoxItem}"> <ControlTemplate.Resources> <Storyboard x:Key="HoverOn"> <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="HoverRectangle" Storyboard.TargetProperty="(UIElement.Opacity)"> <SplineDoubleKeyFrame KeyTime="00:00:00.2000000" Value="1"/> </DoubleAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="HoverOff"> <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="HoverRectangle" Storyboard.TargetProperty="(UIElement.Opacity)"> <SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="0" /> </DoubleAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="SelectedOn"> <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="SelectedRectangle" Storyboard.TargetProperty="(UIElement.Opacity)"> <SplineDoubleKeyFrame KeyTime="00:00:00.2000000" Value="1"/> </DoubleAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="SelectedOff"> <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="SelectedRectangle" Storyboard.TargetProperty="(UIElement.Opacity)"> <SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="0" /> </DoubleAnimationUsingKeyFrames> </Storyboard> </ControlTemplate.Resources> <Grid Background="{TemplateBinding Background}" Margin="1,1,1,1" SnapsToDevicePixels="true" x:Name="grid"> <Rectangle x:Name="Background" IsHitTestVisible="False" Fill="{StaticResource SelectedBackgroundBrush}" RadiusX="0"/> <Rectangle x:Name="SelectedRectangle" IsHitTestVisible="False" Opacity="0" Fill="{StaticResource NormalBrush}" RadiusX="0"/> <Rectangle x:Name="HoverRectangle" IsHitTestVisible="False" Fill="{StaticResource HoverBrush}" RadiusX="0" Opacity="0"/> <ContentPresenter Margin="5,3,3,3" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" x:Name="contentPresenter"/> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Trigger.EnterActions> <BeginStoryboard Storyboard="{StaticResource HoverOn}"/> </Trigger.EnterActions> <Trigger.ExitActions> <BeginStoryboard Storyboard="{StaticResource HoverOff}"/> </Trigger.ExitActions> </Trigger> <Trigger Property="IsSelected" Value="true"> <Trigger.EnterActions> <BeginStoryboard Storyboard="{StaticResource SelectedOn}"/> </Trigger.EnterActions> <Trigger.ExitActions> <BeginStoryboard Storyboard="{StaticResource SelectedOff}"/> </Trigger.ExitActions> </Trigger> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Foreground" Value="{DynamicResource DisabledForegroundBrush}"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Foreground" Value="{DynamicResource TextBrush}"/> </Style>

    Read the article

  • Type for use in template object to compare double values

    - by DaClown
    I got this n-dimensional point object: template <class T, unsigned int dimension> class Obj { protected: T coords[dimension]; static const unsigned int size = dimension; public: Obj() { }; Obj(T def) { for (unsigned int i = 0; i < size; ++i) coords[i]=def; }; Obj(const Obj& o) { for (unsigned int i = 0; i < size; ++i) coords[i] = o.coords[i]; } const Obj& operator= (const Obj& rhs) { if (this != &rhs) for (unsigned int i = 0; i < size; ++i) coords[i] = rhs.coords[i]; return *this; } virtual ~Obj() { }; T get (unsigned int id) { if (id >= size) throw std::out_of_range("out of range"); return coords[id]; } void set (unsigned int id, T t) { if (id >= size) throw std::out_of_range("out of range"); coords[id] = t; } }; and a 3D point class which uses Obj as base class: template <class U> class Point3DBase : public Obj<U,3> { typedef U type; public: U &x, &y, &z; public: Point3DBase() : x(Obj<U,3>::coords[0]), y(Obj<U,3>::coords[1]), z(Obj<U,3>::coords[2]) { }; Point3DBase(U def) : Obj<U,3>(def), x(Obj<U,3>::coords[0]), y(Obj<U,3>::coords[1]), z(Obj<U,3>::coords[2]) { }; Point3DBase(U x_, U y_, U z_) : x(Obj<U,3>::coords[0]), y(Obj<U,3>::coords[1]), z(Obj<U,3>::coords[2]) { x = x_; y = y_; z= z_; }; Point3DBase(const Point3DBase& other) : x(Obj<U,3>::coords[0]), y(Obj<U,3>::coords[1]), z(Obj<U,3>::coords[2]) { x = other.x; y = other.y; z = other.z; } // several operators ... }; The operators, basically the ones for comparison, use the simple compare-the-member-object approach like: virtual friend bool operator== (const Point3DBase<U> &lhs, const Point3DBase<U> rhs) { return (lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z); } Then it occured to me that for the comparion of double values the simply equality approach is not very useful since double values should be compared with an error margin. What would be the best approach to introduce an error margin into the point? I thought about an epsDouble type as template parameter but I can't figure out how to achieve this.

    Read the article

  • How is method group overload resolution different to method call overload resolution?

    - by thecoop
    The following code doesn't compile (error CS0123: No overload for 'System.Convert.ToString(object)' matches delegate 'System.Converter<T,string>'): class A<T> { void Method(T obj) { Converter<T, string> toString = Convert.ToString; } } however, this does: class A<T> { void Method(T obj) { Converter<T, string> toString = o => Convert.ToString(o); } } intellisense gives o as a T, and the Convert.ToString call as using Convert.ToString(object). In c# 3.5, delegates can be created from co/contra-variant methods, so the ToString(object) method can be used as a Converter<T, string>, as T is always guarenteed to be an object. So, the first example (method group overload resolution) should be finding the only applicable method string Convert.ToString(object o), the same as the method call overload resolution. Why is the method group & method call overload resolution producing different results?

    Read the article

  • C++ Using a class template argument as a template argument for another type

    - by toefel
    Hey Everyone, I'm having this problem while writing my own HashTable. It all works, but when I try to templatize the thing, it gave me errors. I recreated the problem as follows: THIS CODE WORKS: typedef double Item; class A { public: A() { v.push_back(pair<string, Item>("hey", 5.0)); } void iterate() { for(Iterator iter = v.begin(); iter != v.end(); ++iter) cout << iter->first << ", " << iter->second << endl; } private: vector<pair<string, double> > v; typedef vector< pair<string, double> >::iterator Iterator; }; THIS CODE DOES NOT: template<typename ValueType> class B { public: B(){} void iterate() { for(Iterator iter = v.begin(); iter != v.end(); ++iter) cout << iter->first << ", " << iter->second << endl; } private: vector<pair<string, ValueType> > v; typedef vector< pair<string, ValueType> >::iterator Iterator; }; the error messages: g++ -O0 -g3 -Wall -c -fmessage-length=0 -omain.o ..\main.cpp ..\main.cpp:50: error: type std::vector<std::pair<std::string, ValueType>, std::allocator<std::pair<std::string, ValueType> > >' is not derived from typeB' ..\main.cpp:50: error: ISO C++ forbids declaration of `iterator' with no type ..\main.cpp:50: error: expected `;' before "Iterator" ..\main.cpp: In member function `void B::iterate()': ..\main.cpp:44: error: `Iterator' was not declared in this scope ..\main.cpp:44: error: expected `;' before "iter" ..\main.cpp:44: error: `iter' was not declared in this scope Does anybody know why this is happening? Thanks!

    Read the article

  • EntityFramework repository template- how to write GetByID lamba within a template class?

    - by FerretallicA
    I am trying to write a generic one-size-fits-most repository pattern template class for an Entity Framework-based project I'm currently working on. The (heavily simplified) interface is: internal interface IRepository<T> where T : class { T GetByID(int id); IEnumerable<T> GetAll(); IEnumerable<T> Query(Func<T, bool> filter); } GetByID is proving to be the killer. In the implementation: public class Repository<T> : IRepository<T>,IUnitOfWork<T> where T : class { // etc... public T GetByID(int id) { return this.ObjectSet.Single<T>(t=>t.ID == id); } t=t.ID == id is the particular bit I'm struggling with. Is it even possible to write lamba functions like that within template classes where no class-specific information is going to be available?

    Read the article

  • Checked status not updated in CheckBox template

    - by Simon
    Hey there. I'm trying to create an hyperlink that changes its text depending on a boolean value. I thought I could leverage the IsChecked method of a CheckBox. So I wrote this ControlTemplate for a CheckBox: <CheckBox Checked="CheckBox_Checked" IsChecked="{Binding Path=SomeBool, Mode=TwoWay}"> <CheckBox.Template> <ControlTemplate TargetType="{x:Type CheckBox}"> <BulletDecorator> <BulletDecorator.Bullet> <TextBlock> <Hyperlink> <TextBlock x:Name="TextBoxHyperlink">Unchecked</TextBlock> </Hyperlink> </TextBlock> </BulletDecorator.Bullet> <ContentPresenter /> </BulletDecorator> <ControlTemplate.Triggers> <Trigger Property="IsChecked" Value="True"> <Setter TargetName="TextBoxHyperlink" Property="Text" Value="Checked" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </CheckBox.Template> </CheckBox> But when I click on the hyperlink, nothing happens. The checked status is not changed and the Text property of the TextBlock is not updated. Any ideas?

    Read the article

  • Template Sort In C++

    - by wdow88
    Hey all, I'm trying to write a sort function but am having trouble figuring out how to initialize a value, and making this function work as a generic template. The sort works by: Find a pair =(ii,jj)= with a minimum value = ii+jj = such at A[ii]A[jj] If such a pair exists, then swap A[ii] and A[jj] else break; The function I have written is as follows: template <typename T> void sort(T *A, int size) { T min =453; T temp=0; bool swapper = true; while(swapper) { swapper = false; int index1 = 0, index2 = 0; for (int ii = 0; ii < size-1; ii++){ for (int jj = ii + 1; jj < size; jj++){ if((min >= (A[ii]+A[jj])) && (A[ii] > A[jj])){ min = (A[ii]+A[jj]); index1 = ii; index2 = jj; swapper = true; } } } if (!swapper) return; else { temp = A[index1]; A[index1] = A[index2]; A[index2] = temp; sort(A,size); } } } This function will successfully sort an array of integers, but not an array of chars. I do not know how to properly initialize the min value for the start of the comparison. I tried initializing the value by simply adding the first two elements of the array together (min = A[0] + A[1]), but it looks to me like for this algorithm it will fail. I know this is sort of a strange type of sort, but it is practice for a test, so thanks for any input.

    Read the article

  • Link error for user defined class type template parameter

    - by isurulucky
    Hi, I implemented a Simple STL map in C++. Factored out the comparison as a type as I was instructed to, then implemented the comparison as shown below: template <typename T> int KeyCompare<T>::operator () (T tKey1, T tKey2) { if(tKey1 < tKey2) return -1; else if(tKey1 > tKey2) return 1; else return 0; } here, tKey1 and tKet2 are the two keys I'm comparing. This worked well for all the basic data types and string. I added a template specialization to compare keys of a user defined type named Test and added a specialization as follows: int KeyCompare<Test>::operator () (Test tKey1, Test tKey2) { if(tKey1.a < tKey2.a) return -1; else if(tKey1.a > tKey2.a) return 1; else return 0; } when I run this, I get a linking error saying SimpleMap.obj : error LNK2005: "public: int __thiscall KeyCompare::operator()(class Test,class Test)" (??R?$KeyCompare@VTest@@@@QAEHVTest@@0@Z) already defined in MapTest.obj SimpleMap.obj : error LNK2005: "public: __thiscall KeyCompare::~KeyCompare(void)" (??1?$KeyCompare@VTest@@@@QAE@XZ) already defined in MapTest.obj SimpleMap.obj : error LNK2005: "public: __thiscall KeyCompare::KeyCompare(void)" (??0?$KeyCompare@VTester@@@@QAE@XZ) already defined in MapTest.obj MapTest.cpp is the test harness class in which I wrote the test case. I have used include guards as well, to stop multiple inclusions. Any idea what the matter is?? Thank you very much!!

    Read the article

  • C++. How to define template parameter of type T for class A when class T needs a type A template parameter?

    - by jaybny
    Executor class has template of type P and it takes a P object in constructor. Algo class has a template E and also has a static variable of type E. Processor class has template T and a collection of Ts. Question how can I define Executor< Processor<Algo> > and Algo<Executor> ? Is this possible? I see no way to defining this, its kind of an "infinite recursive template argument" See code. template <class T> class Processor { map<string,T> ts; void Process(string str, int i) { ts[str].Do(i); } } template <class P> class Executor { Proc &p; Executor(P &p) : Proc(p) {} void Foo(string str, int i) { p.Process(str,i); } Execute(string str) { } } template <class E> class Algo { static E e; void Do(int i) {} void Foo() { e.Execute("xxx"); } } main () { typedef Processor<Algo> PALGO; // invalid typedef Executor<PALGO> EPALGO; typedef Algo<EPALGO> AEPALGO; Executor<PALGO> executor(PALGO()); AEPALGO::E = executor; }

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >