EzDevInfo.com

order interview questions

Top order frequently asked interview questions

Python dictionary, keep keys/values in same order as declared

new to Python and had a question about dictionaries. I have a dictionary that I declared in a particular order and want to keep it in that order all the time. The keys/values can't really be kept in order based on their value, I just want it in the order that I declared it.

So if I have the dictionary:

d = {'ac':33, 'gw':20, 'ap':102, 'za':321, 'bs':10}

It isn't in that order if I view it or iterate through it, is there any way to make sure Python will keep the explicit order that I declared the keys/values in?

Using Python 2.6


Source: (StackOverflow)

Preserving order with LINQ

I use LINQ to Objects instructions on an ordered array. Which operations shouldn't I do to be sure the order of the array is not changed?


Source: (StackOverflow)

Advertisements

How to preserve insertion order in HashMap? [duplicate]

This question already has an answer here:

I'm using a HashMap. When I iterate over the map, the data is returned in (often the same) random order. But the data was inserted in a specific order, and I need to preserve the insertion order. How can I do this?


Source: (StackOverflow)

How do I change Bootstrap 3 column order on mobile layout?

I'm making a responsive layout with a top fixed navbar. Underneath I have two columns, one for a sidebar (3), and one for content (9). Which on desktop looks like this

navbar
[3][9]

When I resize to mobile the navbar is compressed and hidden, then the sidebar is stacked on top of the content, like this:

navbar
[3]
[9]

I would like the main content at the top, so I need to change the order on mobile to this:

navbar
[9]
[3]

I found this article which covers the same points, but the accepted answer has been edited to say that the solution no applies to the current version of Bootstrap.

How can I reorder these columns on mobile? Or alternatively, how can I get the sidbar list-group into my expanding navbar?

Here is my code:

<div class="navbar navbar-inverse navbar-static-top">
  <div class="container">
    <a rel='nofollow' href="#" class="navbar-brand">Brand Title</a>
    <button class="navbar-toggle" data-toggle="collapse" data-target=".navHeaderCollapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <div class="collapse navbar-collapse navHeaderCollapse">

    <ul class="nav navbar-nav navbar-right"><!--original navbar-->
      <li class="active"><a rel='nofollow' href="#">Home</a></li>
      <li><a rel='nofollow' href="#">FAQ</a></li>
    </ul>

    </div>
  </div>
</div><!--End Navbar Div-->
    <div class="container">
  <div class="row">

    <div class="col-lg-3">
  <div class="list-group">
    <a rel='nofollow' href="#" class="list-group-item">
    <h4 class="list-group-item-heading">Lorem ipsum</h4>
    <p class="list-group-item-text">Lorem Ipsum is simply dummy text.</p></a>
  </div>
</div><!--end sidebar-->


<div class="col-lg-9">
  <div class="panel panel-default">
    <div class="panel-body">
      <div class="page-header">
     Main Content
    </div>
  </div>
</div><!--end main content area-->

Source: (StackOverflow)

Ordering by the order of values in a SQL IN() clause

I am wondering if there is away (possibly a better way) to order by the order of the values in an IN() clause.

The problem is that I have 2 queries, one that gets all of the IDs and the second that retrieves all the information. The first creates the order of the IDs which I want the second to order by. The IDs are put in an IN() clause in the correct order.

So it'd be something like (extremely simplified):

SELECT id FROM table1 WHERE ... ORDER BY display_order, name

