Sunday, March 20, 2011

Is there a way to import blockbuster.com queue into Netflix?

Is there a utility or website that takes the all of the movies in a blockbuster.com queue and adds the corresponding movies (blu-ray and all) to Netflix.com?

From superuser
  • While Netflix has a published API for manipulating your account, doing searches, etc, Blockbuster doesn't seem to have such a thing. However!

    You can save an HTML template of your Blockbuster queue, and then use Netflix's API to work with your queue there.

    This blog post describes an outline of doing this, and links to a php program that is in early stages of development.

Make files dump into a fence by default

I want to make any files that get dumped onto my desktop go into an "Unfiled" or "Misc" fence by default with Fences, is there a way to do this?

From superuser
  • I wish this existed as well, but unfortunately auto-fencing is not yet supported. It doesn't hurt to send in a request for it though!

    Ivo Flipse : That would be even more awesome ;-)

PHP - Extremely light templating system

Hi

does anyone know a php templating system that is very simple, something like almost as simple as str_replace("{variable}", $variable); ?

I need this for a series of textareas in the administration panel, where the site admin should change templates for various elements of the website (not complex stuff like pages etc, just blocks of content)

From stackoverflow
  • /**
     * Renders a single line. Looks for {{ var }}
     *
     * @param string $string
     * @param array $parameters
     *
     * @return string
     */
    function renderString($string, array $parameters)
    {
        $replacer = function ($match) use ($parameters)
        {
            return isset($parameters[$match[1]]) ? $parameters[$match[1]] : $match[0];
        };
    
        return preg_replace_callback('/{{\s*(.+?)\s*}}/', $replacer, $string);
    }
    
    Emil H : Neat. :) It should be said that it's php 5.3+ only, though.
    alex : You'll need to be running PHP 5.3 to use this. Otherwise it is not so elegant.
    willell : Try to avoid this if you can. Regexes are resource-expensive.
    Gordon : Same as Fabien Potencier's in [Design patterns revisited with PHP 5.3](http://www.slideshare.net/fabpot/design-patternrevisitedphp53) (page 45)
    efritz : It's actually a method from the Symfony2 framework.
    Alex : nice. is there a way to make this work for php 4 ?
    alex : @Alex You'll need to make a separate function for the callback (outside of the scope you are currently in).
    Gordon : @efritz figures because Fabien is the author of Symfony2
  • $findReplaces = array(
        'first_name' => $user['first_name'],
        'greeting' => 'Good ' . (date('G') < 12 ) ? 'morning' : 'afternoon'
    );
    
    $finds = $replaces = array();
    
    foreach($findReplaces as $find => $replace) {
        $finds[] = '{' . $find . '}';
        $replaces[] = $replace;
    }
    
    $content = str_replace($finds, $replaces, $content);
    
    Gordon : why dont you just include the curly braces, e.g. `{{first_name}}` in the array keys and simply do `str_replace(array_keys($findReplaces),$findReplaces,$content)`

Truncate ASP.NET MVC C#

I'm displaying some content using the following bit of code:

<% foreach ( var m in ViewData.Model) { %>

<div class="content">
<%= m.article %>
</div>

Which shows a news article from my database. What I want to do is truncate the story to be smaller, how do would I do this? Also the article column contains HTML tags such as <p> so therefore splitting up the article purely on character numbers would cause issues.

Any ideas on where to start? I'm new to MVC.

Thanks

From stackoverflow
  • This is not a simple problem, but you can start by using the HtmlAgilityPack.

    This is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT (you actually don't HAVE to understand XPATH nor XSLT to use it, don't worry...). It is a .NET code library that allows you to parse "out of the web" HTML files. The parser is very tolerant with "real world" malformed HTML. The object model is very similar to what proposes System.Xml, but for HTML documents (or streams).

    Once you have your DOM in memory you can then extract or truncate elements in a way that will not break the DOM structure, e.g., you can remove entire <p></p> nodes, or just truncate some fo the text within that node.

    Cameron : Hi, I don't want to download any additional stuff. I want to use purely the default framework.
    RedFilter : The default framework does not contain anything to handle the messiness that is HTML. If you know that your content is valid XHTML (or you can convert it to be), then just use the XML classes in C# to do something similar.
    Cameron : Yes it is valid XHTML. Would you be able to explain how to do that. As like I said I'm new to C# and MVC and so not really sure what you mean.
    Paco : Or copy paste the code from the library you don't want to download.
    RedFilter : @Paco: HtmlAgilityPack is provided as source.
  • Do you have control over how articles are submitted? Perhaps you can ask for a short intro/summary. I believe WordPress does it.

    Or have the user insert a marker which signifies the end of intro/summary. something like:

    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    <!-- END INTRO -->
    <p>Ut malesuada porttitor consectetur. </p>
    

    You can display it without any consequences and still "split" the article programmatically.

Javascript select drop down menu onchange not firing properly

my onchange isn't firing the javascript method properly.

Select code (in HTML file)

<select id="crit_1" onchange="crit1Update()">
    <option value=null>Criteria 1</option>
 <option value="major">Major</option>
 <option value="grad">Graduation Year</option>
</select>

crit1Update() code (in external filter.js file in same folder as HTML file containing the above with the following code in head of HTML

<script type="text/javascript" src="filter.js">
</script>

function crit1Update() {
 var crit1 = document.criteria.getElementsByID("crit1");
 var criteria1 = crit1.options[crit1.selectedIndex].value;
 alert("criteria1"); // this is never firing, so this isnt getting called
 if (criteria1 == null) {
  // eventually set all other lists to null in here as well
  filter(null,null,null,null,null,null)
            // the above returns all the resumes 
            // (this is eventually going to filter resumes)
 }
 else if (criteria1 == "major") {
  alert("Major!");
 }
}

Are there any glaring or not glaring errors that I am missing? I dont see why the alert("criteria1" isnt being called. I come from a java background and this is my first foray into JS, so I may be missing something simple.

Thanks for any help.

From stackoverflow
  • Your <select> ID is "crit_1" and your function is looking for ID "crit1" (no underscore).

    It would probably be a better idea to pass the <select> element as a reference to the function, eg

    JavaScript

    function crit1Update(crit1) {
        var criteria1 = crit1.options[crit1.selectedIndex].value;
    

    HTML

    <select id="crit1" name="crit1" onchange="crit1Update(this)">
    
    Ross Larson : thank you very much!
    klox : @Ross: read some tutorial for the project that do you want to built up. so it can prevent the mistake during type the script.
    Ross Larson : @Klox, that is probably a good idea. I have been going back and forth between my js doc, html doc and www.w3schools.com
    klox : yah w3schools is a place for beginner like me too.keep trying and learning.;)
  • There is a typo in this method call:

    document.criteria.getElementsByID(
    

    should be

    document.criteria.getElementById(
                                ^  ^ no "s" and lower case "d"
    

    also make sure the id matches your HTML element e.g. "crit_1"

    Phil Brown : Good catch on the first typo, but you also missed the "s" - `getElementsByID` should be `getElementById`
    Ross Larson : Thank you very much
    scunliffe : thanks @Phil Brown I was so focused on the "D" I missed the s.

How to return a data.frame with a given name from a function?

Assume I have a function that reads data from a MySQL table, manipulates it and returns some data.frame. Note the function is just an example whose functionality does not matter itself..., E.g.:

addRowSd <- function(table,con,pattern="^Variable") {

dframe <- dbReadTable(con,table)
cn <- colnames(dframe)
qs <- subset(x, x  %in% grep(pattern, x, value=TRUE))
dframe$qsd <- sd(t(dframe[,c(qs)])) 

return(dframe)
}

mydf$sd <- addRowSd(...)

I end up with a data.frame called mydf. Now I´d like to do to this to a character vector of SQL table names AND name the returned dataframes correspondingly. If I just use

x=lapply(MySQLtablenames,addRowSd,con)

I´ll get some list called x. Of course I could unlist and rename everything the way I´d like to, but my question is:

How can I make lapply (or another comparable function) return multple single dataframes or at least a list that contains some names derived from my character vector "MySQLtablenames"?

From stackoverflow
  • just found an answer on my own:

    assign("somename",dframe,envir = .GlobalEnv)
    
    Marek : You could run into scoping issues with this. E.g if you want to use function inside another function, then your data.frame is created in global environment. You could play with `parent.frame` to improve your method.
    Gavin Simpson : In both your examples, you are inserting a DF into a list (or `lapply` returns a list). In those cases, the name of the object that is the DF is irrelevant, is it not. What matter is the `names` for the list components. If I were doing this, I'd store the DFs in a list, set the names on the list after the table names, as per Marek's comment above, and then work with the list. If you want to refer to the individual DFs by name, use `with(x, DF.name)` where `x` is list returned by `lapply` and `DF.name` is the name of the DF you want to access or some function applied to it.
    ran2 : @Marek, currently the only thing that runs into scoping issues is my brain. the parent.frame stuff is all new to me and I do not get it yet, but thx for pointing to it. What will cause the scoping issues? Loading to much data from the database to the same (global) environment?
  • If you supply sapply a character vector, it will name the items in the returned list by the supplied character vector (USE.NAMES default to TRUE)... I would also use simplify=FALSE as depending on the data.frames returned you may get unpredictable results

    x=sapply(MySQLtablenames,addRowSd,con, simplify=FALSE)
    

Best python/Django code generator?

Hello, very quick question. I am wondering if there are any software Django software that generates python coding automatically. If there are any, please let me know.

From stackoverflow
  • I have never heard of python code generators. Python is a dynamic language where you can do almost anything. Instead of relying on static code generators known from the Java world, I would argue that you can write a couple of equivalent Python lines in most cases which is way more convenient.

    In case you are looking for a Python lexer/parser, try pyparsing.

    Shehzad009 : Ok I will check it out

In Eclipse, hide files ending in tilde `~`

Eclipse, by default, hides files that begin with . in the Package Explorer, Navigator, and other file views (e.g. .classpath, .settings, etc). Is it possible to hide files which end in ~ (e.g. somefile.txt~).

Yes, these are Emacs backup files, created while using both Eclipse and Emacs on the same project.

From stackoverflow
  • use backup-directory-alist in your emacs config to stash away the emacs backups in a different directory

    Chadwick : In the end I went with the Eclipse setting, but I find this a useful suggestion - I just happen to like where the backups are, but don't want to see them.
  • In the package explorer toolbar, there should be an icon that makes a dropdown menu appear; in that menu, select "Filters…".

Scala assigning vals

Why isn't it possible to have this:

def main(args:Array[String]) {
  val whatever:String // have it uninitialized here

  if(someCondition) {
     whatever = "final value" // initialize it here
  }
}

I don't understand why this shouldn't be legal.I know that I can make it a var,but why do we have to initialize the val exactly when we declare it? Doesn't it seem more logical to be able to initialize it later?

From stackoverflow
  • You can do:

      val whatever =
        if (someCondition)
          "final value"
        else
          "other value"
    
  • Because the purpose of 'val' is to signal to the reader (and the compiler): "This value will stay what it is initialized to until it goes out of existence"

    This doesn't make much sense without initialization.

    Of course one could dream up somehting like val(3) which allows three assignement to a variable, but I don't think that would be of much use.

  • Use lazy vals like so:

    def main(args:Array[String]) {
      lazy val whatever:String = if (someCondition) "final value" else "other value"
    
      // ...
    
      println(whatever) // will only initialize on first access
    }
    
    Zwirb : The assignment inside the if will return Unit. An if without an else clause will also return Unit. I think you example won't compile...
    Max A. : Read before submit... You're right. Corrected.
  • In addition to what others have said, note that Java allows "blank final" "variables", which is a feature I kinda miss:

    final Boolean isItChristmasYet;
    
    if (new Date().before(christmas)) {
        isItChristmasYet = Boolean.FALSE;
    } else {
        isItChristmasYet = Boolean.TRUE;
    }
    

    However, thanks to data flow analysis in the compiler, javac wouldn't let you leave your whatever variable unassigned if someCondition doesn't hold.

    Geo : Yeah, this is what I miss from Java too.
    Zwirb : Out of curiosity, what exactly do you gain by having the uninitialized variable pre-declared? It's not as if you could use it in any way before it's actually initialized...
    Alex Cruise : It's a stylistic thing, I used to declare all my locals up-front at the top of their scope. I probably still would--at least sometimes--if Scala had blank vals. :)
    Kevin Wright : What's wrong with `final boolean isItChristmasYet = ! (new Date().before(christmas))` ?
    Alex Cruise : I knew someone would golf me. :) Nothing, but this is a trivial example in a style that's suited to more complex situations.
  • The Java solution is actually a workaround to the problem that not all expressions return values, so you can't write this in Java:

    final String whatever = if (someCondition) {
        "final value"
    } else {
        "other value"
    }
    

    Increasingly, the trend in Java is to use the ternary operator instead:

    final String whatever = someCondition ? "final value" : "other value"
    

    Which is fine for that limited use case, but totally untenable once you start dealing with switch statements and multiple constructors.


    Scala's approach is different here. All object construction must ultimately pass through a single "primary" constructor, all expressions return a value (even if it's Unit, equivalent to Java's Void), and constructor injection is strongly favoured. This results in object graphs being cleanly built as a Directed Acyclic Graph, and also works very nicely with immutable objects.

    You also want to be aware that declaring and defining variables in separate operations is, in general, a bad practice when dealing with multiple threads - and could leave you vulnerable to exposing nulls and race conditions when you least expect them (though this isn't really a problem during object construction). The atomic creation of immutable values is just one aspect of the way in which functional languages help to to deal with concurrency.

    It also means that the Scala compiler can avoid some of the hideously complicated flow analysis from the Java language spec.

    As previously stated, the Scala Way™ is:

    val whatever =
      if (someCondition)
        "final value"
      else
        "other value"
    

    An approach which also scales up to other control structures:

    val whatever = someCondition match {
      case 1 => "one"
      case 2 => "two"
      case 3 => "three"
      case _ => "other"
    }
    

    With a bit of Scala experience you'll discover that this style helps the compiler to help you, and you should find yourself writing programs with fewer bugs!

PHP Regular expression

I need to add href=" before an http:// if this http:// doesn't follow href=" or src="

Following code partly works. Partly means it considers <a href=" only but not src="

$str= preg_replace( 
    "/(?<!a href=\")((http|ftp)+(s)?:\/\/[^<>\s]+)/i", 
    "<a href=\"\\0\"> target=\"blank\">\\0</a>", 
    $str
);

Thank you guys in advance for your reply.

From stackoverflow
  • $str= preg_replace( 
        "/(?<!a href=\")(?<!src=\")((http|ftp)+(s)?:\/\/[^<>\s]+)/i", 
        "<a href=\"\\0\"> target=\"blank\">\\0</a>", 
        $str
    );
    
    David : works well. Thank you.

QTreeview mousePressEvent implementation prevents selection of items

Hello all I have class that inherited from Qtreeview and I implement simple ( empty ) mousePressEvent function
But whenever I try to do this , the selection of the items in the Qtreeview are disabled , when I remove this function everything is working fine
What im missing here ?
Here Is the code:

void MyTreeWidget::mousePressEvent(QMouseEvent *event)
    {   
        QModelIndex index =  this->indexAt(event->pos());
        QAbstractItemModel *model = this->model();
        QMap<int, QVariant> ItemData = model->itemData(index);
        QMap<int, QVariant>::const_iterator i = ItemData.constBegin();
        while (i != ItemData.constEnd()) {
            QString k = QString::number(i.key());
            QString v = i.value().toString();

         ++i;
        }
        if (event->button() == Qt::LeftButton) {
             QByteArray itemData ;
             QString urlTo;
             itemData.append(urlTo);
             QDrag *drag = new QDrag(this);
             QMimeData *mimeData = new QMimeData;
             mimeData->setData("application/x-dnditemdata", itemData);
             drag->setMimeData(mimeData);

             Qt::DropAction dropAction = drag->exec(Qt::MoveAction);
             if (dropAction == Qt::MoveAction)
             {
                UT::getInstance()->LogToFile("dropAction");
             }


        }
        QTreeView::mousePressEvent(event);
    }
From stackoverflow
  • It's because that when you override a method, the original on is not called anymore. You would have to manually call the mousePressEvent method of QTreeView in the method you created.

    Here is how to do it:

    void YourClass::mousePressEvent ( QMouseEvent * event )
    {
        QTreeView::mousePressEvent(event);
    }
    

    Hope this helps.

    : Hi yeah i did this but now its blocking the drag and drop events again when i remove this method , the D&D and working ..
    Live : Do you confirm that your method is exactly like the one I wrote above or have you added anything at all? If yes, what is it?
    : yes it is see code in the question, now i found the problem , and it is in this code: Qt::DropAction dropAction = drag->exec(Qt::MoveAction); when i comment it it is working but when , what is wrong in this?
    Live : The best for you would be to post a new question, since I never experimented with the Drag & Drop system and that the title of your question does not match your actual problem. Good luck.
    : found the answer thanks for the help

Validating a string in Java

I have a question about validation in Java, I have looked at previous topic and none seem to answer my little problem.

What I am trying to do is validate what is put into a string variable in the constructor but also when a set method is used.

What I need to is If Mr Miss Mrs or Ms is entered, then to set that in a Variable (title) if not then to set title as ''Not set'' and print an error, now I know how to the the last part, its the the validation of what the user is entering into the variable I am stuck in... I have tried using an array but couldn't get it to work and tried if statements, again couldn't get it to function

From stackoverflow
  •     String title = textBoxTitle.getText();
        if(!title.equals("Mr") && !title.equals("Miss") && !title.equals("Mrs") && !title.equals("Ms"))
        {
            // Text is invalid
        }
        else
        {
            // Text is valid
        }
    
    fuzzy lollipop : negative tests are hard to read and understand from a maintence standpoint, why not test of equals || equals || that would be better than a negative test like this.
  • why not just call a small method that does the validation and then sets the value?

    private void validateString(String) {
    
    if string is valid 
     call setter
    }
    
    Anon : or turn this into `validateAndSet()` and call from both ctor and public setter
    fuzzy lollipop : a method name should not have a side affect that isn't expected, this is a terrible name. methods should do one thing and one thing only, the internal workings should be a black box, there is absolutely no reason to have "validate" in the name of the method. All the caller should be concerned with is the end result. if you were going to have it called `isValidPrefix` that then returned a true or false that would be better, as it stands this is horrible.
  • public void setTitle(final String title)
    {
      if (title.matches("^Mrs|Mr|Miss|Ms$"))
      {
        this.title = title;
      }
      else
      {
        this.title = "Not Set";
        System.err.format("%s is not a valid title, expecting Mrs,Mr,Miss,Ms\n", title);
      }
    }
    

    if you want to do case insensitive then change the regular expression to:

    "(?i)^Mrs|Mr|Miss|Ms$"
    

    then you can just lowercase the entire thing and uppercase just the first letter to re-normalize your input to what you really want. Google for "java proper case" to find some pre-written snippets of code.

    A more concise one liner, again case sensitive:

    public void setTitle(final String title)
    {
      title.matches("^Mrs|Mr|Miss|Ms$")) ? this.title= title: this.title= "Not Set";
    }
    
    Necronet : I like this answer better... is quite flexible with Regexp!
  • i'm pretty sure u did something like --

    
       if(title =="Mr."){ blah.. }
    
       do this instead ..
    
       if(title.equals("Mr."){blah..}
        
    Chris : This is what I did do it was when shown the ''title.equals'' I realised what I was doing wrong.
  • Create a set of the words that you care about (capitalize them), and then see if the title falls into the set:

    Set allowedTitles = new HashSet();
    allowedTitles.add("MR");
    allowedTitles.add("MRS");
    allowedTitles.add("MS");
    allowedTitles.add("MISS");
    if (! allowedTitles.contains(textBoxTitle.getText().trim().toUpperCase()) {
       //print exception
    }
    else { title = textBoxTitle.getText().trim());
    
    fuzzy lollipop : checking against capitalization is a bad idea because of unicode, capital letters in unicode can be problematic, lowercase on the other had is normalized to the same characters. also the original question wants them in Proper Case, they don't specify anything about case insensitivity.
    Matthew Flynn : Fair enough. Use toLowerCase() then. I think the downvote is a little harsh, as the concept was to use "contains". If case isn't an issue, then don't bother with it, obviously.

How do I throw away the original image file and just keep the resizes with Paperclip and Rails 3?

I am using Paperclip to, among other things, allow a registered user to upload an avatar for use on thier profile. I want to store a big and small version of the image which will be rmagicked to standard sizes. Now, what i want to do, is store these two standard sizes (:normal and :tiny, for example.) but I do not want to store the :original.

This will be nice for several reasons as I will never display or use any version than the two standard (re)sizes.

From stackoverflow
  • I can't think of an way to do that with Paperclip directly, but you could remove the original manually after creating the record. An example could look like this:

    class Photo
      has_attached_file :photo
    
      after_create :destroy_original
    
      protected
    
        def destroy_original
          # photo.url will look something like /system/photos/1/original.png
          File.unlink("#{Rails.root}/public#{self.photo.url}")
        end
    
    end
    
    NJ : I like this idea, but I am using S3 and my whole intent is to save transfer and storage costs. Not using the local file system also makes it more complicated. I should have said. Thank you, though!
  • What is your reasoning for wanting to delete the files? File storage is so cheap now, that it's not really a valid reason anymore.

    I would advise against deleting the original files. If you ever decide you want to resize the files using Paperclip's rake tasks, you will need the originals.

    NJ : A good question. I plan on only using the avatar images in two sizes. I want them all to be standard so I resize whatever they upload into the two versions. You have a point, I just thought it would be worth implementing if not too difficult. I really mostly wanted to know how, I guess. Maybe it is not an intended use of Paperclip. :) I'll just set a max size so people aren't uploading massive originals! Thanks!

Brown noise on cocoa

Hi,

How can I create a brown noise generator using Cocoa?

BTW Brown noise is similar to pink and white noise and has nothing to do with "The brown note" or anything silly. See http://www.mediacollege.com/audio/noise/brown-noise.html

From stackoverflow
  • I thought I saw some open source white noise Core Audio audio units around the web but I can't find them. In any case I'd start there since the basics are the same. I think Brown noise is just a few differently set parameters / ranges.

    MusicKit might certainly work but Core Audio is part of the OS and likely a lot more CPU-friendly because of that.

distance calculation between two ports with PostgreSQL and Postgis

I'm using PostgreSQL with PostGis and have shapes of all countries loaded.

How can I calculate the shortes sea route between two ports (without intersecting a country shape)

is there a 'standard solution'?

From stackoverflow
  • you could use graph theory so long as you have a set of sea-lane type way-points defined. these would be points along the ship travel lanes with maybe nautical miles between each one indicated. then use a min path algorithm to find the best travel lane.

    of course inreal life this problem has many more variables than just distance i would think.

    dodiddone : hmm, I thought about this but it would require a sheer endless amount of connections
    Randy : so how do you envision the calculation? it can't be the great circle distance, because land masses are in the way. Where should the ship go if it encounters a land mass? tightly follow the coast?

silverlight 4.0 runtime hide grid row.?

Any one have idea how to runtime tide grid row.?

From stackoverflow
  • You cannot set its Visibility, the only way to do it is to set its height to 0. Assuming the grid's name is LayoutRoot and you want to hide the first row:

    LayoutRoot.RowDefinitions[0].Height = new GridLength(0);
    
    Pratik : Thank you.it's working..
    Samvel Siradeghyan : Mark it as right answer if it is working :)

are associations dependent on a database in Rails?

I tested an association on mysql as follows and it works:

User.campaigns

These are the associations in the Models:

Campaign belongs_to :user

User has_many :campaigns

However, when I run it on heroku which uses Postgres, I get the following:

CampaignsController#index (ActiveRecord::StatementInvalid) "PGError: ERROR: column campaigns.user_id does not exist\nLINE 1: SELECT * FROM \"campaigns\" WHERE (\"campaigns\".user_id = 1) \n ^\n: SELECT * FROM \"cam

This is a little worrying because -- if the way I use rails associations depends on the database...hmm...not sure how I can effectively doing any development...thoughts?

From stackoverflow
  • Your error indicates the column doesn't exist. Have you run the migrations on Heroku?

    $ heroku rake db:migrate
    
    Angela : Hi, yeah, I did run them....seemed okay, then ran it again and got an error not related to this model....
    Angela : hmm...thinking maybe the migration didn't run completely then...will check, it looked like it did locally though

Jave Applet: how to simulate an url has been clicked ?

Hi all:

Basically I want my Java Applet to simulate an url has been clicked, once a certain event listener has been executed.

Say, before I have a link in html:

<a href='destinationpage.php?pid=1001' target='rightFrame' />

I'd like to keep the same link to php intact, and when Applet actually invoke the click simulation method, the "target" attribute can also be used to control the behavior.

Similar SO thread found at here, but it doesn't have an answer.

I have little experience in this area, but I am okay with Java programming so long as someone can give me the suggestion of where to get started with.

Many thanks in advance.

Edit:

Okay, tried to get JSObject from the netscape.javascript package to work, added plugin.jar into CLASSPATH, unfortunately I finally got an ExceptionInInitializerError, so this approach failed, unless I can know how to debug in such a mess...

From stackoverflow
  • You could call the url directly in the applet but if you want to reference the link in the page something like the following should work. I have not tested this though.

    getAppletContext().showDocument(new URL("javascript:function() {
      document.getElementById('mylink').click();
    }"));
    }
    
    Michael Mao : @HeathLilley: unfortunately I don't this this would work with my Firefox 3.0.15...
    Michael Mao : @HeathLilley: Actually I know how to mimic a simple plain POST method in Java/Applet, but the "target" attribute is the messy part in this case.
    HeathLilley : getAppletContext().showDocument(new URL("http://www.google.com"), "_blank");
    HeathLilley : Keep hitting the enter button. There is a version of the showDocument method that takes a target argument as a string so if you can get a reference to the link in a javascript method you should be able to get the target value.
    Michael Mao : @HeathLilley : Thanks for the tip and I will try it later :)

Binding a CollectionViewSource within a DataTemplate

'ContentTemplate' is a DataTemplate that displays an object which has a member 'FooList' (an ObservableCollection).

<DataTemplate x:Key="ContentTemplate">
    <ListBox ItemsSource="{Binding Path=FOO}">
        ...
    </ListBox>
</DataTemplate>

I need to be able to filter that FooList using a CollectionViewSource. This is usually been straight forward but I can't seem to get the binding to work within a DataTemplate. I attempted to this:

<DataTemplate x:Key="ContentTemplate">
    <DataTemplate.Resources>
        <CollectionViewSource x:Key="CVS" Source="{Binding Path=FooList}" Filter="FooFilter"/>
    <DataTemplate.Resources>
    <ListBox ItemsSource="{Binding Source={StaticResource CVS}}">

The errors I get from this is:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=FooList; DataItem=null; target element is 'CollectionViewSource' (HashCode=52991666); target property is 'Source' (type 'Object')

Which sounds to me like it's looking for 'FooList' on the CollectionViewSource instead of the object bound to the DataTemplate.

So... how do I get this to look at the correct object?

From stackoverflow
  • I think you need to bind to the view of the CollectionViewSource:

    <ListBox ItemsSource="{Binding Path=View, Source={StaticResource CVS}}">
    
    MarqueIV : Just posted a similar question as well. Tried your solution of explicitly specifying 'View' for the path, but it doesn't work. Also, when you normally bind to a CVS, you don't specify 'View' for the path anyway so I'm not sure what that would have given. Still, I'm not sure why this code doesn't work anyway so there's that too.

Dynamic Crystal Report

Hi All

I want to get the following working, please could someone advise...

Dim rpt As ReportDocument

If (Exists(rpt.ReportDefinition.ReportObjects("crlTitle"))) Then
   txtTitle = CType(rpt.ReportDefinition.ReportObjects("crlTitle"), TextObject)
   txtTitle.Color = mainColour
   txttitle.Text = "Report Title"
End If

Any help much appreciated.

From stackoverflow
  • I've never done anything like that...I'm not sure if it's possible. What will work for sure though is to use a parameter to control the report title. Simply create a parameter and then rpt.SetParamterValue("title", "Some Title")

    Richard : Hi Thanks for your response. and yes, if I was creating all of my reports from scratch then I could do it that way, my reason for asking about doing this in code is that there are already 200+ reports set up and so it is less time consuming executing this through vb code.
    dotjoe : I see...in order to dynamically change the report, you might need to save it after changing that field and then run it. Can you try a `rpt.SaveAs("test.rpt", RptFileFormat)` and then open it and see if the title was actually changed.
    Richard : The problem I have Joe is that the object may not exist on the report so this would throw an error and the report would not load. You get where Im coming from?
  • Since you've identified the problem as "Exists is undefined". Addressing that problem is more straightforward. Try replacing the "Exists" line with:

        If (rpt.ReportDefinition.ReportObjects.Contains("crlTitle")) Then
    

    Were there any other problems?

    Richard : Using this method gives me an IndexOutOfRangeException
    Eric Towers : Having to do this without access to Crystal Reports module (i.e. from Express edition), so the corrected above is probably only close.
  • Here is my solution:

    Dim rpt as ReportDocument
    Dim rptTextObject as TextObject = nothing
    Dim mainColour As Color = Color.Green
    
    Try
        If (rpt.ReportDefinition.ReportObjects("crlTitle") IsNot Nothing) Then
          rptTextObject = CType(rpt.ReportDefinition.ReportObjects("crlTitle"), TextObject)
          rptTextObject.Color = mainColour
          rptTextObject.Text = "Report Title"
        End If
    Catch
    End Try
    

    I do this for each Object on the report that I want to either set text or set colour.

python windows standalone exe file

whenever i build python file to exe file from py2exe, it takes lots of space of minimum 25MB for small project also,it includes all the the python library file. Is there any other way that i can reduce the size.

From stackoverflow
  • No, not really; you need Python shipped with the exe so that it is standalone. It it not common to create exe Files from Python projects, anyway.

    John Machin : "not common" may be true of your computer. In any case it's irrelevant to the OP's question.
    Florian Mayer : I was talking about the Python developer community, that it is not common practice to use py2exe. That does matter.
  • Python programs need python to run. All py2exe does is to include full python and all libraries you use together with your script in a single file.

    John Machin : """all libraries you use""" ... yeah, and often many libraries that you don't use -- see the reference given by @ghostdog74.
  • You should have read the documentation before using. Here's a page you can read

    : thank you very much!!!..
  • py2exe tends to err on the side of caution. You can manually exclude some libraries with the exclude list option in order to reduce the size of the file.

    In my experience, you should be able to compress down to a ~9 MB installer (Inno) if you include wxPython or another GUI framework, ~7 MB if you ship a console app or use tkinter.

    Florian Mayer : But then, why not install Python properly in the installation procedure, when you use an installer, and let py2exe be?
    Ryan Ginstrom : @Florian: Because the average Windows user is going to have a hard time installing Python in order to use your software. I've dealt with the problem many times. Even when they manage to install Python, getting them to navigate the command line is a challenge.
    Florian Mayer : You can make your installer install Python for them and link directly to the main .py file.
    Ryan Ginstrom : If you have a savvy user, then fine. But if your user doesn't know Python from a turnip (and most Windows users don't), then expecting them to handle the package management of a normal Python install is simply not realistic.

How do I set the .application icon for a ClickOnce deployment (online only)

I have a clickonce application that I would like to have the ApplicationName.application file have an icon for the application. Currently the ApplicaitonName.applicaiton file has the default window with blue top and green arrow standard icon.

I have an application icon under the application setup, resources, icon and manifest. That application icon is set to content (i have also tried with it set to embedded resource). That application icon shows up as the window icon and toolbar icon for the application when it is running.

Under publish I publish to a UNC Path and have the "The applicaiton is available online only" radio button clicked. Under Application Files the Resources\ApplicationIcon.ico is Publish Status: Include (Auto), Download Group: (Required), Hash: Include (if the icon is embedded resource it is not in the Application Files).

I generally open the UNC Path and create a shortcut to the .application file to run the application then. I just want that .application file to have the same icon as the windows and toolbar, but not sure what else i need to do to accomplish that. Any help is much appreciated.

From stackoverflow
  • The .application file is the deployment manifest. I don't think you can add an icon in that file. Why should it matter to have the default window icon as it is not seen by the client if hosted in IIS.
    On the other hand you can definitely add an icon to the appplication manifest (the .manifest file) and this icon is what shown on the start menu and in the application. The .manifest file should look like

    <asmv1:assembly .. />
      <description asmv2:iconFile="custom.ico" xmlns="urn:schemas-microsoft-com:asm.v1" />
     ...  
    

    In my msbuild script I use the GenerateApplicationManifest task to set the IconFile

    ChrisHDog : the application is deployed via a UNC path, so no IIS, and no start menu either. the current setup does have the icon for the application, but not for the .application file on the UNC path (or shortcuts made to that file) which are what people actually click on to start the file up ... would your suggestion work for that?
    Pratik : I don't think so. If you are able to create a website in IIS to host your application then this will work, but with UNC patch I don't know. You can always try.
    ChrisHDog : with the settings i have that line is already in the .manifest file, and doesn't make the .application file icon ... shame, there must be a way to do this though.

PHP $_FILES['tmp_name']

I am trying to upload a doc file from a form and send it to email. I am using

$_FILES['file']['tmp_name'];

The problem is, it is returning a randomly generated file name. So, when it reaches the inbox, the filename is phpvwRGKN.dat (filename is random each time).

How can I preserve the filename and extension?

Note: I am using geekMail class

From stackoverflow
  • $_FILES["file"]["name"] - the name of the uploaded file

    from http://www.w3schools.com/php/php_file_upload.asp

    Jaspero : If I use $_FILES["file"]["name"] and assign it to a variable, say $attachment, than it will not work because, that returns just a file name. I think I'll need to give the path and path can come only from tmp_name. Please correct me if I am wrong.
    Marc B : Most mail libraries have two filenames you use for attachments. One is the name/location of the file on the server, the other is the name as you want the user to see it. In your case, the name/location is `tmp_name`, and the end-user filename is `name`.
    Gabi Purcaru : From your question I understand that you want to store the file on the server, by using the name instead of tmp_name. The thing to do is use http://php.net/manual/en/function.move-uploaded-file.php `move_uploaded_file()` and move the `tmp_file` to its permanent path with `name` filename.
    Jaspero : No, I want to send the file in an email not upload to server.
    Gabi Purcaru : Then, you can `rename($_FILES["file"]["tmp_name"], $_FILES["file"]["name"])` it...
  • $_FILES['file']['tmp_name']; will contain the temporary file name of the file on the server. This is just a placeholder on your server until you process the file

    $_FILES['file']['name']; contains the original name of the uploaded file from the user's computer.

    Jaspero : $geekMail->attach('/home/willem/file2.zip') should be the format to use the library. So I had to use $attachment = $_FILES['file']['tmp_name']; $geekMail->attach($attachment); Is there a way I can pass ['name'] as well along with the path?
  • Just a suggestion, but you might try the Pear Mail_Mime class instead.

    http://pear.php.net/package/Mail_Mime/docs

    Otherwise you can use a bit of code. Gabi Purcaru method of using rename() won't work the way it's written. See this post http://us3.php.net/manual/en/function.rename.php#97347 . You'll need something like this:

    $dir = dirname($_FILES["file"]["tmp_name"]);
    $destination = $dir . DIRECTORY_SEPARATOR . $_FILES["file"]["name"];
    rename($_FILES["file"]["tmp_name"], $destination);
    $geekMail->attach($destination);
    

Best way for two apps on the same machine to communicate

I have an ASP.NET app running on a webserver. A third party is created another app in PHP which needs to send data to my app for processing.

Initially it was assumed that the PHP app would be deployed elsewhere so we agreed that the communication would occur over the internet via HTTP (over SSL). My app would simply use a generic handler (ashx) file to recieve the data and send confirmation back.

Now it seems that the PHP app might be deployed on the same machine as my app. I like the fact that using HTTP (as opposed to say direct database access), the PHP app needs to know nothing at all about how my app works. But using the public internet seems silly for communication between two apps on the same machine.

If the PHP app simply used a localhost address, would this ensure that all the data stays within the machine? Is there a better way to do this?

From stackoverflow
  • The public Internet would never be used, even if the PHP app specified an address on an external interface. But if you want to be... overcautious... then just use 127.0.0.1.

    David : Sorry to clarify... if the PHP app used the full public URL of my app, the communication would still occur internally only?
    Paul : Assuming the full public URL's domain name resolves to the server, yes. If it resolves to a load balancer or proxy server separate to the app server. no.
    Ignacio Vazquez-Abrams : If it resolves to an interface on the machine, then yes. If it resolves to some reverse proxy somewhere else, then no.
    David : Excellent, thank you for the clarification.
    Aliostad : But using localhost or 127.0.0.1 will not help since most probably host headers are used to host multiple websites. See my answer.
    Ignacio Vazquez-Abrams : That's easily solved. Deploy the ASP.NET app to an additional internal hostname that resolves to 127.0.0.1. Then just use that hostname in the PHP app.
  • If the PHP simply used a localhost address, would this ensure that all the data stays within the machine?

    Yes

    Is there a better way to do this?

    Makes sense to me. It's a common architectual choice, and it makes it easier should the two apps be deployed on separate machines again in future.

  • Yes, if you configure your TCP-connection using localhost, there will be no traffic sent out to the web. We have lot of applications which communicates with services using the TCP interface. No traffic will ever leave the server.

    If you are unable to change the address in the PHP app, you may consider adding a hosts entry and redirect it to the local machine instead.

  • If they are deployed to the same machine, they must have been set up with host headers so that the IIS sends the traffic to the correct website - it is true that they can be listening tio different ports and no host headers but being a public web site, this is not an option.

    If host headers are setup - which I am pretty sure they are - you cannot use localhost.

    David : Wow, that's interesting. I think that because my ASP.NET app uses SSL, it listens on port 443 so it doesn't need a specific host header. I am finding that when remoted onto the server, typing https:// localhost brings the web app up, but only after a warning that there is a problem with the certificate - presumably because I'm not using the domain name associated with the certificate. Whether this will cause problems for inter-app communications, we'll find out during testing I guess.
    Paul : You could still bind multiple IP addresses to one interface and stick to port 80. You can't use host-headers on an SSL site with different domain names anyway (and since the apps were to be on two servers), I'm assuming they are on different domains. And if the ASP.Net app is only to be accessed from the PHP one, it could run on a different port without any big issue