Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
17 total  XML / RSS feed 

Django and Open-flash-charts

// Found this on the django-users mailing list, need to test
ok, I finally got open-flash-chart to work.

1. create an xhtml-file and insert (something like) this:

    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
        codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/
flash/swflash.cab#version=8,0,0,0"
        width="600"
        height="400"
        id="graph-2"
        align="middle">
    <param name="allowScriptAccess" value="sameDomain" />
    <param name="movie" value="/media/site/chart/open-flash-chart.swf?
width=600&height=400&data=/chart_data/" />
    <param name="quality" value="high" />
    <param name="bgcolor" value="#FFFFFF" />
    <embed src="/media/site/chart/open-flash-chart.swf?
width=600&height=400&data=/chart_data/"
        quality="high"
        bgcolor="#FFFFFF"
        width="600"
        height="400"
        name="open-flash-chart"
        align="middle"
        allowScriptAccess="sameDomain"
        type="application/x-shockwave-flash"
        pluginspage="http://www.macromedia.com/go/getflashplayer"; />
    </object>

2. define the url for the chart, eg: (r'^chart/$',
'www.views.charts.chart'),

3. define the url for the chart-data, e.g.: (r'^chart_data/$',
'www.views.charts.chart_data'),

4. the views:

def chart(request):

   ### nothing really required. whatever you want to do here. points
to the html-file created above

    return render_to_response('site/charts/chart.html', {
        'var': 'var',
    }, context_instance=RequestContext(request) )


def chart_data(request):

    import random

    g = graph()

    data_1 = []
    data_2 = []
    data_3 = []
    for i in range(12):
      data_1.append( random.randint(14,19) )
      data_2.append( random.randint(8,13) )
      data_3.append( random.randint(1,7) )

    g.title('PageViews (2007)', '{color: #999999; font-size: 16; text-
align: center}' );
    g.bg_colour = '#ffffff'

    # we add 3 sets of data:
    g.set_data( data_1 )
    g.set_data( data_2 )
    g.set_data( data_3 )

    # we add the 3 line types and key labels
    g.line_dot( 3, 5, '#333333', 'Page views', 10 )
    g.line_dot( 3, 5, '#666666', 'Visits', 10)    # <-- 3px thick +
dots
    g.line_hollow( 2, 4, '#999999', 'Unique visitors', 10 )


g.set_x_labels( 
'Jänner,Februar,März,April,Mai,Juni,Juli,August,September,Oktober,November,Dezember'.split(',')
 )
    g.set_x_label_style( 11, '0x666666', 2, 1)

    g.set_y_max(20)
    g.y_label_steps(4)
    g.set_y_label_style( 10, '0x666666')

    return HttpResponse(g.render())


Stage Align

// STAGEALIGN

var stageListener:Object = new Object();
stageListener.originalWidth = 1000;
stageListener.originalHeight = 700;
Stage.scaleMode = "noScale";
Stage.align = "B";
updateStage = function () {
if (selectedPage == undefined) {
lepel._height = Stage.height;
}
lepel._width = Stage.width+2;
sky.bg._width = Stage.width;
sky.bg._height = Stage.height;
sky["sky"+selectedPage].linear._width = Stage.width+2;
footerBg.Update();
};
stageListener.onResize = function() {
StageLeft = -1*(Stage.width-this.originalWidth)/2;
StageTop = -1*(Stage.height-this.originalHeight);
StageRight = StageLeft+Stage.width;
StageBottom = 700;
updateStage();
};
stageListener.onResize();
Stage.addListener(stageListener);

Get your Flash Movie's URL

This function returns the full URL of the .swf file. Simple enough.

myUrl = getProperty("", _url );

Get rid of white flash when iframe loads

// Adding this to the iframe code will stop the white flash that occurs when an iframe loads.

style="visibility:hidden;" onload="this.style.visibility = 'visible';"

Finding stuff in strings / or not!

Contains is an actionscript function that I use a lot. From Kirupa

contains = function (input, arrayData) {
  for (i=0; i<arrayData.length; i++) {
    if (arrayData[i] == input) {
      return 1;
    }
  }
  return -1;
};

explode() function for Actionscript

A simple version of the explode() function in PHP. It takes a string and splits it up into an array by splitting it at whatever character (or characters) you specify. For example, reading in a tab delimited text file. Will split it into lines by splitting on returns ("\r"). Then split up the lines by splitting on tabs ("\t").

Attribution: I didn't write this myself, I found it in a comment on one of the Actionscript on-line documentation pages.

function explode(separator:String, string:String) {

        var list = new Array();

        if (separator == null) return false;
        if (string == null) return false;

        var currentStringPosition = 0;
        while (currentStringPosition<string.length) {
                var nextIndex = string.indexOf(separator, currentStringPosition);
                if (nextIndex == -1) break;
                var word = string.slice(currentStringPosition, nextIndex);
                list.push(word);
                currentStringPosition = nextIndex+1;
        }
        if (list.length<1) {
                list.push(string);
        } else {
                list.push(string.slice(currentStringPosition, string.length));
        }
        return list;
}

print_r() for Actionscript

Here's a cheap little function to mimic the print_r() function from PHP in Actionscript. It's designed to work on most any array and will handle nested arrays through recursion.
//
// recursive function to print out the contents of an array similar to the PHP print_r() funciton
//
function print_a( obj, indent ) {
        if (indent == null) indent = "";
        var out = "";
        for ( item in obj ) {
                if (typeof( obj[item] ) == "object" )
                        out += indent+"[" + item + "] => Object\n";
                else
                        out += indent+"[" + item + "] => " + obj[item]+"\n";
                out += print_a( obj[item], indent+"   " );
        }
        return out;
}
// example call
trace( print_a( example_array ) );

