Thursday, April 14, 2011

Editing multiple buffers in vim: "((1) of 3)" in status line

When I switch between buffers in vim with ":bn" and ":bp", my status line shows the following handy information:

"foo.txt" 43 lines --88%-- ((1) of 3)                      38,1          All

(I think it's "set showmode" that enables that.) But that "(1)" is always literally "(1)" -- it doesn't change as I change buffers. (The parens around the "1" are strange as well.)

Does anyone know how to fix that?

ADDED: It probably has to do with something nutty in my .vimrc, which is here: http://yootles.com/outbox/.vimrc


Relatedly, here's a handy trick to make switching buffers really painless (entries in .vimrc):

"left/right arrows to switch buffers in normal mode
map <right> :bn<cr>
map <left> :bp<cr>


Keywords to improve searchability: vim, multiple buffers, switching between buffers, strange status line. [Add others here if you were looking for answers to this question and didn't find this on your first attempt!]

From stackoverflow
  • You can customize the looks of your statusline; for example, this is mine:

    set laststatus=2    " all windows have statuslines
    set statusline=%mb%n:%f%R%Y\ %l/%L,%c:%v
    


    1st EDIT:

    Try looking in the help for

    :help arglist-position
    :help shortmess
    

    I never used these options, so I cannot give you a detailed explanation, but with a little reading you should get to the bottom of this.

    dreeves : Ah, thanks; I will try that. I don't have my statusline set to anything now. I guess this is more of a workaround than a fix though, right? (Not that there's anything wrong with that, I'm just wondering if this is really a bug in vim or what.)
    ldigas : @dreeves - Yes, this is more of a workaround. The problem is that I cannot reproduce the (...). That is not the default behaviour. "showmode" you mentioned has nothing to do with it, it just shows the mode you're in (e.g. --INSERT--, --NORMAL--). Could you add your vimrc in your post to help analyze
    dreeves : Sure! yootles.com/outbox/.vimrc You're probably right that it's due to some craziness in my vimrc.
  • In my case status line is ok, but title of the gvim looks like you said.

    You can consider changing both statusline and titlestring to the same value as they use the same pattern options.

    For selecting buffers in a convenient way you can use
    minibufexpl.vim : Elegant buffer explorer - takes very little screen space
    http://www.vim.org/scripts/script.php?script_id=159

    or
    0scan : Tags based search for any things you might want to find(ctags, buffers,...).
    http://www.vim.org/scripts/script.php?script_id=2507

  • The reason vim shows ((1) of 3) is because of the argument list. When you started vim, you probably included 3 file names as arguments. Because you used :bn/:bp to switch buffers instead of :n/:N to move through the argument list, you're still on argument 1. Read :h arglist-position.

In Firefox, how do I force a cursor to stick to the last typed character?

I have an input field in which a serial number will be typed. The number of characters allowed is set.

Problem is that because of the letter-spacing, on typing a char in firefox, the cursor will jump ahead to where you would type the next char (even with maxlength set), which has the chars break break out of the little boxes they are supposed to sit in, like so: firefox cursor jump
firefox cursor jump

IE displays it 'correctly': ie no cursor jump
ie no cursor jump

How can I force firefox to not place the cursor after the letter-spacing? (jQuery would be nice, if JS is possible/needed)

Here's my code:

    #serial {
    background:transparent url(../images/bg_serial.gif) no-repeat scroll 0 50%;
    border:0 none;
    color:#FFFFFF;
    font:bold 16px Courier New;
    height:22px;
    letter-spacing:14px;
    line-height:normal;
    padding:4px 0 0 6px;
    text-transform:uppercase;
    width:208px;
    }
<form id="serialForm">
<label for="serial">Serial:</label>
<input id="serial" type="text" name="serial" maxlength="9" />
</form>
From stackoverflow
  • I fear firefox is actually handling this like it should handle, because the characters are now right-padded to match the letter-spacing. Safari does this as well. IE does it the wrong way, it pretends the character is smaller than it actually is.

    I would suggest to just make the width larger of the input box...

    roosteronacid : What you are trying to say is that Internet Explorer ignores the letter-spacing, right?
  • How about you check the length of the serial number and if its reached the correct length it will move the focus to another element thus avvoiding the overspill?

    <script type="text/javascript">
    function CheckLength(myBox){
    var myValue= myBox.Value;
    var myLength myValue.Length;
    if(myLength == 9){
    document.getElementById("Submit").Focus();
    }
    </script>
    <form id="serialForm">
    <label for="serial">Serial:</label>
    <input id="serial" type="text" name="serial" maxlength="9" onkeyup="CheckLength(this);" />
    <input type="submit" id="Submit" value="Submit"/>
    </form>
    
    roosteronacid : This makes for bad usability, imo.
  • You may be able to offset the x-position of the background image by a certain amount so that the background lines up with the characters in Firefox/Safari et al, and then use a conditional IE CSS statement to have IE revert to your 0 50% positioning.

    edit: misunderstood that the problem only appears at the final character.If pixel precision is not essential in the rest of the layout, setting the width of #serial to around width:230px works for me in IE and Firefox.

  • FireFox handles letter-spacing differently than Internet Explorer and the rest of the browsers, it seems.

    If you change the width of the input element to 220 pixels, you won't cause any text-overflow. And since you are effectively hiding the input, the extra width won't matter.


    I've tested this solution in Chrome build 1.0.154.53, FireFox 3.0.7 and Internext Explorer 8.0.6001. 18372.

HQL order by within a collection

I have 2 entities: car and wheels (oneToMany) and I want to retrieve my car, with all the wheels and (this is the tricky part) ordered by wheels.location.

Select c from Car LEFT JOIN FETCH c.wheels order by c.wheels.location doesn't work: "illegal attempt to dereference collection".

Any idea how to do this and if this is possible in HQL?

From stackoverflow
  • SELECT DISTINCT c FROM Car LEFT JOIN FETCH c.wheels AS wheels ORDER BY wheels.location
    
  • Hmm. Think you might need to use an alias?

    Select c from Car LEFT JOIN FETCH c.wheels wheel order by wheel.location
    

SQL IN clause slower than individual queries

I'm using Hibernate's JPA implementation with MySQL 5.0.67. MySQL is configured to use InnoDB.

In performing a JPA query (which is translated to SQL), I've discovered that using the IN clause is slower than performing individual queries. Example:

SELECT p FROM Person p WHERE p.name IN ('Joe', 'Jane', 'Bob', 'Alice')

is slower than four separate queries:

SELECT p FROM Person p WHERE p.name = 'Joe'
SELECT p FROM Person p WHERE p.name = 'Jane'
SELECT p FROM Person p WHERE p.name = 'Bob'
SELECT p FROM Person p WHERE p.name = 'Alice'

Why is this? Is this a MySQL performance limitation?

From stackoverflow
  • If you're using the IN operator, it's not much different than saying:

    (p.name = 'Joe' OR p.name = 'Jane' OR p.name = 'Bob' OR p.name = 'Alice')
    

    Those are four conditions which must be checked for every row that the query must consider. Of course, each other query you cite has only one condition. I don't believe in most real-world scenarios doing four such queries would be faster, since you have to consider the time it takes for your client to read the result sets and do something with them. In that case, IN looks pretty nice; even better if it can use an index.

  • Are you measuring wall-clock time or query execution time? My guess is that the actual execution time for each of the four individual queries may add up to less than the time to execute the IN query, but the overall wall-clock time will be much longer for the four queries.

    It will help to have an index on the name column.

    Steve Kuo : I am measuring total elapsed time.
  • This is a known deficiency in MySQL.

    It is often true that using UNION performs better than a range query like the one you show. MySQL doesn't employ indexes very intelligently for expressions using IN (...). A similar hole exists in the optimizer for boolean expressions with OR.

    See http://www.mysqlperformanceblog.com/2006/08/10/using-union-to-implement-loose-index-scan-to-mysql/ for some explanation and detailed benchmarks.

    The optimizer is being improved all the time. A deficiency in one version of MySQL may be improved in a subsequent version. So it's worth testing your queries on different versions.

    It is also advantageous to use UNION ALL instead of simply UNION. Both queries use a temporary table to store results, but the difference is that UNION applies DISTINCT to the result set, which incurs an additional un-indexed sort.

    Steve Kuo : Does SQL Server have this deficiency?
    Bill Karwin : I'm not a SQL Server user, so I don't know the answer. Best thing to do is try both query forms in Query Analyzer, and use the Show Execution Plan menu option.
    Matt Rogish : No, SQL Server does not have this problem
  • A query as simple as the IN demonstrated shouldn't have an issue with the optimizer choosing to use the index. The UNION work mentioned by Bill is only required occasionally when you have more complex queries. It could be an issue with index statistics.

    Have you done an ANALYZE on the table in question?

    How many rows are in the table and how many match the IN clause?

    What does EXPLAIN say for the queries in question?

  • For me because the IN clause can free the database and tables up to be used by other connections, and there are application structure benefit to using it, the IN clause is an invaluable tool, even if there is a slight lag over individual queries.

    The following technique is utilized in almost every PHP/MySQL application I construct.

    I use the IN clause quite a bit with numerical keys:

    e.g.

    grab five master items and all subites could be:

    $master_arr = mysql_query(
     select * from master table where master_id in (1,7,9,10)
    );
    

    then:

    $subitem_arr = mysql_query(
       select * from subitems table where par_master_id in (1,7,9,10)
    );
    

    the add the subarray to the master items:

    foreach($subitem_arr AS $sv){
         $m_key = $sv['par_master_id'];
         $s_key = $sv['subitem_id'];
         $master_arr[$m_key]['subitem'][$s_key] = $sv;
    }
    

    This does two things: 1.) the tables are not all held at once with a join 2.) only two mysql queries produce a tree of data

