EzDevInfo.com

block interview questions

Top block frequently asked interview questions

Rails render partial with block

I'm trying to re-use an html component that i've written that provides panel styling. Something like:

  <div class="v-panel">
    <div class="v-panel-tr"></div>
    <h3>Some Title</h3>
    <div class="v-panel-c">
      .. content goes here
    </div>
    <div class="v-panel-b"><div class="v-panel-br"></div><div class="v-panel-bl"></div></div>
  </div>

So I see that render takes a block. I figured then I could do something like this:

# /shared/_panel.html.erb
<div class="v-panel">
  <div class="v-panel-tr"></div>
  <h3><%= title %></h3>
  <div class="v-panel-c">
    <%= yield %>
  </div>
  <div class="v-panel-b"><div class="v-panel-br"></div><div class="v-panel-bl"></div></div>
</div>

And I want to do something like:

#some html view
<%= render :partial => '/shared/panel', :locals =>{:title => "Some Title"} do %>
  <p>Here is some content to be rendered inside the panel</p>
<% end %>

Unfortunately this doesn't work with this error:

ActionView::TemplateError (/Users/bradrobertson/Repos/VeloUltralite/source/trunk/app/views/sessions/new.html.erb:1: , unexpected tRPAREN

old_output_buffer = output_buffer;;@output_buffer = '';  __in_erb_template=true ; @output_buffer.concat(( render :partial => '/shared/panel', :locals => {:title => "Welcome"} do ).to_s)
on line #1 of app/views/sessions/new.html.erb:
1: <%= render :partial => '/shared/panel', :locals => {:title => "Welcome"} do -%>
...

So it doesn't like the = obviously with a block, but if I remove it, then it just doesn't output anything.

Does anyone know how to do what I'm trying to achieve here? I'd like to re-use this panel html in many places on my site.


Source: (StackOverflow)

How to use nonnull and nullable Objective-C keywords in block-based API method

Consider the following method

- (void)methodWithArg:(NSString *)arg1 andArg:(NSString *)arg2 completionHandler:(void (^)(NSArray *results, NSError *error))completionHandler;

With the new nonnull and nullable annotation keywords we can enrich it as follows:

- (void)methodWithArg:(nonnull NSString *)arg1 andArg:(nullable NSString *)arg2 completionHandler:(void (^)(NSArray *results, NSError *error))completionHandler;

but we also get this warning:

Pointer is missing a nullability type specifier (__nonnull or __nullable)

It refers to the third parameter (the block one).

The documentation doesn't cover with examples how to specify the nullability of block parameters. It states verbatim

You can use the non-underscored forms nullable and nonnull immediately after an open parenthesis, as long as the type is a simple object or block pointer.

I tried putting one of the two keywords for the block (in any position) without any luck. Also tried the underscore prefixed variants (__nonnull and __nullable).

Therefore my question is: how can I specify the nullability semantic for block parameters?


Source: (StackOverflow)

Advertisements

Display block without 100% width

I want to set a span element to appear below another element using the display property. I tried applying inline-block but without success, and figured I could use block if I somehow managed to avoid giving the element a width of 100% (I don't want the element to "stretch out"). Can this be done, or if not, what's good praxis for solving this kind of issue?

Example: a news list where I want to set a "read more" link at the end of each post (note: <a> instead of <span>)

<li>
<span class="date">11/15/2012</span>
<span class="title">Lorem ipsum dolor</span>
<a class="read-more">Read more</a> 
</li>


Update: Solved. In CSS, apply

li {
    clear: both;
}
li a {
    display: block;
    float: left;
    clear: both;
}

Source: (StackOverflow)

optional closure and check if it is nil

So what I want to have is a class that may get a closure passed to it in a function, it may also at some point want to disregard a that closure. How can I check if the closure variable is set and hwo can I delete it when I am done with it?

Cannot invoke '!=' with an argument list of type '(@lvalue (sucsess: Bool!, products: [AnyObject]!) -> ()?, NilLiteralConvertible)' Type '(sucsess: Bool!, products: [AnyObject]!) -> ()?' does not conform to protocol 'NilLiteralConvertible'

class someClass{
    //typealias completionHandlerClosureType = (sucsess:Bool!, items:[AnyObject]!)->()
    var completionHandler:(sucsess:Bool!, items:[AnyObject]!)->()?
    var hitpoints = 100
    var someset = ["oh no!","avenge me!"]
    init(){}

    func getHitFunc(impact:Int, passedCompletionsHandler:(sucsess:Bool!, items:[AnyObject]!)->()){
        completionHandler = passedCompletionsHandler
        hitpoints = hitpoints - impact
    }

    func checkIfDead{
        if hitpoints<=0 {               // The error received
            if completionHandler != nil{// Cannot invoke '!=' with an argument list of type 
                                        //'(@lvalue (sucsess: Bool!, products: [AnyObject]!) -> ()?, NilLiteralConvertible)' 
                //run the handler if dead
                completionHandler(sucsess: true, items: someset)
                //do not run it again
                completionHandler = nil     //Type '(sucsess: Bool!, products: [AnyObject]!) -> ()?' does not conform to protocol 'NilLiteralConvertible'
            }
        }
        else{
            completionHandler = nil      //Type '(sucsess: Bool!, products: [AnyObject]!) -> ()?' does not conform to protocol 'NilLiteralConvertible'
        }
    }
}

Source: (StackOverflow)

When do you use scope without a statement in C#?

Just recently I found out you can do this in C#:

{
    // google
    string url = "#";

    if ( value > 5 )
        url = "http://google.com";

    menu.Add( new MenuItem(url) );
}
{
    // cheese
    string url = "#"; // url has to be redefined again, 
                      // so it can't accidently leak into the new menu item

    if ( value > 45 )
        url = "http://cheese.com";

    menu.Add( new MenuItem(url) );
}

instead of i.e.:

    string url = "#";

    // google
    if ( value > 5 )
        url = "http://google.com";

    menu.Add( new MenuItem(url) );


    // cheese
    url = "#"; // now I need to remember to reset the url

    if ( value > 45 )
        url = "http://cheese.com";

    menu.Add( new MenuItem(url) );

This might be a bad example that can be solved in a lot of other manners.

Are there any patterns where the 'scope without statement' feature is a good practice?


Source: (StackOverflow)

Loop & output content_tags within content_tag in helper

I'm trying a helper method that will output a list of items, to be called like so:

foo_list( ['item_one', link_to( 'item_two', '#' ) ... ] )

I have written the helper like so after reading Using helpers in rails 3 to output html:

def foo_list items
    content_tag :ul do
        items.collect {|item| content_tag(:li, item)}
    end
end

However I just get an empty UL in that case, if I do this as a test:

def foo_list items
    content_tag :ul do
        content_tag(:li, 'foo')
    end
end

I get the UL & LI as expected.

I've tried swapping it around a bit doing:

def foo_list items
    contents = items.map {|item| content_tag(:li, item)}
    content_tag( :ul, contents )
end

In that case I get the whole list but the LI tags are html escaped (even though the strings are HTML safe). Doing content_tag(:ul, contents.join("\n").html_safe ) works but it feels wrong to me and I feel content_tag should work in block mode with a collection somehow.


Source: (StackOverflow)

Confusion about the lock statement in C#

This is from MSDN: The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section.

Does a critical section have to be same as the critical section?

Or does it mean: The lock keyword ensures that one thread does not enter any critical section guarded by an object of code while another thread is in any critical section guarded by the same object. ?

    class Program
{
    static void Main(string[] args)
    {
        TestDifferentCriticalSections();

        Console.ReadLine();
    }

    private static void TestDifferentCriticalSections()
    {
        Test lo = new Test();

        Thread t1 = new Thread(() =>
        {
            lo.MethodA();
        });
        t1.Start();

        Thread t2 = new Thread(() =>
        {
            lo.MethodB();
        });
        t2.Start();
    }
}

public class Test
{
    private object obj = new object();

    public Test()
    { }

    public void MethodA()
    {
        lock (obj)
        {
            for (int i = 0; i < 5; i++)
            {
                Thread.Sleep(500);
                Console.WriteLine("A");
            }
        }
    }

    public void MethodB()
    {
        lock (obj)
        {
            for (int i = 0; i < 5; i++)
            {
                Thread.Sleep(500);
                Console.WriteLine("B");
            }
        }
    }
}

Source: (StackOverflow)

Powershell try/catch/finally

I recently wrote a Powershell script that works great - However, I'd like to now upgrade the script and add some error checking / handling - But I've been stumped at the first hurdle it seems. Why won't the following code work?

try {
  Remove-Item "C:\somenonexistentfolder\file.txt" -ErrorAction Stop
}

catch [System.Management.Automation.ItemNotFoundException] {
  "item not found"
}

catch {
  "any other undefined errors"
  $error[0]
}

finally {
  "Finished"
}

The error is caught in the second catch block - You can see the output from $error[0]. Obviously I would like to catch it in the first block - What am I missing? Thanks


Source: (StackOverflow)

data block size in HDFS, why 64MB?

The default data block size of HDFS/hadoop is 64MB. The block size in disk is generally 4KB. What does 64MB block size mean? ->Does it mean that the smallest unit of read from disk is 64MB?

If yes, what is the advantage of doing that?-> easy for continuous access of large file in HDFS?

Can we do the same by using the original 4KB block size in disk?


Source: (StackOverflow)

Compiler error when declaring a variable inside if condition and no curly braces

Why does this first if compile well and the second fail?

if(proceed) {int i;} // This compiles fine.
if(proceed) int i;// This gives an error. (Syntax error on token ")", { expected after this token)

Source: (StackOverflow)

Why do instance variables seemingly disappear when inside a block?

Forgive me, guys. I am at best a novice when it comes to Ruby. I'm just curious to know the explanation for what seems like pretty odd behavior to me.

I'm using the Savon library to interact with a SOAP service in my Ruby app. What I noticed is that the following code (in a class I've written to handle this interaction) seems to pass empty values where I expect the values of member fields to go:

create_session_response = client.request "createSession" do
  soap.body = {
    :user => @user, # This ends up being empty in the SOAP request,
    :pass => @pass  # as does this.
  }
end

This is despite the fact that both @user and @pass have been initialized as non-empty strings.

When I change the code to use locals instead, it works the way I expect:

user = @user
pass = @pass

create_session_response = client.request "createSession" do
  soap.body = {
    :user => user, # Now this has the value I expect in the SOAP request,
    :pass => pass  # and this does too.
  }
end

I'm guessing this strange (to me) behavior must have something to do with the fact that I'm inside a block; but really, I have no clue. Could someone enlighten me on this one?


Source: (StackOverflow)

Change the context/binding inside a block in ruby

I have a DSL in Ruby that works like so:

desc 'list all todos'
command :list do |c|
  c.desc 'show todos in long form'
  c.switch :l
  c.action do |global,option,args|
    # some code that's not relevant to this question
  end
end

desc 'make a new todo'
command :new do |c|
  # etc.
end

A fellow developer suggested I enhance my DSL to not require passing c to the command block, and thus not require the c. for all the methods inside; presumably, he implied I could make the following code work the same:

desc 'list all todos'
command :list do
  desc 'show todos in long form'
  switch :l
  action do |global,option,args|
    # some code that's not relevant to this question
  end
end

desc 'make a new todo'
command :new do
  # etc.
end

The code for command looks something like

def command(*names)
  command = make_command_object(..)
  yield command                                                                                                                      
end

I tried several things and was unable to get it to work; I couldn't figure out how to change the context/binding of the code inside the command block to be different than the default.

Any ideas on if this is possible and how I might do it?


Source: (StackOverflow)

What does to_proc method mean?

I am learning rails and following this thread. I am stuck with the to_proc method. I consider symbols only as alternatives to strings (they are like strings but cheaper in terms of memory). If there is anything else I am missing for symbols, then please tell me. Please explain in simple way what to_proc means and what it is used for.


Source: (StackOverflow)

change order of blocks via local.xml file in magento

Is it possible to change the order of already existing blocks via the local.xml file? I know you can change the order of a block with the after or before attribute, but how can one change those attributes of existing blocks.

For example, if I want to place the layered navigation block underneath the newsletter subscription block in the left column, how would I do that?


Source: (StackOverflow)

Django : Is it impossible to static tag into block tag?

The code below makes error.. How could I resolve this problem??

Thanks in advance :)

{% block header %}
    <link rel="stylesheet" rel='nofollow' href="{% static 'shop/style.css' %}" />
{% endblock %}

The error output :

  • TemplateSyntaxError : Invalid block tag: 'static', expected 'endblock'

Source: (StackOverflow)