Search Results

Search found 332 results on 14 pages for 'baz'.

Page 1/14 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • How to test that invalid arguments raise an ArgumentError exception using RSpec?

    - by John Topley
    I'm writing a RubyGem that can raise an ArgumentError if the arguments supplied to its single method are invalid. How can I write a test for this using RSpec? The example below shows the sort of implementation I have in mind. The bar method expects a single boolean argument (:baz), the type of which is checked to make sure that it actually is a boolean: module Foo def self.bar(options = {}) baz = options.fetch(:baz, true) validate_arguments(baz) end def self.validate_arguments(baz) raise(ArgumentError, ":baz must be a boolean") unless valid_baz?(baz) end def self.valid_baz?(baz) baz.is_a?(TrueClass) || baz.is_a?(FalseClass) end end

    Read the article

  • [Ruby] Object assignment and pointers

    - by Jergason
    I am a little confused about object assignment and pointers in Ruby, and coded up this snippet to test my assumptions. class Foo attr_accessor :one, :two def initialize(one, two) @one = one @two = two end end bar = Foo.new(1, 2) beans = bar puts bar puts beans beans.one = 2 puts bar puts beans puts beans.one puts bar.one I had assumed that when I assigned bar to beans, it would create a copy of the object, and modifying one would not affect the other. Alas, the output shows otherwise. ^_^[jergason:~]$ ruby test.rb #<Foo:0x100155c60> #<Foo:0x100155c60> #<Foo:0x100155c60> #<Foo:0x100155c60> 2 2 I believe that the numbers have something to do with the address of the object, and they are the same for both beans and bar, and when I modify beans, bar gets changed as well, which is not what I had expected. It appears that I am only creating a pointer to the object, not a copy of it. What do I need to do to copy the object on assignment, instead of creating a pointer? Tests with the Array class shows some strange behavior as well. foo = [0, 1, 2, 3, 4, 5] baz = foo puts "foo is #{foo}" puts "baz is #{baz}" foo.pop puts "foo is #{foo}" puts "baz is #{baz}" foo += ["a hill of beans is a wonderful thing"] puts "foo is #{foo}" puts "baz is #{baz}" This produces the following wonky output: foo is 012345 baz is 012345 foo is 01234 baz is 01234 foo is 01234a hill of beans is a wonderful thing baz is 01234 This blows my mind. Calling pop on foo affects baz as well, so it isn't a copy, but concatenating something onto foo only affects foo, and not baz. So when am I dealing with the original object, and when am I dealing with a copy? In my own classes, how can I make sure that assignment copies, and doesn't make pointers? Help this confused guy out.

    Read the article

  • Frustration with generics

    - by sbi
    I have a bunch of functions which are currently overloaded to operate on int and string: bool foo(int); bool foo(string); bool bar(int); bool bar(string); void baz(int p); void baz(string p); I then have a bunch of functions taking 1, 2, 3, or 4 arguments of either int or string, which call the aforementioned functions: void g(int p1) { if(foo(p1)) baz(p1); } void g(string p1) { if(foo(p1)) baz(p1); } void g(int p2, int p2) { if(foo(p1)) baz(p1); if(bar(p2)) baz(p2); } void g(int p2, string p2) { if(foo(p1)) baz(p1); if(bar(p2)) baz(p2); } void g(string p2, int p2) { if(foo(p1)) baz(p1); if(bar(p2)) baz(p2); } void g(string p2, string p2) { if(foo(p1)) baz(p1); if(bar(p2)) baz(p2); } // etc. (The implementation of the g() family is just a placeholder. actually they are more complicated.) More types than the current int or string might have to be introduced at any time. The same goes for functions with more arguments than 4. The current number of identical functions is barely manageable. Add one more variant in either dimension and the combinatoric explosion will be so huge, it might blow away the application. In C++, I'd templatize g() and be done. I understand that .NET generics are different. <sigh> But I have been fighting them for two hours trying to come up with a solution that doesn't involve too much copy&paste of code. To no avail. Surely, C#/.NET/generics/whatever won't require me to type out identical code for a family of functions taking five arguments of either of three types? So what am I missing here?

    Read the article

  • Use of (non) qualified names

    - by AProgrammer
    If I want to use the name baz defined in package foo|bar|quz, I've several choices: provide fbq as a short name for foo|bar|quz and use fbq|baz use foo|bar|quz|baz import baz from foo|bar|quz|baz and then use baz (or an alias given in the import process) import all public symbols from foo|bar|quz|baz and then use baz For the languages I know, my perception is that the best practice is to use the first two ways (I'll use one or the other depending on the specific package full name and the number of symbols I need from it). I'd use the third only in a language which doesn't provide the first and hunt for supporting tools to write the import statements. And in my opinion the fourth should be reserved to package designed with than import in mind, for instance if all exported symbols start with a prefix or contains the name of the package. My questions: what is in your opinion the best practice for your favorite languages? what would you suggest in a new language? what would you suggest in an old language adding such a feature?

    Read the article

  • How do I split filenames from paths using python?

    - by Rasputin Jones
    I have a list of files that look like this: Input /foo/bar/baz/d4dc7c496100e8ce0166e84699b4e267fe652faeb070db18c76669d1c6f69f92.mp4 /foo/baz/bar/60d24a24f19a6b6c1c4734e0f288720c9ce429bc41c2620d32e01e934bfcd344.mp4 /bar/baz/foo/cd53fe086717a9f6fecb1d0567f6d76e93c48d7790c55e83e83dd1c43251e40e.mp4 And I would like to split out the filenames from the path while retaining both. Output ['/foo/bar/baz/', 'd4dc7c496100e8ce0166e84699b4e267fe652faeb070db18c76669d1c6f69f92.mp4'] ['/foo/baz/bar/', '60d24a24f19a6b6c1c4734e0f288720c9ce429bc41c2620d32e01e934bfcd344.mp4'] ['/bar/baz/foo', 'd53fe086717a9f6fecb1d0567f6d76e93c48d7790c55e83e83dd1c43251e40e.mp4'] How would one go about this? Thanks!

    Read the article

  • XML to be validated against multiple xsd schemas

    - by Michael Rusch
    I'm writing the xsd and the code to validate, so I have great control here. I would like to have an upload facility that adds stuff to my application based on an xml file. One part of the xml file should be validated against different schemas based on one of the values in the other part of it. Here's an example to illustrate: <foo> <name>Harold</name> <bar>Alpha</bar> <baz>Mercury</baz> <!-- ... more general info that applies to all foos ... --> <bar-config> <!-- the content here is specific to the bar named "Alpha" --> </bar-config> <baz-config> <!-- the content here is specific to the baz named "Mercury" --> </baz> </foo> In this case, there is some controlled vocabulary for the content of <bar>, and I can handle that part just fine. Then, based on the bar value, the appropriate xml schema should be used to validate the content of bar-config. Similarly for baz and baz-config. The code doing the parsing/validation is written in Java. Not sure how language-dependent the solution will be. Ideally, the solution would permit the xml author to declare the appropriate schema locations and what-not so that s/he could get the xml validated on the fly in a sufficiently smart editor. Also, the possible values for <bar> and <baz> are orthogonal, so I don't want to do this by extension for every possible bar/baz combo. What I mean is, if there are 24 possible bar values/schemas and 8 possible baz values/schemas, I want to be able to write 1 + 24 + 8 = 33 total schemas, instead of 1 * 24 * 8 = 192 total schemas. Also, I'd prefer to NOT break out the bar-config and baz-config into separate xml files if possible. I realize that might make all the problems much easier, as each xml file would have a single schema, but I'm trying to see if there is a good single-xml-file solution.

    Read the article

  • Mounting filesystem with special user id set

    - by qbi
    I want to mount the device /dev/sda3 to the directory /foo/bar/baz. After mounting the directory should have the uid of user johndoe. So I did: sudo -u johndoe mkdir /foo/bar/baz stat -c %U /foo/bar/baz johndoe and added the following line to my /etc/fstab: /dev/sda3 /foo/bar/baz ext4 noexec,noatime,auto,owner,nodev,nosuid,user 0 1 When I do now sudo -u johndoe mount /dev/sda3 the command stat -c %U /foo/bar/baz results in root rather than johndoe. What is the best way to mount this ext4-filesystem with uid johndoe set?

    Read the article

  • How do I add a column that displays the number of distinct rows to this query?

    - by Fake Code Monkey Rashid
    Hello good people! I don't know how to ask my question clearly so I'll just show you the money. To start with, here's a sample table: CREATE TABLE sandbox ( id integer NOT NULL, callsign text NOT NULL, this text NOT NULL, that text NOT NULL, "timestamp" timestamp with time zone DEFAULT now() NOT NULL ); CREATE SEQUENCE sandbox_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER SEQUENCE sandbox_id_seq OWNED BY sandbox.id; SELECT pg_catalog.setval('sandbox_id_seq', 14, true); ALTER TABLE sandbox ALTER COLUMN id SET DEFAULT nextval('sandbox_id_seq'::regclass); INSERT INTO sandbox VALUES (1, 'alpha', 'foo', 'qux', '2010-12-29 16:51:09.897579+00'); INSERT INTO sandbox VALUES (2, 'alpha', 'foo', 'qux', '2010-12-29 16:51:36.108867+00'); INSERT INTO sandbox VALUES (3, 'bravo', 'bar', 'quxx', '2010-12-29 16:52:36.370507+00'); INSERT INTO sandbox VALUES (4, 'bravo', 'foo', 'quxx', '2010-12-29 16:52:47.584663+00'); INSERT INTO sandbox VALUES (5, 'charlie', 'foo', 'corge', '2010-12-29 16:53:00.742356+00'); INSERT INTO sandbox VALUES (6, 'delta', 'foo', 'qux', '2010-12-29 16:53:10.884721+00'); INSERT INTO sandbox VALUES (7, 'alpha', 'foo', 'corge', '2010-12-29 16:53:21.242904+00'); INSERT INTO sandbox VALUES (8, 'alpha', 'bar', 'corge', '2010-12-29 16:54:33.318907+00'); INSERT INTO sandbox VALUES (9, 'alpha', 'baz', 'quxx', '2010-12-29 16:54:38.727095+00'); INSERT INTO sandbox VALUES (10, 'alpha', 'bar', 'qux', '2010-12-29 16:54:46.237294+00'); INSERT INTO sandbox VALUES (11, 'alpha', 'baz', 'qux', '2010-12-29 16:54:53.891606+00'); INSERT INTO sandbox VALUES (12, 'alpha', 'baz', 'corge', '2010-12-29 16:55:39.596076+00'); INSERT INTO sandbox VALUES (13, 'alpha', 'baz', 'corge', '2010-12-29 16:55:44.834019+00'); INSERT INTO sandbox VALUES (14, 'alpha', 'foo', 'qux', '2010-12-29 16:55:52.848792+00'); ALTER TABLE ONLY sandbox ADD CONSTRAINT sandbox_pkey PRIMARY KEY (id); Here's the current SQL query I have: SELECT * FROM ( SELECT DISTINCT ON (this, that) id, this, that, timestamp FROM sandbox WHERE callsign = 'alpha' AND CAST(timestamp AS date) = '2010-12-29' ) playground ORDER BY timestamp DESC This is the result it gives me: id this that timestamp ----------------------------------------------------- 14 foo qux 2010-12-29 16:55:52.848792+00 13 baz corge 2010-12-29 16:55:44.834019+00 11 baz qux 2010-12-29 16:54:53.891606+00 10 bar qux 2010-12-29 16:54:46.237294+00 9 baz quxx 2010-12-29 16:54:38.727095+00 8 bar corge 2010-12-29 16:54:33.318907+00 7 foo corge 2010-12-29 16:53:21.242904+00 This is what I want to see: id this that timestamp count ------------------------------------------------------------- 14 foo qux 2010-12-29 16:55:52.848792+00 3 13 baz corge 2010-12-29 16:55:44.834019+00 2 11 baz qux 2010-12-29 16:54:53.891606+00 1 10 bar qux 2010-12-29 16:54:46.237294+00 1 9 baz quxx 2010-12-29 16:54:38.727095+00 1 8 bar corge 2010-12-29 16:54:33.318907+00 1 7 foo corge 2010-12-29 16:53:21.242904+00 1 EDIT: I'm using PostgreSQL 9.0.* (if that helps any).

    Read the article

  • Apache RewriteRule: it is possible to 'detect' the first and second parameter?

    - by DaNieL
    Im really really a newbie in regexp and i cant figure out how to do that. My goal is to have the RewriteRule to 'slice' the request url in 3 parts: example.com/foo #should return: index.php?a=foo&b=&c= example.com/foo/bar #should return: index.php?a=foo&b=bar&c= example.com/foo/bar/baz #should return: index.php?a=foo&b=bar&c=baz example.com/foo/bar/baz/bee #should return: index.php?a=foo&b=bar&c=baz/bee example.com/foo/bar/baz/bee/apple #should return: index.php?a=foo&b=bar&c=baz/bee/apple example.com/foo/bar/baz/bee/apple/and/whatever/else/no/limit/in/those/extra/parameters #should return: index.php?a=foo&b=bar&c=baz/bee/apple/and/whatever/else/no/limit/in/those/extra/parameters In short, the first parameter in the url (foo) should be given to a, the second (bar) to b, and the rest of the string in c I wroted this one <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !=/favicon.ico RewriteRule ^(([a-z0-9/]))?(([a-z0-9/]+))?(([a-z0-9]+))(.*)$ index.php?a=$1&b=$2&c=$3 [L,QSA] </IfModule> but obviously doesnt work, and i dont even know if what i want is possible. Any suggestion?

    Read the article

  • Apache RewriteRule: it is possible to 'detect' the first and second path segment?

    - by DaNieL
    Im really really a newbie in regexp and I can’t figure out how to do that. My goal is to have the RewriteRule to 'slice' the request URL path in 3 parts: example.com/foo #should return: index.php?a=foo&b=&c= example.com/foo/bar #should return: index.php?a=foo&b=bar&c= example.com/foo/bar/baz #should return: index.php?a=foo&b=bar&c=baz example.com/foo/bar/baz/bee #should return: index.php?a=foo&b=bar&c=baz/bee example.com/foo/bar/baz/bee/apple #should return: index.php?a=foo&b=bar&c=baz/bee/apple example.com/foo/bar/baz/bee/apple/and/whatever/else/no/limit/in/those/extra/parameters #should return: index.php?a=foo&b=bar&c=baz/bee/apple/and/whatever/else/no/limit/in/those/extra/parameters In short, the first segment in the URL path (foo) should be given to a, the second segment (bar) to b, and the rest of the string in c I wroted this one <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !=/favicon.ico RewriteRule ^(([a-z0-9/]))?(([a-z0-9/]+))?(([a-z0-9]+))(.*)$ index.php?a=$1&b=$2&c=$3 [L,QSA] </IfModule> But obviously doesn’t work, and I don’t even know if what I want is possible. Any suggestion? EDIT: After playing with coach manager, I got this one working too: RewriteRule ^([^/]*)?/?([^/]*)?/?(.*)?$ index.php?a=$1&b=$2&c=$3 [L,QSA]

    Read the article

  • How can I bind the same dependency to many dependents in Ninject?

    - by Mike Bantegui
    Let's I have three interfaces: IFoo, IBar, IBaz. I also have the classes Foo, Bar, and Baz that are the respective implementations. In the implementations, each depends on the interface IContainer. So for the Foo (and similarly for Bar and Baz) the implementation might read: class Foo : IFoo { private readonly IDependency Dependency; public Foo(IDependency dependency) { Dependency = dependency; } public void Execute() { Console.WriteLine("I'm using {0}", Dependency.Name); } } Let's furthermore say I have a class Container which happens to contain instances of the IFoo, IBar and IBaz: class Container : IContainer { private readonly IFoo _Foo; private readonly IBar _Bar; private readonly IBaz _Baz; public Container(IFoo foo, IBar bar, IBaz baz) { _Foo = foo; _Bar = bar; _Baz = baz; } } In this scenario, I would like the implementation class Container to bind against IContainer with the constraint that the IDependency that gets injected into IFoo, IBar, and IBaz be the same for all three. In the manual way, I might implement it as: IDependency dependency = new Dependency(); IFoo foo = new Foo(dependency); IBar bar = new Bar(dependency); IBaz baz = new Baz(dependency); IContainer container = new Container(foo, bar, baz); How can I achieve this within Ninject? Note: I am not asking how to do nested dependencies. My question is how I can guarantee that a given dependency is the same among a collection of objects within a materialized service. To be extremely explicit, I understand that Ninject in it's standard form will generate code that is equivalent to the following: IContainer container = new Container(new Foo(new Dependency()), new Bar(new Dependency()), new Baz(new Dependency())); I would not like that behavior.

    Read the article

  • How to handle Clean URIs in Classic ASP using PATH_INFO?

    - by Mario
    I'm trying to handle Clean URIs in a Classic ASP application. In PHP, I was able to use URIs like http://example.com/index.php/foo/bar/baz and have /foo/bar/baz available in the PATH_INFO environment variable. (I usually add a rewrite rule so I do not need the index.php segment) However, I don't seem to be able to mimic this in Classic ASP. If I try http://example.com/index.asp/foo/bar/baz, I get a 404 error. Is there a way to add a path after the index.asp segment and get the PHP like behaviour in ASP? Note: I'm currently using the workaround of rewriting URLs of the form: http://example.com/foo/bar/baz/ to index.asp?path=/foo/bar/baz since I can't seem to get index.asp/foo/bar/baz to work.

    Read the article

  • PHP5: restrict access to function to certain classes

    - by Tim
    Is there a way in PHP5 to only allow a certain class or set of classes to call a particular function? For example, let's say I have three classes ("Foo", "Bar", and "Baz"), all with similarly-named methods, and I want Bar to be able to call Foo::foo() but deny Baz the ability to make that call: class Foo { static function foo() { print "foo"; } } class Bar { static function bar() { Foo::foo(); print "bar"; } // Should work } class Baz { static function baz() { Foo::foo; print "baz"; } // Should fail } Foo::foo(); // Should also fail There's not necessarily inheritance between Foo, Bar, and Baz, so the use of protected or similar modifiers won't help; however, the methods aren't necessarily static (I made them so here for the simplicity of the example).

    Read the article

  • Switch or a Dictionary when assigning to new object

    - by KChaloux
    Recently, I've come to prefer mapping 1-1 relationships using Dictionaries instead of Switch statements. I find it to be a little faster to write and easier to mentally process. Unfortunately, when mapping to a new instance of an object, I don't want to define it like this: var fooDict = new Dictionary<int, IBigObject>() { { 0, new Foo() }, // Creates an instance of Foo { 1, new Bar() }, // Creates an instance of Bar { 2, new Baz() } // Creates an instance of Baz } var quux = fooDict[0]; // quux references Foo Given that construct, I've wasted CPU cycles and memory creating 3 objects, doing whatever their constructors might contain, and only ended up using one of them. I also believe that mapping other objects to fooDict[0] in this case will cause them to reference the same thing, rather than creating a new instance of Foo as intended. A solution would be to use a lambda instead: var fooDict = new Dictionary<int, Func<IBigObject>>() { { 0, () => new Foo() }, // Returns a new instance of Foo when invoked { 1, () => new Bar() }, // Ditto Bar { 2, () => new Baz() } // Ditto Baz } var quux = fooDict[0](); // equivalent to saying 'var quux = new Foo();' Is this getting to a point where it's too confusing? It's easy to miss that () on the end. Or is mapping to a function/expression a fairly common practice? The alternative would be to use a switch: IBigObject quux; switch(someInt) { case 0: quux = new Foo(); break; case 1: quux = new Bar(); break; case 2: quux = new Baz(); break; } Which invocation is more acceptable? Dictionary, for faster lookups and fewer keywords (case and break) Switch: More commonly found in code, doesn't require the use of a Func< object for indirection.

    Read the article

  • SML/NJ incomplete match

    - by dimvar
    I wonder how people handle nonexhaustive match warnings in the SML/NJ compiler. For example, I may define a datatype datatype DT = FOO of int | BAR of string and then have a function that I know only takes FOOs fun baz (FOO n) = n + 1 The compiler will give a warning stdIn:1.5-1.24 Warning: match nonexhaustive FOO n = ... val baz = fn : DT - int I don't wanna see warnings for incomplete matches I did on purpose, because then I have to scan through the output to find a warning that might actually be a bug. I can write the function like this fun baz (FOO n) = n + 1 | baz _ = raise Fail "baz" but this clutters the code. What do people usually do in this situation?

    Read the article

  • Flatten a PHP array

    - by deadkarma
    Say I have a form with these fields, and cannot rename them: <input type="text" name="foo[bar]" /> <input type="text" name="foo[baz]" /> <input type="text" name="foo[bat][faz]" /> When submitted, PHP turns this into an array: Array ( [foo] => Array ( [bar] => foo bar [baz] => foo baz [bat] => Array ( [faz] => foo bat faz ) ) ) What methods are there to convert or flatten this array into a data structure such as: Array ( [foo[bar]] => foo bar [foo[baz]] => foo baz [foo[bat][faz]] => foo bat faz )

    Read the article

  • Solr dataimport skips entities in my data-config.xml

    - by lerhaupt
    My data-config.xml defines 3 different entities under the document tag (lets call them foo, bar and baz). When I issue a basic full import localhost:8983/solr/dataimport?command=full-import, only 2 of the 3 entities get indexed (foo and bar are in my index but baz never makes it). However, if I then issue a command to just import baz via localhost:8983/solr/dataimport?command=full-import&entity=baz&clean=false it adds baz documents just fine and the index then has all 3 types. Does anyone have any thoughts on why one entity gets skipped in the general data import but then still works okay if I specifically call it out? Is there an error/warning log I can check? Nothing bad shows up in /solr/logs/ but those just appear to be request logs.

    Read the article

  • In Spring MVC (2.0) how can you easily hook multiple pages/urls to use 1 controller?

    - by danny
    <!--dispatcher file--> <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/foo/bar/baz/boz_a.html">bozController</prop> </props> </property> </bean> <!--mappings file--> <bean id="bozController" class="com.mycompany.foo.bar.baz.BozController"> <property name="viewPathA" value="foo/bar/baz/boz_a" /> <property name="viewPathB" value="foo/bar/baz/boz_b" /> ... <property name="viewPathZ" value="foo/bar/baz/boz_z" /> </bean> how do I set it up so that when the user loads page boz_w.html it uses the bozController, and sets the viewPath to use boz_w.jsp?

    Read the article

  • Can AutoMapper create a map for an interface and then map with a derived type?

    - by TheCloudlessSky
    I have an interface IFoo: public interface IFoo { int Id { get; set; } } And then a concrete implementation: public class Bar : IFoo { public int Id { get; set; } public string A { get; set; } } public class Baz : IFoo { public int Id { get; set; } public string B { get; set; } } I'd like to be able to map all IFoo but specifying their derived type instead: Mapper.CreateMap<int, IFoo>().AfterMap((id, foo) => foo.Id = id); And then map (without explicitly creating maps for Bar and Baz): var bar = Mapper.Map<int, Bar>(123); // bar.Id == 123 var baz = Mapper.Map<int, Baz>(456); // baz.Id == 456 But this doesn't work in 1.1. I know I could specify all Bar and Baz but if there are 20 of these, I'd like to not have to manage them and rather just have what I did above for creating the map. Is this possible?

    Read the article

  • JAXB doesn't unmarshal list of interfaces

    - by Joker_vD
    It seems JAXB can't read what it writes. Consider the following code: interface IFoo { void jump(); } @XmlRootElement class Bar implements IFoo { @XmlElement public String y; public Bar() { y = ""; } public Bar(String y) { this.y = y; } @Override public void jump() { System.out.println(y); } } @XmlRootElement class Baz implements IFoo { @XmlElement public int x; public Baz() { x = 0; } public Baz(int x) { this.x = x; } @Override public void jump() { System.out.println(x); } } @XmlRootElement public class Holder { private List<IFoo> things; public Holder() { things = new ArrayList<>(); } @XmlElementWrapper @XmlAnyElement public List<IFoo> getThings() { return things; } public void addThing(IFoo thing) { things.add(thing); } } // ... try { JAXBContext context = JAXBContext.newInstance(Holder.class, Bar.class, Baz.class); Holder holder = new Holder(); holder.addThing(new Bar("1")); holder.addThing(new Baz(2)); holder.addThing(new Baz(3)); for (IFoo thing : holder.getThings()) { thing.jump(); } StringWriter s = new StringWriter(); context.createMarshaller().marshal(holder, s); String data = s.toString(); System.out.println(data); StringReader t = new StringReader(data); Holder holder2 = (Holder)context.createUnmarshaller().unmarshal(t); for (IFoo thing : holder2.getThings()) { thing.jump(); } } catch (Exception e) { System.err.println(e.getMessage()); } It's a simplified example, of course. The point is that I have to store two very differently implemented classes, Bar and Baz, in one collection. Well, I observed that they have pretty similar public interface, so I created an interface IFoo and made them two to implement it. Now, I want to have tools to save and load this collection to/from XML. Unfortunately, this code doesn't quite work: the collection is saved, but then it cannot be loaded! The intended output is 1 2 3 some xml 1 2 3 But unfortunately, the actual output is 1 2 3 some xml com.sun.org.apache.xerces.internal.dom.ElementNSImpl cannot be cast to testapplication1.IFoo Apparently, I need to use the annotations in a different way? Or to give up on JAXB and look for something else? I, well, can write "XMLNode toXML()" method for all classes I wan't to (de)marshal, but...

    Read the article

  • Templated derived class in CRTP (Curiously Recurring Template Pattern)

    - by Butterwaffle
    Hi, I have a use of the CRTP that doesn't compile with g++ 4.2.1, perhaps because the derived class is itself a template? Does anyone know why this doesn't work or, better yet, how to make it work? Sample code and the compiler error are below. Source: foo.C #include <iostream> using namespace std; template<typename X, typename D> struct foo; template<typename X> struct bar : foo<X,bar<X> > { X evaluate() { return static_cast<X>( 5.3 ); } }; template<typename X> struct baz : foo<X,baz<X> > { X evaluate() { return static_cast<X>( "elk" ); } }; template<typename X, typename D> struct foo : D { X operator() () { return static_cast<D*>(this)->evaluate(); } }; template<typename X, typename D> void print_foo( foo<X,D> xyzzx ) { cout << "Foo is " << xyzzx() << "\n"; } int main() { bar<double> br; baz<const char*> bz; print_foo( br ); print_foo( bz ); return 0; } Compiler errors foo.C: In instantiation of ‘foo<double, bar<double> >’: foo.C:8: instantiated from ‘bar<double>’ foo.C:30: instantiated from here foo.C:18: error: invalid use of incomplete type ‘struct bar<double>’ foo.C:8: error: declaration of ‘struct bar<double>’ foo.C: In instantiation of ‘foo<const char*, baz<const char*> >’: foo.C:13: instantiated from ‘baz<const char*>’ foo.C:31: instantiated from here foo.C:18: error: invalid use of incomplete type ‘struct baz<const char*>’ foo.C:13: error: declaration of ‘struct baz<const char*>’

    Read the article

  • Change directory upwards to specified goal

    - by haakon
    I'm often deep inside a directory tree, moving upwards and downwards to perform various tasks. Is there anything more efficient than going 'cd ../../../..'? I was thinking something along the lines of this: If I'm in /foo/bar/baz/qux/quux/corge/grault and want to go to /foo/bar/baz, I want to do something like 'cdto baz'. I can write some bash script for this, but I'd first like to know if it already exists in some form.

    Read the article

  • Assignments in mock return values

    - by zerkms
    (I will show examples using php and phpunit but this may be applied to any programming language) The case: let's say we have a method A::foo that delegates some work to class M and returns the value as-is. Which of these solutions would you choose: $mock = $this->getMock('M'); $mock->expects($this->once()) ->method('bar') ->will($this->returnValue('baz')); $obj = new A($mock); $this->assertEquals('baz', $obj->foo()); or $mock = $this->getMock('M'); $mock->expects($this->once()) ->method('bar') ->will($this->returnValue($result = 'baz')); $obj = new A($mock); $this->assertEquals($result, $obj->foo()); or $result = 'baz'; $mock = $this->getMock('M'); $mock->expects($this->once()) ->method('bar') ->will($this->returnValue($result)); $obj = new A($mock); $this->assertEquals($result, $obj->foo()); Personally I always follow the 2nd solution, but just 10 minutes ago I had a conversation with couple of developers who said that it is "too tricky" and chose 3rd or 1st. So what would you usually do? And do you have any conventions to follow in such cases?

    Read the article

  • What is the right way to initialize a constant in Ruby?

    - by zbrimhall
    I have a simple class that defines some constants, e.g.: module Foo class Bar BAZ = "bof" ... Everything is puppies and rainbows until I tell Rake to run all my Test::Unit tests. When it does, I get warnings: bar.rb:3: warning: already initialized constant BAZ My habit has been to avoid these warnings by making the constant initialization conditional, e.g.: ... BAZ = "bof" unless const_defined? :BAZ ... This seems to solve the problem, but it is a little tedious, and I don't ever see anyone else initializing constants this way. This makes me think I might be Doing It Wrong. Is there a better way to initialize constants that won't generate warnings?

    Read the article

  • Python hashable dicts

    - by TokenMacGuy
    As an exercise, and mostly for my own amusement, I'm implementing a backtracking packrat parser. The inspiration for this is i'd like to have a better idea about how hygenic macros would work in an algol-like language (as apposed to the syntax free lisp dialects you normally find them in). Because of this, different passes through the input might see different grammars, so cached parse results are invalid, unless I also store the current version of the grammar along with the cached parse results. (EDIT: a consequence of this use of key-value collections is that they should be immutable, but I don't intend to expose the interface to allow them to be changed, so either mutable or immutable collections are fine) The problem is that python dicts cannot appear as keys to other dicts. Even using a tuple (as I'd be doing anyways) doesn't help. >>> cache = {} >>> rule = {"foo":"bar"} >>> cache[(rule, "baz")] = "quux" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'dict' >>> I guess it has to be tuples all the way down. Now the python standard library provides approximately what i'd need, collections.namedtuple has a very different syntax, but can be used as a key. continuing from above session: >>> from collections import namedtuple >>> Rule = namedtuple("Rule",rule.keys()) >>> cache[(Rule(**rule), "baz")] = "quux" >>> cache {(Rule(foo='bar'), 'baz'): 'quux'} Ok. But I have to make a class for each possible combination of keys in the rule I would want to use, which isn't so bad, because each parse rule knows exactly what parameters it uses, so that class can be defined at the same time as the function that parses the rule. But combining the rules together is much more dynamic. In particular, I'd like a simple way to have rules override other rules, but collections.namedtuple has no analogue to dict.update(). Edit: An additional problem with namedtuples is that they are strictly positional. Two tuples that look like they should be different can in fact be the same: >>> you = namedtuple("foo",["bar","baz"]) >>> me = namedtuple("foo",["bar","quux"]) >>> you(bar=1,baz=2) == me(bar=1,quux=2) True >>> bob = namedtuple("foo",["baz","bar"]) >>> you(bar=1,baz=2) == bob(bar=1,baz=2) False tl'dr: How do I get dicts that can be used as keys to other dicts? Having hacked a bit on the answers, here's the more complete solution I'm using. Note that this does a bit extra work to make the resulting dicts vaguely immutable for practical purposes. Of course it's still quite easy to hack around it by calling dict.__setitem__(instance, key, value) but we're all adults here. class hashdict(dict): """ hashable dict implementation, suitable for use as a key into other dicts. >>> h1 = hashdict({"apples": 1, "bananas":2}) >>> h2 = hashdict({"bananas": 3, "mangoes": 5}) >>> h1+h2 hashdict(apples=1, bananas=3, mangoes=5) >>> d1 = {} >>> d1[h1] = "salad" >>> d1[h1] 'salad' >>> d1[h2] Traceback (most recent call last): ... KeyError: hashdict(bananas=3, mangoes=5) based on answers from http://stackoverflow.com/questions/1151658/python-hashable-dicts """ def __key(self): return tuple(sorted(self.items())) def __repr__(self): return "{0}({1})".format(self.__class__.__name__, ", ".join("{0}={1}".format( str(i[0]),repr(i[1])) for i in self.__key())) def __hash__(self): return hash(self.__key()) def __setitem__(self, key, value): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def __delitem__(self, key): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def clear(self): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def pop(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def popitem(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def setdefault(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def update(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def __add__(self, right): result = hashdict(self) dict.update(result, right) return result if __name__ == "__main__": import doctest doctest.testmod()

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >