Monday, February 21, 2011

Using ZK Tree component, how do I remove Treeitems from a Treechildren node

Does anyone know how to remove Treeitems from a Treechildren node in ZK? I have tried using an iterator and removeChild but a ConcurrentModificationException!

List<Treeitem> myTreeItems = treechildren.getChildren();

Iterator<Treeitem> iterator = myTreeItems.iterator();

while (iterator.hasNext()){
   myItem = (Treeitem)iterator.next();
   parent.removeChild(myItem);
}

Any ideas?

From stackoverflow
  • That is not the correct way to remove the items, you need to do something like this.

    while (parent.getItemCount() > 0) {
       parent.removeChild(parent.getFirstChild());
    }
    

    This will provide the functionality that you require!

    More details on using the Tree component are available here.

    Justin.Eckner : Thanks, worked like a charm!
  • As what I saw in your case you want to remove all components which are all attached on a treechildren. I think the fastest way is:

    treechildren.getChildren().clear();
    

    just operate the result like a java.util.List.

php:how to check if string contains any of the listed keyword ?

i have an array of strings.

I have an array of keywords.

i loop through each string, and need to store them to mysql database if it contains any of the keywords.

currently i am using multiple stristr(), which is getting difficult.

is it possible to do something like stristr($string, array("ship","fukc","blah")); ?

From stackoverflow
  • try using in_array()

    for ($i = 0 ; $i < count($arrayString); $i++){
    
      for ($j = 0 ; $j < count($arrayKeyWord); $j++){
    
        if (in_array($arrayString[$i],$arrayKeyWord[$j]) == true){
          /* mysql code */
    
        }
    
      }
    
    }
    
  • I would advice you to use regular expresion for that

    snipet:

    preg_match_all('|(keyword1|keyword2|keyword3)|', $text, $matches);
    var_dump($matches);
    

    see the documentation of preg_match_all for reference

  • $to_be_saved = array();
    foreach($strings as $string) {
      foreach($keywords as $keyword) {
         if(stripos($string, $keyword) !== FALSE){
            array_push($to_be_saved, $keyword);
         }
      }
    

    }

    /*save $to_be_saved to DB*/
    
  • foreach ( $strings as $string ) {
      foreach ( $keywords as $keyword ) {
        if ( strpos( $string, $keyword ) !== FALSE ) {
          // insert into database
        }
      }
    }
    
  • if(in_array($string, array("ship","fukc","blah"))) {

    }

    see http://au.php.net/manual/en/function.in-array.php

What is a resonable maximum DB rows for built-in GridView paging?

I'm using a simple GridView to display some tabular data straight from a SQL Server DB. I know using the built-in paging functionality is inefficient because it pulls the entire dataset on every bind. At the moment that's fine, there are only a few dozen rows.

The data rows themselves are... about 6 nvarchar(50) columns, a couple ints, a couple floats.

The question is, at what point do I need to implement some custom paging? 500 rows? 5000? 50000?

Maybe a tough question to answer. Need more information?

From stackoverflow
  • It really depends on when it starts to slow down and how important it is to you. There is not magic number. You may be able to put indexes and other things in place to speed it up and not have to worry about it for a long time. Ideally, you should never return more than the rows being used.

  • Can you profile with test data? If so I highly recommend just trying increasing amounts of rows until it becomes too slow for you. By doing so you will probably gain some insight you cannot get any other way than trying yourself.

    Having said that, I personally never just bind from the database, I always have a glue object that manages the datasource and gets exactly what is needed for the page. It might very well not be worth spending the time on that for you though.

  • It depends on the number of users hitting the web application as well as the volume of data that needs to be displayed in the grid because by not using custom paging you are putting more load on the web server. Personally I always implement data paging when the volume > 1000 rows.

    Bryan : Finally, an answer with a number in it. :) I'm going to leave it as-is for now. Looks like we'll max out at 5000 rows, which is not a lot of data. I believe the GridView will handle this without trouble. Maybe I'll update this question with a new answer if I find otherwise.
  • Given the choice I would never use it, its not a great deal of work to implement custom paging and will give you a much more scalable solution. If you use the built in provider you 're always going to wonder at what point will it start slowing things down.

CodeIgniter form verification and class

I'm using the form validation library and have something like this in the view

<p>
        <label for="NAME">Name <span class="required">*</span></label>
        <?php echo form_error('NAME'); ?>
        <br /><input id="NAME" type="text" name="NAME" class="" value="<?php echo set_value('NAME'); ?>"  />
</p>

I'd like to add a class to the input that is dependent on the form error so i could have something like this

<input id="NAME" type="text" name="NAME" class="<?php echo $error;?>" value="<?php echo set_value('NAME'); ?>"

I realize that it would have to be a bit more complicated, but I'd like to this this without creating a custom rule callback for every field.

Thanks ~Daniel

From stackoverflow
  • I just realized, there is a way to do this with error delimiters

    $this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
    

    I this makes it much easier.

    But just out of curiosity, Is there any way of doing this with class in the input?

    Thorpe Obazee : What do you mean by class in the input?
    Daniel : Ideally... I'd like to be able to push another variable in. Right now you can set the message to be displayed in the callback. I would like to set an error class to assign css to. This would allow me to style it differently depending on the error.
  • If you set all your validation fields in your controller using:

    $this->validation->set_fields()
    

    You will have access to any possible error messages, which you could use in the following manner:

    <input id="NAME" name="NAME" value="<?php echo $this->validation->NAME; ?>" <?php echo (!empty($this->validation->NAME_error)) ? 'class="error"' : ''; ?> />
    

    http://codeigniter.com/user%5Fguide/libraries/validation.html

    As pointed out in the comments, the code above references the old validation library. The new 1.7 way to perform this task would be:

    <input id="NAME" name="NAME" value="<?php echo set_value('NAME'); ?>" <?php echo (!empty(form_error('NAME')) ? 'class="error"' : ''; ?> />
    
    Thorpe Obazee : This is really really wrong to teach the old validation class. You should go use the new Form Validation class here: http://codeigniter.com/user_guide/libraries/form_validation.html
    cballou : I added a solution for 1.7 as well.

Page not submitting in Firefox

Hi,

I've a user control registered in an aspx page. User control has a textbox and a submit button. Ascx code of user control is placed under a asp:panel. Using firefox, when user hits enter key, the page is not submitting to the server.However, this works fine in IE browsers. Am i missing something here?

From stackoverflow
  • Hi Ed, Try setting defaultbutton="urbuttonid" to the asp:panel

    Pandiya Chendur : Whether ur page is submitting or not when using firefox.... ur question is not clear....
  • Set property DefaultButton="submitbtn" for asp:panel.

    Replace submitbtn with your asp:button id.

  • Yea, what the others say. You've probably got a submit button earlier in the page that Firefox is associating you enter key press with.

    Use:

      <asp:panel .... DefaultButton="btSubmit">
         <asp:textbox ... />
         <asp:button id="btSubmit" ... />
        </asp:panel>
    

jQuery find() returning an empty string in Google Chrome

I'm using jQuery to setup an Ajax request that grabs an XML feed from a PHP script and then parses some information out of the feed and inserts it into the DOM. It works fine in Firefox; however, in Chrome, I am getting an empty string for the title element.

Here's the basic setup of the Ajax request:

$.get('feed.php', function(oXmlDoc) {
  $(oXmlDoc).find('entry').each(function() {
    $(this).find('title').text();
    $(this).find('id').text();
    // do other work...
  }); 
});

For what it's worth, here's the PHP script that's grabbing data from the feed. I'm using cURL because I'm making the request across domains (and because it was a quick and dirty solution for the problem at hand).

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $str_feed_url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$xml = curl_exec($curl);
curl_close($curl);

echo $xml;

The XML data is being returned correctly and I can see the values of the sibling nodes in Chrome (such as ID), but, for whatever reason, I continue to get an empty string for the title node.

Edit: As requested, here's a fragment of the relevant XML:

<entry>
    <id>http://TheAddress.com/feed/01</id>
    <title type="text">The Title of the Post</title>
    <author><name>Tom</name></author>
    <published>2009-11-05T13:46:44Z</published>
    <updated>2009-11-05T14:02:19Z</updated>
    <summary type="html">...</summary>
</entry>
From stackoverflow
  • The page you have in the example XML has an HTML entity in the title. This can cause issues. Here is a blog post I found on this issue.

    I wonder if the same goes for other special characters...

    The home page title looks like this:

    <title>The Address Hotels + Resorts</title>
    
  • I haven't tried it, but make sure that the xml is returned with the correct content type (text/xml). You can also set the dataType to xml at the jQuery.ajax(options).

    Tom : I ended up needing to specify the Content-Type as rss+xml in the PHP script. $.get() ended up working just fine after that.
  • Hi! I have the same problem. It seems than Chrome don't handle html tag in ajax. try changing "title" to "booktitle" in the XML and in the JS.

urlencode but ignore certain chars

It is possible to run the urlencode function without converting # or % ?

From stackoverflow
  • There are a number of examples in the comments section on the PHP Docs of urlencode for alternative functions. You could simply take the most appropriate function for your needs and remove any replacements for # and %.

    http://php.net/manual/en/function.urlencode.php

  • Can you not just do:

    $str = urlencode($str);
    $str = str_replace("%23", "#", $str);
    $str = str_replace("%25", "%", $str);
    
    cballou : Mmmm less lines. +1
    Patrick : nice solution!!!
  • I don't think so, but I guess you could replace the equivalent codes from the encoded string back with # and %.

  • As far as I know, it's not possible with the urlencode function itself, but you could do a simple string replacement on the encoded results to achieve that:

    function my_urlencode($input){
       $input=urlencode($input); 
       return str_replace(array("%25","%23"),array("%","#"),$input);
    }
    

Recommendations for eCommerce Framework / Products for working with Django?

We are building out an app in Django and trying to nail down what the right ecommerce framework will be to work with in Django. We've heard of Satchmo. Any other suggestions on ways to approach ecommerce in Django that's clean, simple, cheap and easy to implement? Thanks!

From stackoverflow
  • Take a look on the LFS - it is much simpler then Satchmo is

View Control name concatenated with ClientID and masterpage control name in ASP.NET MVC

I am working with ASP.NET MVC application.

I have One master page having one contentplaceholder. I have one view placed in the contentplaceholder of master page. i have few textBoxes say "name", "age" , "email" in it. I also have submit button in my master page.

when i click submit button , postback event will be called in the controller.

//POST
public ActionResult Result(FormCollection Form) { }

Question is if i try to access the value of the text box "name" using Form["name"] it will give me null value.

Instead Form["$ct100$contentplaceholder1$name"] will give me the correct value.

can any one tell how to get the value using only "name" ?

From stackoverflow
  • The input name was autogenerated for you, which you don't want to happen. Try to generate those inputs in MVC-style, like this:

    <%=Html.TextBox("name")%>
    

    or like this:

    <input type="text" id="name" name="name" value="" />
    
  • Don't mix Web Forms with MVC

    You shouldn't be using <asp:TextBox id="name" /> but rather

    <%= Html.TextBox("name") %>
    

Removing multiple object from array

I place the MC in an array and would like to remove it later on from an index maybe till the end.

//Removeing MC from stage, from an index till the end
LISTmc.removeChild(listArray[clickedIndex+1]);

//Removing MC starting from an index till the end
listArray.splice(clickedIndex+1);

Is the way to remove the MC from the stage same with removing it from array?

From stackoverflow
  • Do you mean that for the MovieClips in the array you remove you also want to remove those from the stage?

    for (var i:int = clickedIndex+1; i < listArray.length;i++)
    {
      //if this is on timeline leave as is otherwise you need to reference stage
      removeChild(listArray[i]);
    
      //if the movieclips are in various movieclips then you can do:
      // var parent:DisplayObject = (listArray[i]).parent;
      // parent.removeChild(listArray[i]);
    
    }
    
    listArray = listArray.slice(0,clickedIndex);//returns a new array from start index to end index
    

How to get local time zone name from Ruby in the same way as Java does?

I need to find out local machine time zone name from Ruby (from the TZInfo::Timezone.all_identifiers list of values). I need it so that I could set correctly Oracle database session time zone so that I could handle correctly timestamp with time zone values in the database.

I would like to get the same value that in Java you could get with java.util.TimeZone.getDefault().getID() (which on my computer returns "Europe/Riga"). As far as I have had a look on JDK sources there is platform specific C functions which finds this default time zone.

So when using JRuby then I can call this Java method. But I need a solution that I can use with MRI.

I tried to use Time.now.zone but it returns different results (in my case "EET" or "EEST") depending on if currently is daylight saving time or not. So I really would need to get in the previously mentioned location format (like "Europe/Riga") which correctly specifies dates when switching to daylight saving time happens.

Any suggestions?

From stackoverflow
  • JRuby returns EET/CDT-like values for compatibility reasons, since C-Ruby does the same. But, since JRuby can easily call the Java layer, you could just call it like tat:

    require 'java'
    id = java.util.TimeZone.getDefault().getID()
    

    or, in more Ruby-like syntax:

    require 'java'
    id = java.util.TimeZone.get_default.get_id
    

    Alternatively, you could use JodaTime:

    require 'java'
    id = org.joda.time.DateTimeZone.getDefault.getID
    
    Raimonds Simanovskis : Yes, in JRuby it's easy. But I would like to get the same result in MRI (original C based Ruby interpreter).
    VVSiz : I don't think MRI has a way to do that without some tricks or native calls. On Linux, it is easy, just "cat /etc/timezone".

What version of StructureMap can I use in webform app (Net 2.0)

Hi Guys,
I am bit confuse. I would like to use StructureMap in my webform app, but it is still Net 2.0. I am not really sure which version I should use.

Anyone using StructureMap for Net 2.0 project? Which version?

Thanks for any response. X.

From stackoverflow
  • I believe that you have to use Structure Map 2.0 or earlier.

BlackBerry - Facebook connect from application

i m developing a blackberry app which requires facebook login. can i login to facebook via my app without stopping the app in the middle. means can i login to facebook in parallel with my application, without interrupting it.

From stackoverflow
  • You would need to make your program multithreaded, and handle the connection to facebook in another thread.

  • It all depends whether the User of your application has already grants your application the access to his/her profile. If it is true, you would then have the session key (valid and non-expiring) for the User and no login is required. Furthermore, some methods do not require session at all (cf. Facebook API documentation).

    tek3 : what if the user has not granted the request..?? how to proceed further in that case..
    Eki : Unfortunately there is not much your app can do as Desktop application (Facebook Connect) requires session key. (http://wiki.developers.facebook.com/index.php/Category:Sessionless_API)

How does a syscall get located in Linux?

I'm trying to add a new syscall in Red Hat 8.0 and I'm confused about some aspect of the mechanism. I've been following this guide: http://www.linuxjournal.com/article/3326 which details the steps of updating the syscall table in entry.S and unistd.h.

However, I can't seem to figure out how the compiler actually finds where the syscall is implemented from this information. Obviously there's something that involves #includes, but I can't find any indications of includes being made, nor locate many of the syscalls in the code. What do I need to do for my syscall to be found?

From stackoverflow
  • Maybe this Guide will help you.

  • The C library provides functions which happen to look like system calls. What actually happens is that the C library function is called and then it makes the system call.

    If you add a new system call, then to make it easily usable you would need to add it to the C library and recompile that too.

    Or you can use the syscall function and macros provided by the C library: syscall and _syscall.

    Try man syscall and man _syscall to see details.

Snow Leopard Reference Library

Hi, Does anyone know how to download all the developer reference documentation for snow leopard. For some reason Apple changed it so that whenever you wanted a document you have to get it form their website. I don't have an internet connection all the time so I would like to have all of the reference documentation locally on the desktop.

How would I obtain all the documentation (i.e. is there a batch download?)

Thanks for the help.

From stackoverflow
  • I'm not on my Mac right now, but IIRC there is an option in Preferences->Documentation, near the bottom, to enable them offline.

  • Go to XCode preferences, select the Documentation tab. Click on the "Check and Install Now" button. After many minutes, depending on your Internet connection speed, the reference documentation will be ready to use offline.

C++ university course

Hi there

Do you know any university which has his C++ course available online? I'm looking for something similar with MIT style(lecture notes, projects and examples, assignments, exams, solutions and video content )

this is what I've found on MIT, but id doesn't have video content.

From stackoverflow
  • Most universities will be quite protective of such things. I suspect the best thing to do would be to A) find a project you want to work on and B) buy a very good book.

    dole doug : MIT does this already for a lot of his course : http://ocw.mit.edu/OcwWeb/web/courses/courses/index.htm
  • I don't know about C++ specifically, but in terms of video lectures on programming concepts, check out this:

    http://academicearth.org/subjects/computer-science

  • use iTunes U search for the course in the stanford they have a course on itunes for c++

