Friday, April 29, 2011

What is the proper "Rails Way" to consume a RESTful web service on another domain?

I would like to write a Ruby on Rails application that consumes a RESTful web service API performs some logic on the result and then displays that data on my view. For example, let's say I wanted to write a program that did a search on search.twitter.com. Using pure ruby I might create the following method:

def run(search_term='', last_id=0)
  @results = []
  url = URI.parse("http://search.twitter.com")
  res = Net::HTTP.start(url.host, url.port) do |http|
    http.get("/search.json?q=#{search_term}&since_id=#{last_id.to_s}")
  end
  @results = JSON.parse res.body
end

I'm tempted to just drop that method into my Rails controller as a private method, but part of me thinks that there is a better, more "Rails" way to do this. Is there a best practice approach or is this really the best way?

From stackoverflow
  • Hi Mike, if the remote RESTful web service was also created with Ruby on Rails, ActiveResource is the way to go.

    Mike Farmer : I can't make that assumption as I would like to pull data from many different web sites wherein I would have no idea what the underlying framework would be. But I'll look at ActiveResource for the things I know are Rails. Thanks!
  • In response to your Twitter example, there is a Twitter Gem that would help to automate this for you.

  • There is a plugin/gem called HTTParty that I've used for several projects.

    http://httparty.rubyforge.org/

    HTTParty lets you easily consume any web service and parses results into a hash for you. Then you can use the hash itself or instantiate one or more model instances with the results. I've done it both ways.

    For the twitter example, your code would look like this:

    class Twitter
      include HTTParty
      base_uri 'twitter.com'
    
      def initialize(u, p)
        @auth = {:username => u, :password => p}
      end
    
      # which can be :friends, :user or :public
      # options[:query] can be things like since, since_id, count, etc.
      def timeline(which=:friends, options={})
        options.merge!({:basic_auth => @auth})
        self.class.get("/statuses/#{which}_timeline.json", options)
      end
    
      def post(text)
        options = { :query => {:status => text}, :basic_auth => @auth }
        self.class.post('/statuses/update.json', options)
      end
    end
    
    # usage examples.
    twitter = Twitter.new('username', 'password')
    twitter.post("It's an HTTParty and everyone is invited!")
    twitter.timeline(:friends, :query => {:since_id => 868482746})
    twitter.timeline(:friends, :query => 'since_id=868482746')
    

    As a last point, you could use your code above also, but definitely include the code in a model as opposed to a controller.

    Mike Farmer : I love this gem. This makes consuming web services really slick. A question I still have though is whether Rails has something built in already to do this? Seems like this is a common enough thing to try to do that they would have a way to do it.
    Mike Farmer : Also, forgive my Rails noobieness :) , how would I set that up in as a model. I have only used models for database access using ActiveRecord.
    Kyle Boon : There isn't anything built in to rails core. A model is a just a class - just create a class in the models directory and don't inherit from the ActiveRecord:Base class. You won't have any of the AR goodness included, but this is a pretty common pattern for consuming web services within a rails app
    Mike Farmer : Thanks! I'll give it a try. I appreciate the help.
    Angela : Mike, did you settle on HttpParty and are you using it to do POST's to non-rest HTTP web services? I am using rest-client, not sure if it's working right though so wanted you take?

Flex: cross-domain image loading?

OK I have an application that loads product images using the < mx:Image /> tag and changing the source. the .SWF is on the http side of the website and the images are on the https side of the site. so at first I was getting this error:

SecurityError: Error #2122: Security sandbox violation: Loader.content: http://www.MYDOMAIN.com/Masonic.swf cannot access https://www.MYDOMAIN.com/masonic_images/13_red_d2-MAS72479bl_red.jpg. A policy file is required, but the checkPolicyFile flag was not set when this media was loaded. at flash.display::Loader/get content() at SmoothImage/http://www.adobe.com/2006/flex/mx/internal::contentLoaderInfo_completeEventHandl er()

So after some research I found this article: http://www.damienking.net/tutorial-using-remotely-hosted-images-flex I did what it said and I am now getting this similar error:

SecurityError: Error #2123: Security sandbox violation: Loader.content: http://www.MYDOMAIN.com/Masonic.swf cannot access https://www.MYDOMAIN.com/masonic_images/12_red_d2-MAS60338bl_red.jpg. No policy files granted access. at flash.display::Loader/get content() at SmoothImage/http://www.adobe.com/2006/flex/mx/internal::contentLoaderInfo_completeEventHandl er()

Also after I click dismiss to the error box that pops up, the images do load afterwards, but are then set to the size of the actual image not the width and height I set the component to. I have no clue what to make of that.

Any help is appreciated.

THANKS!

From stackoverflow

Thursday, April 28, 2011

Load a ResourceDictionary from an assembly