SELECT name, description, ... WHERE id IN ([id's from first])

The issue is that the second query does not return the results in the same order that the IDs are put into the IN() clause.

One solution I have found is to put all of the IDs into a temp table with an auto incrementing field which is then joined into the second query.

Is there a better option?

Note: As the first query is run "by the user" and the second is run in a background process, there is no way to combine the 2 into 1 query using sub queries.

I am using MySQL, but I'm thinking it might be useful to have it noted what options there are for other DBs as well.


Source: (StackOverflow)

How to limit UITableView row reordering to a section

I was hitting my head over this one, and google was turning up nothing. I eventually worked it out and thought I'd write it up here for the sake of the next person.

You have a UITableView with multiple sections. Each section is homogeneous, but the table overall is heterogeneous. So you might want to allow re-ordering of rows within a section, but not across sections. Maybe you only even want want one section to be reorderable at all (that was my case). If you're looking, as I was, at the UITableViewDataSourceDelegate you won't find a notification for when it is about to let you move a row between sections. You get one when it starts moving a row (which is fine) and one when it's already moved it and you get a chance to sync with your internal stuff. Not helpful.

So how can you prevent re-orders between sections?

I'll post what I did as a separate answer, leaving it open for someone else to post an even better answer!


Source: (StackOverflow)

Order by multiple columns with Doctrine

I need to order data by two columns (when the rows have different values for column number 1, order by it; otherwise, order by column number 2)

I'm using a QueryBuilder to create the query.

If I call the orderBy method a second time, it replaces any previously specified orderings.

I can pass two columns as the first parameter:

->orderBy('r.firstColumn, r.secondColumn', 'DESC');

But I cannot pass two ordering directions for the second parameter, so when I execute this query the first column is ordered in an ascending direction and the second one, descending. I would like to use descending for both of them.

Is there a way to do this using QueryBuilder? Do I need to use DQL?


Source: (StackOverflow)

Sort rows in data.table (R)

Let's say I have the following data.table in R:

  library(data.table)
  DT = data.table(x=rep(c("b","a","c"),each=3), y=c(1,3,6), v=1:9)

I want to order it by two columns (say columns x and v). I used this:

 DT[order(x,v)] # sorts first by x then by v (both in ascending order)

But now, I want to sort it by x (in decreasing order) and have the following code:

  DT[order(-x)] #Error in -x : invalid argument to unary operator

Therefore, I think this error is due to the fact that class(DT$x)=character. Could you give me any suggestion in order to solve this issue?

I know I can use DT[order(x,decreasing=TRUE)], but I want to know the syntax to sort by several columns using both ways (some decreasing, some increasing) at the same time.

Note that if you use DT[order(-y,v)] the result is ok, but if you use DT[order(-x,v)] there is an error. So, my question is: how to solve this error?


Source: (StackOverflow)

How to define servlet filter order of execution using annotations in WAR

If we define webapp specific servlet filters in WAR's own web.xml, then the order of execution of the filters will be the same as the order in which they are defined in the web.xml.

But, if we define those filters using @WebFilter annotation, what is the order of execution of filters, and how can we determine the order of execution?


Source: (StackOverflow)

MySQL: Sort GROUP_CONCAT values

In short: Is there any way to sort the values in a GROUP_CONCAT statement?

Query:

GROUP_CONCAT((SELECT GROUP_CONCAT(parent.name SEPARATOR " &raquo; ") 
FROM test_competence AS node, test_competence AS parent 
WHERE node.lft BETWEEN parent.lft AND parent.rgt 
  AND node.id = l.competence 
  AND parent.id != 1 
ORDER BY parent.lft) SEPARATOR "<br />\n") AS competences

I get this row:

Crafts » Joinery

Administration » Organization

I want it like this:

Administration » Organization

Crafts » Joinery


Source: (StackOverflow)

MySQL Orderby a number, Nulls last

Currently I am doing a very basic OrderBy in my statement.

SELECT * FROM tablename WHERE visible=1 ORDER BY position ASC, id DESC

The problem with this is that NULL entries for 'position' are treated as 0. Therefore all entries with position as NULL appear before those with 1,2,3,4. eg:

NULL, NULL, NULL, 1, 2, 3, 4

Is there a way to achieve the following ordering:

1, 2, 3, 4, NULL, NULL, NULL.

Source: (StackOverflow)

Is the order of iterating through std::map known (and guaranteed by the standard)?

What I mean is - we know that the std::map's elements are sorted according to the keys. So, let's say the keys are integers. If I iterate from std::map::begin() to std::map::end() using a for, does the standard guarantee that I'll iterate consequently through the elements with keys, sorted in ascending order?


Example:

std::map<int, int> map_;
map_[1] = 2;
map_[2] = 3;
map_[3] = 4;
for( std::map<int, int>::iterator iter = map_.begin();
     iter != map_.end();
     ++iter )
{
    std::cout << iter->second;
}

Is this guaranteed to print 234 or it's implementation defined?


Real life reason: I have a std::map with int keys. In very rare situations, I'd like go iterate through all elements, with key, greater than a concrete int value. Yep, it sounds like std::vector would be the better choice, but notice my "very rare situations".


EDIT: I know, that the elements of std::map are sorted.. no need to point it out (for most of the answers here). I even wrote it in my question.
I was asking about the iterators and the order when I'm iterating through a container. Thanks @Kerrek SB for the answer.


Source: (StackOverflow)

What order are the Junit @Before/@After called?

I have an Integration Test Suite. I have a IntegrationTestBase class for all my tests to extend. This base class has a @Before (public void setUp()) and @After (public void tearDown()) method to establish API and DB connections. What I've been doing is just overriding those two methods in each testcase and calling super.setUp() and super.tearDown(). However this can cause problems if someone forgets to call the super or puts them at the wrong place and an exception is thrown and they forget to call super in the finally or something.

What I want to do is make the setUp and tearDown methods on the base class final and then just add our own annotated @Before and @After methods. Doing some initial tests it appears to always call in this order:

Base @Before
Test @Before
Test
Test @After
Base @After

but I'm just a little concerned that the order isn't guaranteed and that it could cause problems. I looked around and haven't seen anything on the subject. Does anyone know if I can do that and not have any problems?

Code:

public class IntegrationTestBase {

    @Before
    public final void setUp() { *always called 1st?* }

    @After
    public final void tearDown() { *always called last?* }
}


public class MyTest extends IntegrationTestBase {

    @Before
    public final void before() { *always called 2nd?* }

    @Test
    public void test() { *always called 3rd?* }

    @After
    public final void after() { *always called 4th?* }
}

Source: (StackOverflow)

UICollectionView effective drag and drop

I am currently trying to implement the UITableView reordering behavior using UICollectionView.

Let's call a UItableView TV and a UICollectionView CV (to clarify the following explanation)

I am basically trying to reproduce the drag&drop of the TV, but I am not using the edit mode, the cell is ready to be moved as soon as the long press gesture is triggered. It works prefectly, I am using the move method of the CV, everything is fine.

I update the contentOffset property of the CV to handle the scroll when the user is dragging a cell. When a user goes to a particular rect at the top and the bottom, I update the contentOffset and the CV scroll. The problem is when the user stop moving it's finger, the gesture doesn't send any update which makes the scroll stop and start again as soon as the user moves his finger.

This behavior is definitely not natural, I would prefer continu to scroll until the user release the CV as it is the case in the TV. The TV drag&drop experience is awesome and I really want to reproduce the same feeling. Does anyone know how they manage the scroll in TV during reordering ?

  • I tried using a timer to trigger a scroll action repeatedly as long as the gesture position is in the right spot, the scroll was awful and not very productive (very slow and jumpy).
  • I also tried using GCD to listen the gesture position in another thread but the result is even worst.

I ran out of idea about that, so if someone has the answer I would marry him!

Here is the implementation of the longPress method:

- (void)handleLongPress:(UILongPressGestureRecognizer *)sender
{
    ReorganizableCVCLayout *layout = (ReorganizableCVCLayout *)self.collectionView.collectionViewLayout;
    CGPoint gesturePosition = [sender locationInView:self.collectionView];
    NSIndexPath *selectedIndexPath = [self.collectionView indexPathForItemAtPoint:gesturePosition];

    if (sender.state == UIGestureRecognizerStateBegan)
    {
        layout.selectedItem = selectedIndexPath;
        layout.gesturePoint = gesturePosition; // Setting gesturePoint invalidate layout
    }
    else if (sender.state == UIGestureRecognizerStateChanged)
    {
        layout.gesturePoint = gesturePosition; // Setting gesturePoint invalidate layout
        [self swapCellAtPoint:gesturePosition];
        [self manageScrollWithReferencePoint:gesturePosition];
    }
    else
    {
        [self.collectionView performBatchUpdates:^
        {
            layout.selectedItem = nil;
            layout.gesturePoint = CGPointZero; // Setting gesturePoint invalidate layout
        } completion:^(BOOL completion){[self.collectionView reloadData];}];
    }
}

To make the CV scroll, I am using that method:

- (void)manageScrollWithReferencePoint:(CGPoint)gesturePoint
{
    ReorganizableCVCLayout *layout = (ReorganizableCVCLayout *)self.collectionView.collectionViewLayout;
    CGFloat topScrollLimit = self.collectionView.contentOffset.y+layout.itemSize.height/2+SCROLL_BORDER;
    CGFloat bottomScrollLimit = self.collectionView.contentOffset.y+self.collectionView.frame.size.height-layout.itemSize.height/2-SCROLL_BORDER;
    CGPoint contentOffset = self.collectionView.contentOffset;

    if (gesturePoint.y < topScrollLimit && gesturePoint.y - layout.itemSize.height/2 - SCROLL_BORDER > 0)
        contentOffset.y -= SCROLL_STEP;
    else if (gesturePoint.y > bottomScrollLimit &&
             gesturePoint.y + layout.itemSize.height/2 + SCROLL_BORDER < self.collectionView.contentSize.height)
        contentOffset.y += SCROLL_STEP;

    [self.collectionView setContentOffset:contentOffset];
}

Source: (StackOverflow)

Sort objects in ArrayList by date?

Can someone help me with this? Every example I find is about doing this alphabetically, while I need my elements sorted by date.

My ArrayList contains objects on which one of the datamembers is a DateTime object. On DateTime I can call the functions:

lt() // less-than
lteq() // less-than-or-equal-to

So to compare I could do something like:

if(myList.get(i).lt(myList.get(j))){
    // ...
}

I don't really know what to do inside the if block. Any ideas?


Source: (StackOverflow)