Cropping an image using VBA

I need to crop an image on a Powerpoint slide using VBA - in my particular case I'm cropping from the top and left edges.

Can anyone offer any advice?

From stackoverflow
  • Found it:

    With ActivePresentation.Slides(3).Shapes(1) 
      .PictureFormat.CropLeft = 10
      .PictureFormat.CropTop = 10
      .PictureFormat.CropRight = 10
      .PictureFormat.CropBottom = 10
    End With
    

How can i hide MPMoviePlayer controls?

Hi ...

i want put a movie at my application starting but i want hide the movie controls like (stop , play , next and ... ) here is my code :

#import <MediaPlayer/MediaPlayer.h>



-(void)viewDidLoad
{
     NSBundle *bundle = [NSBundle mainBundle];
     NSString *moviePath = [bundle pathForResource:@"myvideo" ofType:@"mp4"];
     NSURL *movieURL = [[NSURL fileURLWithPath:moviePath] retain];
     MPMoviePlayerController *IntroMovie = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
     [IntroMovie play];
}
From stackoverflow
  • Ok, i figured it out.

    Code:

    IntroMovie.movieControlMode = MPMovieControlModeHidden;
    
  • but it is deprecated now.

Binding a Dictionary to the DataGridView in C#?

I have a dictionary item as below