How to programatically encrypt/decrypt plain text credentials in JSP?

As as part of my daily routine, I have the misfortune of administering an ancient, once "just internal" JSP web application that relies on the following authentication schema:

...

// Validate the user name and password.
if ((user != null) && (password != null) && (
    (user.equals("brianmay") && password.equals("queen")) ||
    (user.equals("rogertaylor") && password.equals("queen")) ||
    (user.equals("freddiemercury") && password.equals("queen")) ||
    (user.equals("johndeacon") && password.equals("queen"))
   )) {
// Store the user name as a session variable.
    session.putValue("user", user);

...

As much as I would like to, the Queen members have never been users of the system but anyway it does make a great example, does it not?

Despite that by policy this client enforces security by domain authentication among other things, therefore this issue isn't seen as a security risk, still, my idea is to at least obfuscate that plain text credentials using perhaps a simple MD5 or SHA1 method, so such sensitive data is not visible to the naked eye.

I'm a total newbie when it comes to JSP so I would really appreciate any piece of advice you'd be willing to share with me.

Thanks much in advance!

From stackoverflow
  • First of all you should move that logic from jsp to a separate class.

    Second, you shouldn't keep plain text password anywhere in the code. Use some kind of one way hash function (md5, sha1, ...) and keep only password hashes.

    When checking for user password, first hash it and then compare hashes.

    Nano Taboada : Thanks much for the reply buddy. Would you mind elaborating about that techniques you mention?
  • It is hard to understand the exact scheme you are thinking about but I assume the password is coming in from a request and you want to calculate the MD5 hash in a JSP that the request is being sent to. After that you can compare it to the pre-computed MD5 version. You could even be more secure if it isn't being done with https and use a javascript MD5 library to hash the password before submitting it.

    You can MD5 a string in java like this:

    try
    {
      String digestInput = "queen";
    
      MessageDigest messageDigest = MessageDigest.getInstance("MD5");
      messageDigest.update(digestInput.getBytes());
    
      BASE64Encoder base64Encoder = new BASE64Encoder();
      String digestString = base64Encoder.encode(messageDigest.digest());
    
      // digestString now contains the md5 hashed password
    }
    catch (Exception e)
    {
      // do some type of logging here
    }
    
    Nano Taboada : Beautiful! Thanks a lot! What would be the simplest way to store that MD5 hash? A plain text file?
    mtruesdell : Surely pre-computing with js would only be more secure if the password is being used other places. Otherwise precomputing the hash means you are just comparing two strings on the server side and it's no more secure than comparing naked passwords. An attacker could just submit the hash manually.
    Nano Taboada : I don't think we're authorized to implement solutions in JS for that particular client so I'd have to stick with storing the pre calculated MD5 and then comparing. Could you give me some hint regarding how to implement that in JSP?
    mtruesdell : Use carson's code to get the hash. First time through store it, after that compute and compare the stored value. A database is the common storage. The problem with a text file is that you would have to synchronize access to it so that multiple users didn't try to write to it at the same time.
  • Good Day:

    based on the previous example Could you please let me know how to decode or decrypt digestString ??? In order to get the word "queen" Thanks in Advance

Wednesday, April 13, 2011

PHP: Creating a psuedo-join method inside an object

I am trying to create an object that is capable of handling query-like conditional statements. This is so I can 'join' two conditions together to create a dependency between them based on the type of 'join' being used. I currently have a simple object that contains the following methods:

public function addCondition ( Condition $condition, $join = null )
{
    $this->conditions[] = $condition;
}

public function validate ( )
{
    foreach ( $this->conditions as $condition )
    {
        $result = $condition->validate( );
        [...]
    }
}

The problem is, I need to be able to perform a conditional join between two statements, that will affect the return value of the the validate method. The idea is that you could supply a condition as follows:

$this->addCondition($condition_1);
$this->addCondition($condition_2, 'AND');
$this->addCondition($condition_3, 'NOT');

This would then generate the logic required to specify that the results of the third condition would backwards-chain to affect the results of the first condition.

In the example, lets say:

condition_1 = Apple is Red
condition_2 = Apple is Ripe
condition_3 = Apple is Golden Delicious

Using this I should assume that if I was to pass a ripe, red and golden delicious apple, the result of validate() would be false. The method should fail because the 'join' for condition_3 is NOT.

However, at present there is no way of telling the code that the result of the entire method depends on the result of the previous condition and the way it is joined to it.

Any help is greatly appreciated! Thanks.

From stackoverflow
  • Put the logic in your Condition subclasses.

    Create a Condition_And class that takes two (or more) Condition objects and returns true only if they are both true.

    Create a Condition_Or class that takes two (or more) Condition objects and returns false if any is true.

    Create a Condition_Not class if you feel it is necessary (Apple is NOT Golden Delicious).

    Stringing these together should get you any query you're looking for. Since they're all subclasses of the same type, you can build them up putting NOTs inside of ORs inside of ANDs inside of ORs and so on.

  • Conditionals that involve both AND and OR are inherently nested. Your class does not seem to have a way to express this.

    No nesting means that your conditions must either all be joined with AND, or all be joined with OR. In any case - you can't use both at the same time.

    For your example, AND seems the natural choice, so all you need is a NOT flag for each condition:

    $this->addCondition($condition_1, true);   // e.g.: must be true to succeed
    $this->addCondition($condition_2, true);
    $this->addCondition($condition_3, false);  // e.g.: must be false to succeed
    

    You would then do:

    $valid = true;
    
    foreach ( $this->conditions as $condition )
    {
      $valid = $valid && $condition->validate();
      if (!$valid) 
      {
        // react to "validation failed at $condition"
      }
    }
    
    return $valid;
    

Client-Side validation with groups

I have several tabs that are loaded via ajax, and each one has a set of validators. I want to allow the user to change tabs only if the tab is valid

I thought setting a validationgroup to the validators and then check for the specific group like this, would work:

function validatePage(group) {
    return Page_ClientValidate(group);
}

However, when I call the function, it always returns true. Can anyone see what I'm doing wrong?

I check it like this

alert(validatePage("presentaciones"));

And I have some validators:

// (...)
<asp:TextBox ValidationGroup="presentaciones" id="txtDescription" runat="server" Text='<%# Eval("Description") %>' MaxLength="50" />
<asp:RequiredFieldValidator ID="DescriptionRequiredFieldValidator" runat="server" ControlToValidate="txtDescription" SetFocusOnError="true" ValidationGroup="presentaciones" ErrorMessage="Debe ingresar una descripción" Display="Dynamic" />
// (...)
From stackoverflow
  • I have made groups work server-side with Page.Validate(group) but I wasn't aware this could be done client-side. Perhaps you need to implement a custom validation control that checks the status of each tab.

  • My guess is that the validation scripts are not being wired up. In your function do an alert((typeof(Page_Validators) == "undefined")) and see if it displays true. You said you are loading the tabs via ajax. You may want to see if placing a validator on the page somewhere will help wire up the validation scripts.

    The other thing to watch for is Firefox and legacy rendering mode....client side just plain does not work in that scenario.