Search Results

Search found 8397 results on 336 pages for 'implementation'.

Page 92/336 | < Previous Page | 88 89 90 91 92 93 94 95 96 97 98 99  | Next Page >

  • Method in RootViewController not Storing Array

    - by Antonio
    I have an array initialized in my RootViewController and a method that addsObjects to an array. I created a RootViewController object in my SecondViewController. The method runs (outputs a message) but it doesn't add anything to the array, and the array seems empty. Code is below, any suggestions? RootViewController.h #import "RootViewController.h" #import "SecondViewController.h" @implementation RootViewController - (void)viewDidLoad { [super viewDidLoad]; myArray2 = [[NSMutableArray alloc] init]; NSLog(@"View was loaded"); } -(void)addToArray2{ NSLog(@"Array triggered from SecondViewController"); [myArray2 addObject:@"Test"]; [self showArray2]; } -(void)showArray2{ NSLog(@"Array Count: %d", [myArray2 count]); } -(IBAction)switchViews{ SecondViewController *screen = [[SecondViewController alloc] initWithNibName:nil bundle:nil]; screen.modalTransitionStyle = UIModalTransitionStyleCoverVertical; [self presentModalViewController:screen animated:YES]; [screen release]; } SecondViewController.m #import "SecondViewController.h" #import "RootViewController.h" @implementation SecondViewController -(IBAction)addToArray{ RootViewController *object = [[RootViewController alloc] init]; [object addToArray2]; } -(IBAction)switchBack{ [self dismissModalViewControllerAnimated:YES]; } EDIT***** With Matt's code I got the following error: " expected specifier-qualifier-list before 'RootViewController' "

    Read the article

  • Strict pointer aliasing: is access through a 'volatile' pointer/reference a solution?

    - by doublep
    On the heels of a specific problem, a self-answer and comments to it, I'd like to understand if it is a proper solution, workaround/hack or just plain wrong. Specifically, I rewrote code: T x = ...; if (*reinterpret_cast <int*> (&x) == 0) ... As: T x = ...; if (*reinterpret_cast <volatile int*> (&x) == 0) ... with a volatile qualifier to the pointer. Let's just assume that treating T as int in my situation makes sense. Does this accessing through a volatile reference solve pointer aliasing problem? For a reference, from specification: [ Note: volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation. See 1.9 for detailed semantics. In general, the semantics of volatile are intended to be the same in C++ as they are in C. — end note ] EDIT: The above code did solve my problem at least on GCC 4.5.

    Read the article

  • C++ Namespaces & templates question

    - by Kotti
    Hi! I have some functions that can be grouped together, but don't belong to some object / entity and therefore can't be treated as methods. So, basically in this situation I would create a new namespace and put the definitions in a header file, the implementation in cpp file. Also (if needed) I would create an anonymous namespace in that cpp file and put all additional functions that don't have to be exposed / included to my namespace's interface there. See the code below (probably not the best example and could be done better with another program architecture, but I just can't think of a better sample...) Sample code (header) namespace algorithm { void HandleCollision(Object* object1, Object* object2); } Sample code (cpp) #include "header" // Anonymous namespace that wraps // routines that are used inside 'algorithm' methods // but don't have to be exposed namespace { void RefractObject(Object* object1) { // Do something with that object // (...) } } namespace algorithm { void HandleCollision(Object* object1, Object* object2) { if (...) RefractObject(object1); } } So far so good. I guess this is a good way to manage my code, but I don't know what should I do if I have some template-based functions and want to do basically the same. If I'm using templates, I have to put all my code in the header file. Ok, but how should I conceal some implementation details then? Like, I want to hide RefractObject function from my interface, but I can't simply remove it's declaration (just because I have all my code in a header file)... The only approach I came up with was something like: Sample code (header) namespace algorithm { // Is still exposed as a part of interface! namespace impl { template <typename T> void RefractObject(T* object1) { // Do something with that object // (...) } } template <typename T, typename Y> void HandleCollision(T* object1, Y* object2) { impl::RefractObject(object1); // Another stuff } } Any ideas how to make this better in terms of code designing?

    Read the article

  • C++ destructor problem with boost::scoped_ptr

    - by bb-generation
    I have a question about the following code: #include <iostream> #include <boost/scoped_ptr.hpp> class Interface { }; class A : public Interface { public: A() { std::cout << "A()" << std::endl; } virtual ~A() { std::cout << "~A()" << std::endl; } }; Interface* get_a() { A* a = new A; return a; } int main() { { std::cout << "1" << std::endl; boost::scoped_ptr<Interface> x(get_a()); std::cout << "2" << std::endl; } std::cout << "3" << std::endl; } It creates the following output: 1 A() 2 3 As you can see, it doesn't call the destructor of A. The only way I see to get the destructor of A being called, is to add a destructor for the Interface class like this: virtual ~Interface() { } But I really want to avoid any Implementation in my Interface class and virtual ~Interface() = 0; doesn't work (produces some linker errors complaining about a non existing implementation of ~Interface(). So my question is: What do I have to change in order to make the destructor being called, but (if possible) leave the Interface as an Interface (only abstract methods).

    Read the article

  • In Varnish, how can I read the Set-Cookie response header?

    - by Adam Friedman
    I am trying to detect if my application has set a cookie that holds an "alert message" for the user on the next page, where the Javascript displays it if detected. In my vcl_fetch(), I need to detect if the specific cookie value "alert_message" appears anywhere in the Set-Cookie header (presumably in the VCL variable beresp.http.Set-Cookie). If detected, then I do not want to cache that next page (since Varnish strips the Set-Cookie header by default, which would obliterate the alert message before it makes it back to the browser). So here is my simple test: if(beresp.http.Set-Cookie ~ "alert_message") { set req.http.no_cache = 1; } Strangely, it fails to evaluate to true. So I throw the variable into the Server header to see what it looks like: set beresp.http.Server = " MyApp Varnish implementation - test reading set-cookie: "+beresp.http.Set-Cookie; But for some reason this only displays the FIRST Set-Cookie line in the response headers. Here are the relevant response headers: Server: MyApp Varnish implementation - test reading cookie: elstats_session=7d7279kjmsnkel31lre3s0vu24; expires=Wed, 10-Oct-2012 00:03:32 GMT; path=/; HttpOnly Set-Cookie:app_session=7d7279kjmsnkel31lre3s0vu24; expires=Wed, 10-Oct-2012 00:03:32 GMT; path=/; HttpOnly Set-Cookie:alert_message=Too+many+results.; expires=Tue, 09-Oct-2012 20:13:32 GMT; path=/; domain=.my.app.com Set-Cookie:alert_key=flash_error; expires=Tue, 09-Oct-2012 20:13:32 GMT; path=/; domain=.my.app.com Vary:Accept-Encoding How do I read and run string detection on ALL Set-Cookie header lines?

    Read the article

  • objective-c having issues with an NSDictioary object

    - by Mark
    I have a simple iPhone app that Im learning and I want to have an instance variable called urlLists which is an NSDictionary I have declared it like so: @interface MyViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate>{ IBOutlet UIPickerView *pickerView; NSMutableArray *categories; NSDictionary *urlLists; } @property(retain) NSDictionary *urlLists; @end and in the implementation: @implementation MyViewController @synthesize urlLists; ... - (void)viewDidLoad { [super viewDidLoad]; categories = [[NSMutableArray alloc] init]; [categories addObject:@"Sport"]; [categories addObject:@"Entertainment"]; [categories addObject:@"Technology"]; [categories addObject:@"Political"]; NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", @"value3", @"value4", nil]; urlLists = [NSDictionary dictionaryWithObjects:objects forKeys:categories]; for (id key in urlLists) { NSLog(@"key: %@, value: %@", key, [urlLists objectForKey:key]); } } ... @end And, this all works up to here. I have added a UIPicker to my app, and when I select one of the items, I want to Log the one picked and its related entry in my dictionary. -(void) pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger) component { for (id key in self.urlLists) { NSLog(@"key: %@, value: %@", key, [urlLists objectForKey:key]); } } but I get the old EXC_BAD_ACCESS error... I know Im missing something small, but what? Thanks

    Read the article

  • Invoke Command When "ENTER" Key Is Pressed In XAML

    - by bitxwise
    I want to invoke a command when ENTER is pressed in a TextBox. Consider the following XAML: <UserControl ... xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" ...> ... <TextBox> <i:Interaction.Triggers> <i:EventTrigger EventName="KeyUp"> <i:InvokeCommandAction Command="{Binding MyCommand}" CommandParameter="{Binding Text}" /> </i:EventTrigger> </i:Interaction.Triggers> </TextBox> ... </UserControl> and that MyCommand is as follows: public ICommand MyCommand { get { return new DelegateCommand<string>(MyCommandExecute); } } private void MyCommandExecute(string s) { ... } With the above, my command is invoked for every key press. How can I restrict the command to only invoke when the ENTER key is pressed? I understand that with Expression Blend I can use Conditions but those seem to be restricted to elements and can't consider event arguments. I have also come across SLEX which offers its own InvokeCommandAction implementation that is built on top of the Systems.Windows.Interactivity implementation and can do what I need. Another consideration is to write my own trigger, but I'm hoping there's a way to do it without using external toolkits.

    Read the article

  • Best way to organize a Go interface

    - by Metropolis
    Hey Everyone, Its been a long time since I have programmed in C++, and if I remember correctly the best way to organize classes was to create your class in the .h file, and then your implementation in your .cpp file. Well I am trying to learn Go now and I was reading over the Go for C++ Programmers article when I came upon interfaces. The article explains that interfaces in Go essentially take the place of classes, and shows how to set them up pretty well. What I am trying to figure out though is how should I organize an interface into files? For instance, should the interface be in one file while the implementation is in another? myInterface.go type myInterface interface { get() int set(i int) } myImplementation.go type myType struct { i int } func (p *myType) set(i int) { p.i = i } func (p *myType) get() int { return p.i } My code here may be wrong since I do not completely know what I am doing yet (and if I am wrong please correct me), but would this be the best way to set this up? Im having a very hard time trying to wrap my head around how to organize code in Go so any help is appreciated! Metropolis

    Read the article

  • Array indexOf implentation for Internet Explorer

    - by Daemon
    There are plenty of solutions on how to get the indexOf implementation into the Array prototype so that it works under Internet Explorer, however I've stumbled upon an issue that doesn't seem to be addressed anywhere I've looked so far. Using the pretty well agreed upon implementation at MDC, I have the following code that's being problematic now: // indexOf support for IE (from MDC) if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in this && this[from] === elt) return from; } return -1; }; } var i = [1,2,3,4]; for (j in i) { alert(i[j]); } I am expecting to receive 4 alerts, each one containing one of the elements of the array. In Firefox and Chrome, that's exactly what I see, however in IE8 I get an additional alert containing the indexOf function code. What can be done to avoid this?

    Read the article

  • Combining Java hashcodes into a "master" hashcode

    - by Nick Wiggill
    I have a vector class with hashCode() implemented. It wasn't written by me, but uses 2 prime numbers by which to multiply the 2 vector components before XORing them. Here it is: /*class Vector2f*/ ... public int hashCode() { return 997 * ((int)x) ^ 991 * ((int)y); //large primes! } ...As this is from an established Java library, I know that it works just fine. Then I have a Boundary class, which holds 2 vectors, "start" and "end" (representing the endpoints of a line). The values of these 2 vectors are what characterize the boundary. /*class Boundary*/ ... public int hashCode() { return 1013 * (start.hashCode()) ^ 1009 * (end.hashCode()); } Here I have attempted to create a good hashCode() for the unique 2-tuple of vectors (start & end) constituting this boundary. My question: Is this hashCode() implementation going to work? (Note that I have used 2 different prime numbers in the latter hashCode() implementation; I don't know if this is necessary but better to be safe than sorry when trying to avoid common factors, I guess -- since I presume this is why primes are popular for hashing functions.)

    Read the article

  • Loading views dynamically

    - by Dan
    Case 1: I have created View-based sample application and tried execute below code. When I press on "Job List" button it should load another view having "Back Btn" on it. In test function, if I use [self.navigationController pushViewController:jbc animated:YES]; nothing gets loaded, but if I use [self presentModalViewController:jbc animated:YES]; it loads another view haveing "Back Btn" on it. Case 2: I did create another Navigation Based Applicaton and used [self.navigationController pushViewController:jbc animated:YES]; it worked as I wanted. Can someone please explain why it was not working in Case 1. Does it has something to do with type of project that is selected? @interface MWViewController : UIViewController { } -(void) test; @end @interface JobViewCtrl : UIViewController { } @end @implementation MWViewController (void)viewDidLoad { UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btn.frame = CGRectMake(80, 170, 150, 35); [btn setTitle:@"Job List!" forState:UIControlStateNormal]; [btn addTarget:self action:@selector(test) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; [super viewDidLoad]; } -(void) test { JobViewCtrl* jbc = [[JobViewCtrl alloc] init]; [self.navigationController pushViewController:jbc animated:YES]; //[self presentModalViewController:jbc animated:YES]; [jbc release]; } (void)dealloc { [super dealloc]; } @end @implementation JobViewCtrl -(void) loadView { self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]]; self.view.backgroundColor = [UIColor grayColor]; UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btn.frame = CGRectMake(80, 170, 150, 35); [btn setTitle:@"Back Btn!" forState:UIControlStateNormal]; [self.view addSubview:btn]; } @end

    Read the article

  • Custom Image Button and Radio/Toggle Button from Common Base Class

    - by Wonko the Sane
    Hi All, I would like to create a set of custom controls that are basically image buttons (it's a little more complex than that, but that's the underlying effect I'm going for) that I've seen a few different examples for. However, I would like to further extend that to also allow radio/toggle buttons. What I'd like to do is have a common abstract class called ImageButtonBase that has default implementations for ImageSource and Text, etc. That makes a regular ImageButton implementation pretty easy. The issue I am having is creating the RadioButton flavor of it. As I see it, there are at least three options: It would be easy to create something that derives from RadioButton, but then I can't use the abstract class I've created. I could change the abstract class to an interface, but then I lose the abstract implementations, and will in fact have duplication of code. I could derive from my abstract class, and re-implement the RadioButton-type properties and events (IsChecked, GroupName, etc.), but that certainly doesn't seem like a great idea. Note: I have seen http://stackoverflow.com/questions/2362641/how-to-get-a-group-of-toggle-buttons-to-act-like-radio-buttons-in-wpf, but what I want to do is a little more complex. I'm just wondering if anybody has an example of an implementation, or something that might be adapted to this kind of scenario. I can see pros and cons of each of the ideas above, but each comes with potential pitfalls. Thanks, wTs

    Read the article

  • Is it possible to customize @synthesized properties?

    - by Dan K.
    I'm probably just being a bit lazy here, but bear with me. Here's my situation. I have a class with two nonatomic, retained properties. Let's say: @property (nonatomic, retain) UITextField *dateField; @property (nonatomic, retain) NSDate *date; I synthesize them as expected in the implementation. What I want to happen is that whenever the setter on date is invoked, it also does something to the dateField (i.e. it sets the text property on the dateField to be a nicely formatted version of the date). I realize I can just manually override the setter for date in my implementation by doing the following: - (void) setDate:(NSDate *)newDate { if (date != newDate) { [date release]; date = [newDate retain]; // my code to touch the dateField goes here } } What would be awesome is if I could let Objective C handle the retain/release cycle, but still be able to "register" (for lack of a better term) a custom handler that would be invoked after the retain/release/set happens. My guess is that isn't possible. My google-fu didn't come up with any answer to this, though, so I thought I'd ask.

    Read the article

  • Dimension Reduction in Categorical Data with missing values

    - by user227290
    I have a regression model in which the dependent variable is continuous but ninety percent of the independent variables are categorical(both ordered and unordered) and around thirty percent of the records have missing values(to make matters worse they are missing randomly without any pattern, that is, more that forty five percent of the data hava at least one missing value). There is no a priori theory to choose the specification of the model so one of the key tasks is dimension reduction before running the regression. While I am aware of several methods for dimension reduction for continuous variables I am not aware of a similar statical literature for categorical data (except, perhaps, as a part of correspondence analysis which is basically a variation of principal component analysis on frequency table). Let me also add that the dataset is of moderate size 500000 observations with 200 variables. I have two questions. Is there a good statistical reference out there for dimension reduction for categorical data along with robust imputation (I think the first issue is imputation and then dimension reduction)? This is linked to implementation of above problem. I have used R extensively earlier and tend to use transcan and impute function heavily for continuous variables and use a variation of tree method to impute categorical values. I have a working knowledge of Python so if something is nice out there for this purpose then I will use it. Any implementation pointers in python or R will be of great help. Thank you.

    Read the article

  • Passing Extras and screen rotation

    - by Luis A. Florit
    This kind of questions appear periodically. Sorry if this has been covered before, but I'm a newbie and couldn't find the appropriate answer. It deals with the correct implementation of communication between classes and activities. I made a gallery app. It has 3 main activities: the Main one, to search for filenames using a pattern; a Thumb one, that shows all the images that matched the pattern as thumbnails in a gridview, and a Photo activity, that opens a full sized image when you click a thumb in Thumbs. I pass to the Photo activity via an Intent the filenames (an array), and the position (an int) of the clicked thumb in the gridview. This third Photo activity has only one view on it: a TouchImageView, that I adapted for previous/next switching and zooming according to where you shortclick on the image (left, right or middle). Moreover, I added a longclick listener to Photo to show EXIF info. The thing is working, but I am not happy with the implementation... Some things are not right. One of the problems I am experiencing is that, if I click on the right of the image to see the next in the Photo activity, it switches fine (position++), but when rotating the device the original one at position appears. What is happening is that Photo is destroyed when rotating the image, and for some reason it restarts again, without obeying super.onCreate(savedInstanceState), loading again the Extras (the position only changed in Photo, not on the parent activities). I tried with startActivityForResult instead of startActivity, but failed... Of course I can do something contrived to save the position data, but there should be something "conceptual" that I am not understanding about how activities work, and I want to do this right. Can someone please explain me what I am doing wrong, which is the best method to implement what I want, and why? Thanks a lot!!!

    Read the article

  • Etiquette: Version bump my fork of opensource project?

    - by Ross
    This question is about etiquette and open source projects. I have forked an application from github and added two new features. The first feature has been request frequently elsewhere. I have added it. Code & implementation are clean (I think). The second feature is more of a hack. It will be of use to others, but the implementation is a little dirty in useage and more so in code. I need the feature but I don't have the skills to fully implement it properly or to a level that could be considered a worth while contrabution to the main project. How should the versioning work? Do I just bump up my version numbers care-free and push to my master branch? It is annoying to know which version is running, modifed or original, as both have the same version number. But will it be confusing when, months later, my github page has a version number the same as the original but both are actually completely different. (I have made pull requests etc. but that is not the context of my question.) The project I have forked uses ruby jeweler so has a versioning format of: Jeweler tracks the version of your project. It assumes you will be using a version in the format x.y.z. x is the 'major' version, y is the 'minor' version, and z is the patch version. Is this standard for other projects/langauges too? Are my changes patches? Thanks

    Read the article

  • Splitting Code into Headers/Source files

    - by cam
    I took the following code from the examples page on Asio class tcp_connection : public boost::enable_shared_from_this<tcp_connection> { public: typedef boost::shared_ptr<tcp_connection> pointer; static pointer create(boost::asio::io_service& io_service) { return pointer(new tcp_connection(io_service)); } tcp::socket& socket() { return socket_; } void start() { message_ = make_daytime_string(); boost::asio::async_write(socket_, boost::asio::buffer(message_), boost::bind(&tcp_connection::handle_write, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } private: tcp_connection(boost::asio::io_service& io_service) : socket_(io_service) { } void handle_write(const boost::system::error_code& /*error*/, size_t /*bytes_transferred*/) { } tcp::socket socket_; std::string message_; }; I'm relatively new to C++ (from a C# background), and from what I understand, most people would split this into header and source files (declaration/implementation, respectively). Is there any reason I can't just leave it in the header file if I'm going to use it across many source files? If so, are there any tools that will automatically convert it to declaration/implementation for me? Can someone show me what this would look like split into header/source file for an example (or just part of it, anyway)? I get confused around weird stuff like thistypedef boost::shared_ptr<tcp_connection> pointer; Do I include this in the header or the source? Same with tcp::socket& socket() I've read many tutorials, but this has always been something that has confused me about C++.

    Read the article

  • unclear use of @property in window app using core data

    - by Matt
    Looking through a Window based application ive used to experiment with as a way of getting my head around core data, ive noticed that the appdelegate has the following code myAppDelegate.h #import <UIKit/UIKit.h> #import <CoreData/CoreData.h> @interface iCaptureFreeAppDelegate : NSObject <UIApplicationDelegate> { NSManagedObjectModel *managedObjectModel; NSManagedObjectContext *managedObjectContext; NSPersistentStoreCoordinator *persistentStoreCoordinator; UIWindow *window; UITabBarController *tabBarController; } myAppDelegate.m #import "myAppDelegate.h" @interface iCaptureFreeAppDelegate (PrivateCoreDataStack) @property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel; @property (nonatomic, retain) NSManagedObjectContext *managedObjectContext; @property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator; @end @implementation iCaptureFreeAppDelegate @synthesize window, tabBarController; // code .... // - (NSManagedObjectContext *) managedObjectContext { } - (NSManagedObjectModel *)managedObjectModel { } - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { } // etc..... i want to understand a few things about what this project is doing why the properties in the category declaration? (if i delete the privateCoreDataStack category everything still works...) why the properties appear to be linked with the methods in the implementation ... managedObjectContext {} etc why the members in the .h file have the same name as the properties and the methods why code completion lets me use dot '.' to access the members but then fails on compilation say it cant find a getter thanks !

    Read the article

  • Xml Conversion "Type mismatch" Error

    - by prema
    I am selecting a query in sql server 2005 SELECT 'Region' AS ELEMENT,(SELECT GeographyName,GeoID from @tmpTable FOR XML RAW, TYPE) FOR XML RAW('Root') This will give the output in xml as <Root ELEMENT="Region"> <row GeographyName="East" GeoID="2" /> <row GeographyName="West" GeoID="3" /> <row GeographyName="North" GeoID="4" /> <row GeographyName="South" GeoID="5" /> </Root> In aspx page, i want to get this function Populatedata(obj, val) { var xmlDom = new JXmlDom(obj, false); --> at this point i am getting error var nodeHeader = xmlDom.selectNodes("//row"); // my code goes here } function JXmlDom (xml,isFile) { this.load=load; this.loadXML=loadXML; this.selectNodes=selectNodes; this.text=text; this.selectSingleNode=selectSingleNode; this.documentElement=documentElement; this.transformNode=transformNode; if (isFile) { this.dom=this.load (xml); }else { this.dom=this.loadXML (xml); } function loadXML (xml) { if (window.ActiveXObject) { var dom=new ActiveXObject("Microsoft.XMLDOm"); dom.async=false; dom.loadXML (xml); } if (document.implementation && document.implementation.createDocument) { var domParser=new DOMParser(); var dom=domParser.parseFromString (xml,"text/xml"); } return dom; } But when i am calling this i am getting an error as Type mismatch.Can anyone help me

    Read the article

  • Java : Inner class of an interface (from google guice)

    - by bsreekanth
    Hello, I was going through the source of google guice, and found an unfamiliar piece of code. It would be great learning if someone can clarify it. I have very basic understanding of inner classes, as they keep the implementation details close to the public interface. Otherwise the inner class may pollute the namespace. Now, I see the below lines at public static final Scope SINGLETON = new Scope() { public <T> Provider<T> scope(final Key<T> key, final Provider<T> creator) { return new Provider<T>() { ......... } It assign an inner class instance to the static variable, but Scope is an interface defined as (at) public interface Scope Is it possible to instantiate the interface?? or is it a succinct syntax for an anonymous implementation of an interface?? If anyone can explain what the author is intended by multiple nested classes above (Scope and Provider), and why it make sense to implement this way, it would help me to understand. thanks.

    Read the article

  • Noise with multi-threaded raytracer

    - by herber88
    This is my first multi-threaded implementation, so it's probably a beginners mistake. The threads handle the rendering of every second row of pixels (so all rendering is handled within each thread). The problem persists if the threads render the upper and lower parts of the screen respectively. Both threads read from the same variables, can this cause any problems? From what I've understood only writing can cause concurrency problems... Can calling the same functions cause any concurrency problems? And again, from what I've understood this shouldn't be a problem... The only time both threads write to the same variable is when saving the calculated pixel color. This is stored in an array, but they never write to the same indices in that array. Can this cause a problem? Multi-threaded rendered image (Spam prevention stops me from posting images directly..) Ps. I use the exactly same implementation in both cases, the ONLY difference is a single vs. two threads created for the rendering.

    Read the article

  • Can I control object creation using MEF?

    - by Akash
    I need to add some extension points to our existing code, and I've been looking at MEF as a possible solution. We have an IRandomNumberGenerator interface, with a default implementation (ConcreteRNG) that we would like to be swappable. This sounds like an ideal scenario for MEF, but I've been having problems with the way we instantiate the random number generators. Our current code looks like: public class Consumer { private List<IRandomNumberGenerator> generators; private List<double> seeds; public Consumer() { generators = new List<IRandomNumberGenerator>(); seeds = new List<double>(new[] {1.0, 2.0, 3.0}); foreach(var seed in seeds) { generators.Add(new ConcreteRNG(seed); } } } In other words, the consumer is responsible for instantiating the RNGs it needs, including providing the seed that each instance requires. What I'd like to do is to have the concrete RNG implementation discovered and instantiated by MEF (using the DirectoryCatalog). I'm not sure how to achieve this. I could expose a Generators property and mark it as an [Import], but how do I provide the required seeds? Is there some other approach I am missing?

    Read the article

  • Is it legal to take sealed .NET framework class source and extend it?

    - by Giedrius
    To be short, I'm giving very specific example, but I'm interested in general situation. There is a FtpWebRequest class in .NET framework and it is missing some of new FTP operations, like MFCT. It is ok in a sense that this operation is still in draft mode, but it is not ok in a sense, that FtpWebRequest is sealed and there's no other way (at least I don't see it) to extend it with this new operation. Easiest way to do it would be take FtpWebRequest class source from .NET reference sources and extend it, in such way will be kept all the consistence in naming, implementation, etc. Question is how much legal it is? I won't sell this class as a product, I can publish my changes on web - nothing to hide here. If it is not legal, can I take this class source from mono and include in native .net project? Did you had similar case and how you solved it? Update: as long as extension method is offered, I'm pasting source from .NET framework which should show that extension methods are not the solution. So there's a property Method, where you can pass FTP command: public override string Method { get { return m_MethodInfo.Method; } set { if (String.IsNullOrEmpty(value)) { throw new ArgumentException(SR.GetString(SR.net_ftp_invalid_method_name), "value"); } if (InUse) { throw new InvalidOperationException(SR.GetString(SR.net_reqsubmitted)); } try { m_MethodInfo = FtpMethodInfo.GetMethodInfo(value); } catch (ArgumentException) { throw new ArgumentException(SR.GetString(SR.net_ftp_unsupported_method), "value"); } } } As you can see there FtpMethodInfo.GetMethodInfo(value) call in setter, which basically validates value against internal enum static array. Update 2: Checked mono implementation and it is not exact replica of native code + it does not implement some of the things.

    Read the article

  • Unit Testing - Algorithm or Sample based ?

    - by ohadsc
    Say I'm trying to test a simple Set class public IntSet : IEnumerable<int> { Add(int i) {...} //IEnumerable implementation... } And suppose I'm trying to test that no duplicate values can exist in the set. My first option is to insert some sample data into the set, and test for duplicates using my knowledge of the data I used, for example: //OPTION 1 void InsertDuplicateValues_OnlyOneInstancePerValueShouldBeInTheSet() { var set = new IntSet(); //3 will be added 3 times var values = new List<int> {1, 2, 3, 3, 3, 4, 5}; foreach (int i in values) set.Add(i); //I know 3 is the only candidate to appear multiple times int counter = 0; foreach (int i in set) if (i == 3) counter++; Assert.AreEqual(1, counter); } My second option is to test for my condition generically: //OPTION 2 void InsertDuplicateValues_OnlyOneInstancePerValueShouldBeInTheSet() { var set = new IntSet(); //The following could even be a list of random numbers with a duplicate var values = new List<int> { 1, 2, 3, 3, 3, 4, 5}; foreach (int i in values) set.Add(i); //I am not using my prior knowledge of the sample data //the following line would work for any data CollectionAssert.AreEquivalent(new HashSet<int>(values), set); } Of course, in this example, I conveniently have a set implementation to check against, as well as code to compare collections (CollectionAssert). But what if I didn't have either ? This is the situation when you are testing your real life custom business logic. Granted, testing for expected conditions generically covers more cases - but it becomes very similar to implementing the logic again (which is both tedious and useless - you can't use the same code to check itself!). Basically I'm asking whether my tests should look like "insert 1, 2, 3 then check something about 3" or "insert 1, 2, 3 and check for something in general" EDIT - To help me understand, please state in your answer if you prefer OPTION 1 or OPTION 2 (or neither, or that it depends on the case, etc )

    Read the article

  • How to limit TCP writes to particular size and then block untlil the data is read

    - by ustulation
    {Qt 4.7.0 , VS 2010} I have a Server written in Qt and a 3rd party client executable. Qt based server uses QTcpServer and QTcpSocket facilities (non-blocking). Going through the articles on TCP I understand the following: the original implementation of TCP mentioned the negotiable window size to be a 16-bit value, thus maximum being 65535 bytes. But implementations often used the RFC window-scale-extension that allows the sliding window size to be scalable by bit-shifting to yield a maximum of 1 gigabyte. This is implementation defined. This could have resulted in majorly different window sizes on receiver and sender end as the server uses Qt facilities without hardcoding any window size limit. Client 1st asks for all information it can based on the previous messages from the server before handling the new (accumulating) incoming messages. So at some point Server receives a lot of messages each asking for data of several MB's. This the server processes and puts it into the sender buffer. Client however is unable to handle the messages at the same pace and it seems that client’s receiver buffer is far smaller (65535 bytes maybe) than sender’s transmit window size. The messages thus get accumulated at sender’s end until the sender’s buffer is full too after which the TCP writes on sender would block. This however does not happen as sender buffer is much larger. Hence this manifests as increase in memory consumption on the sender’s end. To prevent this from happening, I used Qt’s socket’s waitForBytesWritten() with timeout set to -1 for infinite waiting period. This as I see from the behaviour blocks the thread writing TCP data until the data has actually been sensed by the receiver’s window (which will happen when earlier messages have been processed by the client at application level). This has caused memory consumption at Server end to be almost negligible. is there a better alternative to this (in Qt) if i want to restrict the memory consumption at server end to say x MB's? Also please point out if any of my understandings is incorrect.

    Read the article

< Previous Page | 88 89 90 91 92 93 94 95 96 97 98 99  | Next Page >