Dictionary<string, List<StrikePrice>>

where

public class StrikePrice
{
    public string Strike { get; private set; }
    public string Price { get; private set; }

    public StrikePrice(string strike, string price)
    {
        Strike = strike;
        Price = price;
    }
}

and I wish to assign this dictionary to the DataGridView

this.dataGridViewTest.DataSource = listSmiles;

I understand that a dictionary can't be assigned to the the datasource as this doesn't derive from the IList interface.

Is there any way I can assign this dictionary element to the datagrid?

From stackoverflow
  • If the question relates to WPF or silverlight, this article gives a solution.

    I've been using it and it performs well, even for large numbers of columns.

    tush1r : @Phillip: This is for Winforms application.
  • Have you tried using the Values property of the Dictionary?

    this.dataGridViewTest.DataSource = listSmiles.Values
    
    tush1r : @Kane: I tried doing this, however this didn't work.

Can .NET Ria service push data from server to client?

Can the .NET RIA Service automatically push data to the silverlight client without the client polling the server at all?

I want a feature similiar to wcf duplex polling.

From stackoverflow

Data Generation Plan connected fields

Is it possible to have 2 fields with the same data for a Data Generation Plan? For example, the table aspnet_roles has 2 fields RoleName and LoweredRoleName and I want them to show the same data.