I've got an assembly somewhere on the file system, e.g. "C:\temp\test.dll". In that assembly there's a ResourceDictionary, e.g. "abc.xaml".

How can i get that ResourceDictionary? Maybe there is a way using Reflections? I didn't find a solution so far.

Thanks in advance!

Edit: Just wanted to add that I want to access the Resources in the Dictionary, e.g. a Style.

From stackoverflow
  • Grab a copy of Reflector (Lutz has handed this over now). Use that to look at the assembly and the namespace etc of the resources in it.

    Then read in the embedded resource something like this;

    Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
    using (System.IO.Stream s = asm.GetManifestResourceStream(<yourname>)
    {
        using (System.IO.StreamReader reader = new System.IO.StreamReader(s))
        {
            string xml = reader.ReadToEnd();
        }
    }
    
    Christian Hubmann : Thank you. Unfortunatly, when I use your code, I'm just getting garbage from reader.ReadToEnd()
    Dead account : I've no idea what XAML looks like, but I guess you need a decoder of some sort?
    Christian Hubmann : I don't know, but I did it now with resource files. Thanks for your help!
    Simon_Weaver : @christian - the garbage is BAML not XAML : http://blogs.microsoft.co.il/blogs/tomershamam/archive/2007/05/25/Compiled-XAML-_3D00_-BAML-not-IL.aspx
  • Edit: I found an even better solution which works with ResourceDictionaries:

    Assembly.LoadFrom(@"C:\temp\test.dll");
    ResourceDictionary rd = new ResourceDictionary();
    rd.Source = new Uri("/test;component/myresource.xaml");
    


    Well, I couldn't get it to work with ResourceDictionaries, so I'm using good old Resource Files instead ;) For anyone interested, here is how I did it:

    Assembly a = Assembly.LoadFile(@"C:\temp\test.dll");
    ResourceManager rm = new ResourceManager("NameOfResource", a);
    object o = rm.GetObject("xyz");
    

    You can get "NameOfResource" with Reflector, as Ian suggested.

    Dead account : +1 always good to come back and tell us how you got on with your problem :)
    Scott Bilas : See Claraoscura's answer, it is a better solution.
  • You actually need to write the Uri like this:

    Assembly.LoadFrom(@"C:\temp\test.dll");
    ResourceDictionary rd = new ResourceDictionary();
    rd.Source = new Uri(@"pack://application:,,,/test;component/myresource.xaml");
    
    Scott Bilas : Documentation for the goofy Uri syntax is here: http://msdn.microsoft.com/en-us/library/aa970069.aspx

How can I transform an element attribute to an element name in XSLT?

I'd link to transform XML with attributes like the 'name' attribute in the following:

<books>
  <book name="TheBumperBookOfXMLProgramming"/>
  <book name="XsltForDummies"/>
</books>

into elements called what was in the name attribute:

<books>
  <TheBumperBookOfXMLProgramming/>
  <XsltForDummies/>
</books>

using XSLT. Any ideas?

From stackoverflow
  • You can create elements by name using xsl:element:

    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet 
         version="1.0" 
         xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="xml" indent="yes"/>
    
      <xsl:template match="/">
        <books>
          <xsl:apply-templates />
        </books>
    
      </xsl:template>
    
      <xsl:template match="book">
        <xsl:element name="{@name}" />
      </xsl:template>
    
    </xsl:stylesheet>
    
    pc1oad1etter : This leaves open the possibility of creating invalid xml (read: not xml) because the character set is more restricted with element names.
    0xA3 : @pc1oad1etter: How is it more restricted? As far as I know both are names according to this [production rule](http://www.w3.org/TR/REC-xml/#NT-Name)
  • <xsl:template match="book">
       <xsl:element name="{@name}">
           <xsl:copy-of select="@*[name()!='name'] />
       </xsl:element>
    </xsl:template>
    

    this also copies over any properties on <book> not named 'name'

    <book name="XsltForDummies" id="12" />
    

    will turn into

    <XsltForDummies id="12 />
    

Get records ordered alphabetically starting by a certain letter in Sql Server

In SQLSERVER/MSSQL, here's the problem:

SELECT * from [Translation Color] order by [Language Code]

I want records ordered in alphabetical order starting by the 'I' letter.

Example of result:

'Ioren' 'Iumen' 'Tart' 'Arfen' 'Coldry'

I don't want to use union or more sql statements.. just try to catch it with an order by special clause.

I've tried with:

ORDER BY <field> REGEXP '^I' DESC

but it didn't work.

Any ideas?

From stackoverflow
  • This should do it:

    ORDER BY CASE WHEN SUBSTRING([Translation Color],1,1) = 'l' 
         THEN 1 ELSE 0 END DESC
    

    EDIT:

    Full answer for ordering completely starting at i, then looping back round to h is:

    ORDER BY CASE WHEN ASCII(UPPER(SUBSTRING([Translation Color],1,1))) < 73 
             THEN ASCII(UPPER(SUBSTRING([Translation Color],1,1))) + 26
             ELSE ASCII(UPPER(SUBSTRING([Translation Color],1,1))) END ASC,       
             [Translation Color] ASC
    

    Please note that this will affect performance on large tables.

    avastreg : == gives error, but with one = it works! thank you
    Neil Barnwell : Remember to check the performance is acceptable though, especially if you have or are likely to have a large dataset.
    ck : Yeah sorry about that, am coding in C# at the mo, but I've edited it to be right.
    Neil Barnwell : BTW - very clever solution - trés bien!
    Dog Ears : Does it actually work?
    ck : @Dog Ears: See [== gives error, but with one = it works! thank you – avastreg (49 mins ago)]
    Dog Ears : I'm missing the point but don't you want the data to order like this.. l m n o....g h i j k Does the selected answer do that?
    LukeH : @Dog Ears, You are correct. The OP suggests that they need the ordering I-ZA-H. ck's answer doesn't deliver this, your answer and mine do. Note though that it's an I (i), not an l (L).
    ck : @Dog Ears, Luke: Answer updated with full answer
    avastreg : good work guys! :)
  • Alternatively is this any good:

    select [Translation Color], 
      case when [Translation Color] < 'l' then 1
                         else 0 
                         end as Priority
    from t1 
    order by Priority, [Translation Color]
    

    This will order it alphabeticly starting at 'l'

    Edit This solution seems to work for me:

    create table t1 ( c1 varchar(20) collate SQL_Latin1_General_Cp437_CI_AS)
    

    then i populated with some test data then run this:

    select c1 
    from t1 
    order by case when c1 >= 'l' then 0 else 1 end, c1
    
    ck : +1: nice answer, very clean, but does use separate element in select statement
    Dog Ears : My edit works perfectly but doesn't uses the order by clause.
    Dog Ears : ... *now* uses (not doesn't) the order by clause!
  • SELECT *
    FROM [Translation Color]
    ORDER BY
        CASE WHEN [Language Code] LIKE '[I-Zi-z]%' THEN 0 ELSE 1 END,
        [Language Code]
    
    ck : +1: Nice answer, but LIKE clause could be quite slow on large data sets, but possible not as slow as mine :) (however I assume this is a small lookup table)
    LukeH : @ck, The LIKE isn't ideal, but it should still be able to use any index on the [Language Code] column. I suspect that using SUBSTRING, ASCII, UPPER etc would necessitate a table scan.
    LukeH : @ck, I agree that it's most likely a small lookup table. However, even if every drop of performance isn't vital, I think that my answer is more readable than all those string functions.
    ck : You answer is indeed more readable. I like the fact there are three different answers to this question.
    Dog Ears : I like this answer as I imagine it's more tolerant of different collations.

Calculating volumes of hollow three dimensional geometric objects

We've gotten a homework assignment in Java, which relates to inheritance. I don't have a problem with the programming in itself, but I'm a bit unsure about some of the math, and would like confirmation/corrections from someone a bit more knowledgable.

The assignment starts with a abstract class, GeometricObject, which is extended into three two-dimensional objects. A rectangle, a circle and a triangle. Those three are then extended into a cuboid for the rectangle, a cylinder and a sphere for the circle, and the triangle into a triangular prism.

Each of these three-dimensional objects are hollow, and has a defined thickness and is made of a special metal, so we are to calculate their weight. And herein lies the problem, since I'm a bit unsure as to how I find the "inner volume" on some of them.

  • Cuboid: Here I assume that I can just subtract 2 * thickness from the width, height and depth, and then everything looks fine.
  • Cylinder: Subtract thickness from the radius making up the base, and 2*thickness from the height
  • Sphere: Subtract thickness from the radius
  • Prism: This is where I'm a bit stuck. Each object gets passed a baseline, height of the triangle, and the height for the entire prism. How can I use this in order to find the "inner prism" representing the inner volume?

Update: Forgot to mention that when creating the object, we specify the outmost sizes, and the hollow part is inside of this. The other way around is not allowed.

Update again: The triangle is an isosceles triangle.

Update yet again: Mixed up radius and diameter for the circular. Corrected now.