Collapse Whitespace function for Actionscript

This function will strip out all tabs and return characters. It will also collapse all runs of multiple spaces down to one. It will also remove a leading and trailing spaces. It is similar to the php_strip_whiespace() function in PHP.

function collapseWhiteSpace( theString ) {
        theString =  theString.split("\r").join("");
        theString =  theString.split("\t").join("");
        while ( theString.indexOf("  " ) != -1 ) {
                theString= theString.split("  ").join(" ");
        }
        if (theString.substr(0,1) == " ") {
                theString = theString.substr( 1 );
        }
        if (theString.substr( theString.length-1, 1 ) == " ") {
                theString = theString.substr( 0, theString.length - 1 );
        }
        return( theString );
}

Random Numer

Random number function - returns a number between min and max
Receives (min, max)
Returns randomNum


function randRange(min:Number, max:Number):Number {
    var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) + min;
    return randomNum;
}

Actionscript

// Countdown code

countDown = function() {
        seconds_conta = seconds_conta - 1;
        hours = int(seconds_conta / 3600);
        minutes = int((seconds_conta / 60) - (hours * 60));
        //seconds = int(seconds_conta-((hours*3600)+minutes*60));
        seconds = int((seconds_conta % 60));
        
        //Se for menor que dez, acrescenta um zero
        if(minutes<10){
                minutes="0"+minutes;
        }
        if(seconds<10){
                seconds="0"+seconds;
        }
        
        //Será que precisa colocar no frame correto?
        timer_txt.text=(hours+":"+minutes+":"+seconds);
        
                //trace("seconds_conta: "+seconds_conta);
                //trace("hours: "+hours);
                //trace("minutes: "+minutes);
                //trace("seconds: "+seconds);
        
        if (seconds_conta == 0) {
          clearInterval(timer);
                  //Chama função de acabar a contagem!
                  //fim_das_questões();
     }
} 

///////// Acrescentar no código
//Tempo total inicial em segundos ->Calculado a partir da quantidade de questões
seconds_conta = 185;
///////// Inicia o timer
//A cada 1000 ms, ativa a função countDown, diminuindo um segundo do total
timer = setInterval(countDown, 1000);

Check connection with Zinc

function isConnected():Boolean {
var results = mdm.Network.checkConnection();
return results;
}
var hasConnection = isConnected();
mdm.Dialogs.prompt(hasConnection);

Internet Connection: Flash 8 Only.

var connected:Boolean = false;
function checkConnection():Void {
var myLoadVars:LoadVars = new LoadVars();
myLoadVars.onHTTPStatus = function(httpStatus:Number) {
if (httpStatus != 0) {
connected = true;
} else {
connected = false;
}
delete this;
};
myLoadVars.load("http://www.apple.com");
}
checkConnection();

Using FlashObject and the miniFLV player to play videos from an entry

Ideally, at some point, I'll modify the plug-in for EE that shows Flash objects to use flashobject.js.

This code assumes custom fields in the blog.

FlashObject: http://blog.deconcept.com/flashobject/
MiniFLV: http://www.richnetapps.com/miniflv.htm

Online Example.

{if project_video}
{if project_video_title}<h4>{project_video_title}: Video Cliph4>{/if}

<div id="videoClip">
<p style="margin: 10px 0; padding: 10px; border: 3px solid red;"><a href="http://www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" target="_blank" title="Get Flash Player"><img src="http://www.macromedia.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Flash Player" height="31" width="88" align="left" style="padding-right: 10px">a>Flash 7 or above and JavaScript are required to view the project video clip. Please download the //www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" target="_blank" title="Get Flash Player">latest Flash plug-in.

{if project_video_alt}

{project_video_alt}

{/if}
{/if}

SetTimeout : Flash

function testMe() {
 trace("callback: "+getTimer()+" ms.");
}

var intervalID:Number = setTimeout(testMe, 1000);

// clearTimeout(intervalID) // for clear the timeout

Dynamically placed buttons

It's simple, yet I often forget this.

var myMC:MovieClip;
var i = 1;
var pad = 5;
while (i<6) {
        trace(" i : "+i);
        myMC.duplicateMovieClip("myMC"+i, i);
        myMC.removeMovieClip();
        this["myMC"+i]._x = this["myMC"+(i-1)]._x+(this["myMC"+(i-1)]._width)+pad;
        this["myMC"+i].onRollOver = function() {
                trace(this);
        };
        i++;
}

Retreiving a Flash movie's domain name

Use the LocalConnection object to get the domain name of the server where the Flash movie is located.

var localDomainLC:LocalConneciton = new LocalConnection();
myDomainName = localDomainLC.domain();
trace( "My domain is " + myDomainName );



This will print out something like this:

My domain is example.com


Use Flash's MovieClipLoader Class

I'm always forgetting the syntax for this...

var oImgListener = new Object();
oImgListener.onLoadInit = function(target_mc)
{
     trace(target_mc._name + "  load complete");
     ...
}

var mclImg = new MovieClipLoader();
mclImg.addListener(oImgListener);
mclImg.loadClip("http://myurl.com/path/to/swf/or/jpg", mcImgLoader);
« Newer Snippets
Older Snippets »
17 total  XML / RSS feed