From stackoverflow
  • Sure, but maybe not in the way you're expecting. If you want random strings in one and a lowercase version in the other then not really, but if you have a table available that the sequential data-bound generator can use, you can get something similar.

Listen for history events in FireFox?

From the context of a FireFox extension...

Is there some way to be notified of back/forward/goto/reload/etc. "History Events"? I'm not looking for a way to cancel or change them, just to be made aware of them.

My best solution thus far has been to hook into the UI elements responsible (menuitems and buttons) for triggering history navigation. This obviously doesn't work terribly well in the face of any but the most tightly controlled FireFox installations as all it takes is one extension doing:

gBrowser.webNavigation.goBack()

... to ruin my day, to say nothing of webpages themselves playing games with the history.

From stackoverflow
  • You need to implement nsISHistoryListener and register your implementation as a session history listener for the <browser> you're interested in. Googling shows that people have done this already, so you should be able to find extensions that do this to copy their code.

    Kevin Montrose : Ah, the joys of COM (or XPCOM, whatever) in javascript...

ways of place a skype call automatically

I want to place a skype call automatically and I tried different ways:

first I used a api with python which worked for me with an older skype version, after the update it's not working anymore.

then I tried to install a plugin in firefox, set the firefox settings and placed a file in /usr/bin that should call skype number when clicking a skype link. I tried this with calling that skype link with a small script. Not working :(

do you know any other options? I'm using ubuntu 8.10 intrepid

From stackoverflow
  • Did you look at the official APIs? There are APIs for COM (not an option on Linux, I guess?) and Java (which you might try).

    And there is also an official Skype API for Python. If that's what you used, and it fails with the new Skype version, I suggest you bug the Skype developers about that.

MPMediaPickerController, MPMediaItems, and NSData

I was wondering if Apple allowed you to access the MPMediaItem's raw data as an NSData object. If you can, thats great and I would like to know how. If you cannot, then Apple is way too over-protective, and my app that i started is utterly useless. Also if you cannot, Is there any hacky workarounds? I don't care if Apple doesn't accept my app as it would still be cool if me and my friends all had it.

Thanks, Conrad

From stackoverflow
  • You can't, and there are no workaround. An MPMediaItem is not the actual piece of media, it is just the metadata about the media item communicated to the application via RPC from another process. The data for the item itself is not accessible in your address space.

    I should note that even if you have the MPMediaItem its data probably is not loaded into the devices memory. The flash on the iPhone is slow and memory is scarce. While Apple may not want you to have access to the raw data backing an MPMediaItem, it is just as likely that they didn't bother dealing with it because they didn't want to invest the time necessary to deal with the APIs. If they did provide access to such a thing it almost certainly would not be as an NSData, but more likely as an NSURL they would give your application that would allow it to open the file and stream through the data.

    In any event, if you want the functionality, you should file a bug report asking for.

    Also, as a side note, don't mention your age in a bug report you send to Apple. I think it is very cool you are writing apps for the phone, when I was your age I loved experimenting with computers (back then I was working on things written in Lisp). The thing is you cannot legally agree to a contract in the United States, which is why the developer agreement specifically prohibits you from joining. From the first paragraph of the agreement:

    You also certify that you are of the legal age of majority in the jurisdiction in which you reside (at least 18 years of age in many countries) and you represent that you are legally permitted to become a Registered iPhone Developer.

    If you mention to a WWDR representative that you are not of age of majority they may realize you are in violation of the agreement and be obligated to terminate your developer account. Just a friendly warning.

    ckrames1234 : My dad did all that stuff and technically, He's the iPhone Developer, so it's all good
    ckrames1234 : Also, if I were to take the jailbreak path, the music, is stored in /var/mobile/Media/iTunes_Control/Music/, and it is a bunch of randomly named folders with randomly named songs in it. How to decipher the names would be the challenge but its probably in one of the scattered SQLite databases in the "iTunes_Control" folder. Once I build the Toolchain, thats were i'm going next.
  • Hi, you can obtain the media item's data in such way:

    -(void)mediaItemToData { // Implement in your project the media item picker

    MPMediaItem *curItem = musicPlayer.nowPlayingItem;
    
    NSURL *url = [curItem valueForProperty: MPMediaItemPropertyAssetURL];
    
    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL: url options:nil];
    
    AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: songAsset
                                           presetName: AVAssetExportPresetPassthrough];
    
    exporter.outputFileType = @"public.mpeg-4";
    
    NSString *exportFile = [[self myDocumentsDirectory] stringByAppendingPathComponent:           
                                                                   @"exported.mp4"];
    
    NSURL *exportURL = [[NSURL fileURLWithPath:exportFile] retain];
    exporter.outputURL = exportURL; 
    
    // do the export
    // (completion handler block omitted) 
    [exporter exportAsynchronouslyWithCompletionHandler:
      ^{
     NSData *data = [NSData dataWithContentsOfFile: [[self myDocumentsDirectory] 
                                         stringByAppendingPathComponent: @"exported.mp4"]];
    
     // Do with data something
    
       }];
    

    }

    This code will work only on ios 4.0 and later

    Good luck!

    GhostRider : i try this code in ios 4.0 but it not work there below is source of code