From stackoverflow
  • Get the volume of the shapes as if they were not hollow, then, get the volume of the hollow are only (Shape - Thickness)

    subtract full volume from hollow volume to get the actual volume of the metal.

    Example:

    Cube:

    Full Volume: Height * Width * Depth
    
    hollow volume: (Height - Thickness) * ( Width - Thickness ) * ( Depth - Thickness)
    
    Volume of the metal used: Full Volume - hollow Volume
    

    Work out the weight from the volume of the metal used..


    Assuming your prism is triangular and the triangle is equilateral that the base line is the base of the triangle and the height is from the baseline to the opposite point (and the height line is at an right angle from the baseline).

    Then the full volume would be

    fv = (1/2 * baseLine * triangleHeight) * prismHeight
    

    the hollow volume would be

    hv = (1/2 * (baseline - thickness) * (triangleHeight - thickness)) * (prismHeight - thickness)
    


    After reading you comment to jpaleck, it would seem your baseline is the Hypotenuse of the triangle, (the longest line), the above should still hold true with that.


    Sekhat : Assuming your prism is triangular and the triangle is equilateral. Then the full volume would be fv = (1/2 * baseLine * triangleHeight) * prismHeight, the hollow volume would be (1/2 * (baseline - thickness) * (triangleHeight - thickness) * prismHeight
    Sekhat : you may have to multiple thickness by two so that you account for the changes of the line lengths on each side. As a thickness of 10, when drawing a shape shortened by 10 in each dimension actually only gives a metal thickness of 5 all the way around.
    AnthonyWJones : @Killersponge: If the triangles were equilateral there would be no need to include the height of the prism as the question indicates.
    Sekhat : Indeed. Though the above formula is sound anyway, Assuming the baseline is one side of the triangle and the triangle height is from the center of that line to the point opposite it.
    Sekhat : I've edited this answer alot now, but that should be it :)
    AnthonyWJones : I'm no maths wiz but I'm fairly sure you can't calculate the inner baseline so simplistically. Each corner is a three-way mitre, the specified height will modify the available inner baseline. Imagine if the height of the prism in total is only 3 * thickness, what would the inner volume look like?
    Sekhat : a very small prism
    Sekhat : you don't need to calculate the sides if it's just the volume, all you want is the area of the triangle (which is half the area of the tightest rectangle you can fit round) times it's overall height then shrink the values your using. Read my answer again plus the comment about multiplying thickness
    jpalecek : The problem with your approach is that when you put metal of thickness h inside the triangle, the tightest rectangle holding the triangle will not have sides smaller by h, but by more than 2*h.
    Sekhat : @jpalecek hence comment further up
  • I think you cannot get this result from the data you have (baseline length & triangle height). You have to get other information, like location of the points or the angles at the baseline.

    Edit: since the triangle is isosceles:

    As AnthonyWJones already pointed out, the inner triangle is similar to the outer triangle. Therefore, the only thing you need is find the ratio between the two.

    sketch

    You can find it easily from the height. Since triangles CQP and ACS are similar

    h2 : |PQ| = |AC| : |AS|
    

    where

    |PQ| = h1 (= the thickness of the metal)
    |AC| = sqrt(base^2/4+height^2)
    |AS| = base/2
    

    Then, you compute h2 and the ratio r = (height - h1 - h2)/height is the ratio between the two triangles. The area of the inner triangle is then r^2 * area of the outer triangle.

    AnthonyWJones : +1. Nice illustration, better reasoning ;)
  • One thing you know about the inner prism is that it will have the same ratios as the outer prism. In other words given the height of the inner prism you can calculate the inner base length and from there the volume.

    You know the base will have 1 unit thickness. So that leaves calculating the distance from the pinnacle of the inner prism to the pinnacle of the outer prism.

    That distance is the hypontenuse of a right angled triangle. The angles in the triangle are known since they are function of the base length and height. One side of the triangle is of thickness length being the perpendicular from the inner edge at the inner pinnacle to the outer edge. (The final side of the triangle is where that perpendicular intersects the outer edge up to the outer pinnacle).

    This is enough info to use standard trig to caclulate the hypotenuse length. This length plus 1 thickness (for the base) subtracted from the original height gives you the inner height. The ratio between the inner and outer heights can be applied to the base length.

    There a probably cleverer ways to do this but this would be my common bloke approach.

How to search for one value in any column of any table inside one MS-SQL database?

Is there a way to search for one value (in my case it is a UID of the type char(64)) inside any column of any table inside one MS-SQL database?

I'm sitting in front of a huge database without any idea how the tables had to be linked together. To find that out I'd like to list all tables and there columns that contain a certain value in any row. Is that possible?

One way could be to just dump the entire database into a text file and than use any text-editor to search for the value - but this would be pure pain if the database is too huge.

From stackoverflow
  • Thanks for the question as this is a really useful topic. I will use this myself also now for reasons including the one you put forward. :-)

    How to search all columns of all tables in a database for a keyword?

    http://vyaskn.tripod.com/search_all_columns_in_all_tables.htm

    Andrew

    MrTelly : That is an awesome bit of Sql, thanks for finding it for us