.xib not loading right (iPhone)

For some reason when I load a new view (from a .xib) it'll load the class files, BUT NOT the .xib!!

Here's my code:

login *lo =[[login alloc] initWithNibName:@"login" bundle:nil];
self.log = lo;
UIViewController *loginview = log;
[UIView setAnimationTransition:UIViewAnimationCurveEaseIn forView:self.view cache:YES];
[loginview viewWillAppear:YES];
[self.view removeFromSuperview];
[self viewWillDisappear:YES];
[self.view insertSubview:loginview.view atIndex:0];
[self viewDidDisappear:YES];
[loginview viewDidAppear:YES];
[UIView commitAnimations];
[log release];
From stackoverflow
  • Perhaps this question discusses what you're experiencing? Sorry if I misunderstood your question, it's kind of low on the details.

    Matt S. : kinda, however after checking everything it seems that none of that stuff is the problem
    Matt S. : Ok, after some debugging it turns out that when I run that code it doesn't add the view (login), instead it loads the window (in the delegate)

Converting Python code to PHP

What is the following Python code in PHP?

import sys

li = range(1,777);

def countFigure(li, n):
        m = str(n);
        return str(li).count(m);

# counting figures
for substr in range(1,10):
        print substr, " ", countFigure(li, substr);

Wanted output for 777

1   258
2   258
3   258
4   258
5   258
6   258
7   231
8   147
9   147
From stackoverflow
  • It's been a while since I did any Python but I think this should do it. If you could clarify what str(li) looks like it would help.

    <?php
    
    $li = implode('', range(1, 776));
    
    function countFigure($li, $n)
    {
        return substr_count($li, $n);
    }
    
    // counting figures
    
    foreach (range(1, 9) as $substr)
        echo $substr, " ", countFigure($li, $substr), "\n";
    
    Greg : Thanks I've edited to correct

Run command pipes with subprocess.Popen

How to run the following command using subprocess.Popen?

mysqldump database_name table_name | bzip2 > filename

I know os.system() can do the job but I dont want to wait for the dump to finish in main program.

From stackoverflow
  • You want the shell=True option to make it execute shell commands:

    import subprocess
    subprocess.Popen("sleep 4s && echo right thar, right thar",shell=True);
    print 'i like it when you put it'
    

    which yeilds:

     I like it when you put it
     [4 seconds later]
     right thar, right thar
    

How to sign code with only a .SPC file from GoDaddy?

I use InstallShield 2010 which requires a SPC/PFX and a PVK file to sign my files. I just got a GoDaddy Code Signing CERT but all they gave me was a SPC file. I right-clicked it and installed it in Windows 7. I assume the PVK file is somewhere on this system but I cannot find it using the Certificates MMC, etc.

So how will I use this SPC file in InstallShield to sign my files without have a PVK file? I can view the certificate in "My Store" (Personal certs) and export it to a .CER or P7B but the PFX option is grayed out so I can't export the PVK for some reason.

Is it possible to sign using InstallShield without a PVK file? I'm also concerned what will happen if I have to reload this computer, how will I install this code signing .SPC again with no PVK file? I'm used to keeping PFX files on my backup system. It's a 3 year cert so I imagine in 3 years I am going to reload this computer.

From stackoverflow
  • The problem was with GoDaddy and their key generation not working with IE 8. After I used FireFox I was able to run the course and then export the required file (p12) etc.

How can i restrict Texting in iPhone if it is in Motion of 10MPH?

Hi All,

could you please give me some information For how to develop an application/Service for iPhone/Smart phone to restrict Texting in device if it is in Motion of 10MPH speed.

Thanks in Advance.

Bhramar

From stackoverflow
  • From my understanding, without "special" apple support, an iPhone application is only running when it is the foreground -- and if your application is running then it might as well be an animated lighter and the speed of movement doesn't matter (unless, perhaps the flame should burn higher or something).

    At least some months ago, this was the summation of the limitation on an iPhone application. If I recall correctly, a "lo jack" program had special support at the time.

  • If I understand you right, your intent is to restrict use while in a moving vehicle.

    This would be tantamount to implementing an inertial navigation system on a platform with accelerometer support but no gyroscope to provide rotation sensing; which is pretty much a non-starter.

    Kristopher Johnson : Accelerometer data isn't needed. GPS should be sufficient: just get position periodically, and calculate speed from that.
    Matt : An accelerometer wouldn't be appropriate here because accelerometers only detect changes in speed. An iPhone traveling at 10MPH is indistinguishable from an iPhone traveling at any other constant speed.
  • Use the GPS api to locate your iPhone at certain intervals, and use the location difference and the time sampling interval to get an estimate of your speed. When your speed exceeds 10MPh, you could restrict texting within your app, doing it all across the device is somewhat close to impossible.

Windows impersonate [SQL, ASP.NET, C#]

Hi guys, I try use windows impersonate in asmx web service to read sql database.

  1. I make new account in windows.
  2. Set permission to full control on database file ORLDatabase.mdf.

Now I call method GetDataSet, but it finish on client side with this error:

System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Exception: CREATE DATABASE permission denied in database 'master'. An attempt to attach an auto-named database for file D:\work\WebService\App_Data\ORLDatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

I check windows impersonate in code with WindowsIdentity.GetCurrent(), the current identity is good.The Account have full control on databse file,but it finisch with error. Can somebody help me, I dont't work with sql. I try first google, but don't find solution which solve my problem. Thank

public class Service : System.Web.Services.WebService
{
    public TicketHeader Ticket;
    public DataSet ds;

    private string machine = "pcName";
    public string userName = "********";
    public string password = "*********";
    public IntPtr token; 
    public WindowsImpersonationContext impersonationContext;

    [DllImport(@"D:\Windows\System32\advapi32.dll")]
    public static extern bool LogonUser
    (string lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out int phToken);
    public void Login()
    {
        int returnedToken;
        if (LogonUser(userName, machine, password, 3, 0, out returnedToken))
        {
            token = new IntPtr(returnedToken);
        }

    }

    [WebMethod]
    public DataSet GetDataSet(string id)
    {
        DataSet ds = null;

        Login();
        impersonationContext = WindowsIdentity.Impersonate(token);

        SqlConnection conn = null;
        SqlDataAdapter da = null;
        try
        {
            string sql = "Select * from Table";
            conn = new SqlConnection(@"Data Source=.\SQLEXPRESS; Integrated Security=True;" +
                    @"AttachDbFilename=|DataDirectory|\ORLDatabase.mdf;");
            conn.Open();
            da = new SqlDataAdapter(sql, conn);
            ds = new DataSet();
            da.Fill(ds, "Table");
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);

        }
        finally
        {
            if (conn != null)
                conn.Dispose();
        }

        impersonationContext.Undo();
        return ds;
    }
}
From stackoverflow
  • The windows account you created needs to be a login on the database engine as well. In SQL Server Management Studio: servername-->Security-->Login | Right Click --> New Login. I doubt file permissions are sufficient.

    m.duriansky : thank you , it work

Firefox plugin or way to monitor ALL request data, including headers and content downloaded to browser

I am having problems getting ALL of the information that is downloaded to a browser. For example, I want a plugin, ideally a firefox plugin to download the HTML content and monitor when I get a 302 redirect, and all header information.

So far, use Live HTTP Headers and Firebug. Both are fine.

With Live HTTP headers, I can't monitor the data that is downloaded (e.g. the html data) Firebug is worse, because I can't monitor the headers and I can't monitor the full requests. For example, Firebug won't show you all of the content that is downloaded, just the last set of requests. E.g. redirects will clear the Firebug net monitoring.

I am on win32

From stackoverflow
  • Have you looked at Fiddler?

  • While not a firefox plugin, Ethereal is great. Start it up and do your browsing as usual.

  • Try Tamper data firefox add-on, an extension to track and modify http/https requests.

    You can find a nice tutorial here.

    Firebug + Tamper Data is the best couple of firefox tools I cannot live without.

    Berlin Brown : Perfect solution. Thanks a lot. It does have a bug though. It doesn't download the content for javascript client side redirects. E.g. I get a -1 error for body onload=document.location=http://url.com It won't download that content. But that is OK.
  • Your best bet, FireBug. Does everything you can ever want and more...

  • Ethereal (wireshark) is nice, but also complicated. Last I used it with HTTP, it didn't support decoding of HTTPS (secure) packets, though that may have changed. There are actually ton's out there now, but I personally like / use HTTPFox [https://addons.mozilla.org/en-US/firefox/addon/6647/].

TreeNode Image Overlay

I have an imagelist of about 30 images, and 3 images I'd like to be able to overlay on top of the 30 when a TreeNode is in a particular state. I know that a C++ TreeItem can do this with the TVIS_OVERLAYMASK as such:

SetItemState(hItem,INDEXTOOVERLAYMASK(nOverlayIndex), TVIS_OVERLAYMASK);

Is there any mechanism to achieve similar results in .NET?

From stackoverflow
  • I don't know of a way to do the overlay automatically, but you could do this with an owner drawn tree node.

  • I see this question is still getting views, so I'll post the implementation of what David suggested.

    internal class MyTree : TreeView
    {
        internal MyTree() :
            base()
        {
            // let the tree know that we're going to be doing some owner drawing
            this.DrawMode = TreeViewDrawMode.OwnerDrawText;
            this.DrawNode += new DrawTreeNodeEventHandler(MyTree_DrawNode);
        }
    
        void MyTree_DrawNode(object sender, DrawTreeNodeEventArgs e)
        {
            // Do your own logic to determine what overlay image you want to use
            Image overlayImage = GetOverlayImage();
    
            // you have to move the X value left a bit, 
            // otherwise it will draw over your node text
            // I'm also adjusting to move the overlay down a bit
            e.Graphics.DrawImage(overlayImage,
                e.Node.Bounds.X - 15, e.Node.Bounds.Y + 4);
    
            // We're done! Draw the rest of the node normally
            e.DefaultDraw = true
        }
    }