Tag Archive for stream

Read arithmetic binary data using fstreams #2

unsigned short fread_unsigned_short(ifstream &input_file) { //note that the ifstream is passed by reference
    unsigned short num;
    //the cast reinterpretation is very importnant
    input_file.read(reinterpret_cast < char * > (&num),sizeof(unsigned short));
    return num;
}

ifstream input_data;
input_data.open("input.dat",ios::in | ios::binary); //note the modifiers that denote both input file and binary mode
unsigned short num=fread_unsigned_short(input_data);

/*
The above function can be generalized to any numeric datatype like integers, floats e.t.c.
just replace the type 'unsigned short' with the wanted type
*/

source

Pass a stream to a function #2

void myfunction(ifstream &fp, ...)  // use this
void myfunction(ifstream fp, ...)   // not this

source

Constant Video Stream in Actionscript 3.0

package {
	//display
	import flash.display.MovieClip;
	
	//media
	import flash.media.SoundTransform;
	import flash.media.Video;
	
	//net
	import flash.net.NetConnection;
	import flash.net.NetStream;
	
	//events
	import flash.events.SecurityErrorEvent;
	import flash.events.AsyncErrorEvent;
	import flash.events.NetStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.TimerEvent;
	
	//utils
	import flash.utils.Timer;
	
	//transitions
	import fl.transitions.Tween;
	import fl.transitions.easing.Strong;
	import fl.transitions.TweenEvent;
	
	public class VideoManager extends MovieClip {
		
		private var _url:String = "video/";
		private var _VideoList:XMLList;
		private var _VideoListLength:Number;
		private var _CurrentVideoPosition:Number = 0;
		private var _isPlaying:Boolean;
		
		private var _NetConnection:NetConnection;
		private var _NetStream:NetStream;
		private var _Video:Video;
		private var _customClient:Object;
		private var _videoDuration:Number;
		
		private var _SoundTransform:SoundTransform;
		
		private var _VideoContainer:MovieClip;
		
		private var _Timer:Timer;
		
		private var _fadeOut:Tween;
		private var _fadeIn:Tween;
		
		public function VideoManager(pVideoContainer:MovieClip):void {
			trace("Video Manager Instantiated");
			_VideoContainer = pVideoContainer;
		}//end of constructor
		
		public function setVideoList(pVideoList:XMLList):void {
			trace("
Set Video List");
			_VideoList = pVideoList;
			trace("Video List: 
" +_VideoList);
			_VideoListLength = _VideoList.length();
			trace("Video List Length: " + _VideoListLength);
		}//end of setVideoList
		
		public function StartVideo(pVideoPos:Number=NaN):void {
			
			trace("
Start Video");
			
			//is the position not a number
			if(isNaN(pVideoPos))
				pVideoPos = 0;
				
			//check to see if video is playing
			if (_isPlaying) {
				//stop video
				
				//the video is no longer playing
				_isPlaying = false;
			}

			//set up SoundTransform for Video
			_SoundTransform = new SoundTransform();
			_SoundTransform.volume = 0;
			
			//set up NetConnection
			_NetConnection = new NetConnection();
			_NetConnection.connect(null);
			
			//set up CustomClient
			_customClient = new Object();
			_customClient.onMetaData = metaDataHandler;
			
			//set up NetStream
			_NetStream = new NetStream(_NetConnection);
			_NetStream.client = _customClient;
			_NetStream.bufferTime = 1;
			_NetStream.receiveVideo(true);
			_NetStream.soundTransform = _SoundTransform;
			
			//create instance of Video
			_Video = new Video(640,360);
			_VideoContainer.addChild(_Video);
			_Video.attachNetStream(_NetStream);

			//Add Listeners
				//========Net Connection=======================
			_NetConnection.addEventListener(NetStatusEvent.NET_STATUS, doNetStatus);
			_NetConnection.addEventListener(IOErrorEvent.IO_ERROR, doIOError);
			_NetConnection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doSecurityError);
			
				//========Net Stream=======================
			_NetStream.addEventListener(NetStatusEvent.NET_STATUS, doNetStatus);
			_NetStream.addEventListener(IOErrorEvent.IO_ERROR, doIOError);
			_NetStream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, doAsyncError);
			
			trace("Play Video: " + _VideoList[pVideoPos].attribute('filename'));
			_NetStream.play(_url+_VideoList[pVideoPos].attribute('filename'));
			
			_fadeIn = new Tween(_Video,"alpha",Strong.easeOut,0,1,3,true);
			_fadeIn.addEventListener(TweenEvent.MOTION_START, fadeInStart);
			_fadeIn.addEventListener(TweenEvent.MOTION_STOP, fadeInStop);
			_fadeIn.start();
		}
		
		//EVENT HANDLERS
		/*
			Example of Security Error
				Not having secruity rights on the server containing the FLV
			
			Solution:
				crossdomain.xml file
		*/
		protected function doSecurityError(evt:SecurityErrorEvent):void {
			trace("AbstractStream.securityError:"+evt.text);
			//do nothing
		}//end of doSecurityError
		/*
			Examples of IOErrors:
				connection drop
				loss of internet connection
				404 error
		*/
		protected function doIOError(evt:IOErrorEvent):void {
			trace("AbstractScreem.ioError:"+evt.text);
			//do nothing
		}//end of doIOError
		/*
			Examples of AsyncError
				usually due to streaming server
		*/
		protected function doAsyncError(evt:AsyncErrorEvent) {
			trace("AbstractScreem.asyncError:"+evt.text);			
			//do nothing
		}//end of doAsyncError
		
		protected function doNetStatus(e:NetStatusEvent):void {
			switch (e.info.code) {
				//NetStream
				case "NetStream.Play.StreamNotFound":
					trace("Stream not found");
					break;
				case "NetStream.Play.Stop":
					trace("Netstream Stopped");
					break;
				case "NetStream.Play.Start":
					trace("Netstream Playing");					 
					break;
				//NetConnection
				case "NetConnection.Connect.Closed":
					trace("NetConnection Closed");
					//dispatchEvent(new Event(VideoStream.STREAM_COMPLETE));
					break;
				case "NetConnection.Connect.Failed":
					trace("NetConnection Failed");
					break;
				case "NetConnection.Connect.Success":
					trace("NetConnection Success");
					break;
				default :
					break;
			}
		}//end of doNetStatus
		
		private function timerDone(e:TimerEvent):void{
			_Timer.removeEventListener(TimerEvent.TIMER, timerDone);
			_fadeOut = new Tween(_Video,"alpha",Strong.easeOut,1,0,3,true);
			_fadeOut.addEventListener(TweenEvent.MOTION_START, fadeOutStart);
			_fadeOut.addEventListener(TweenEvent.MOTION_STOP, fadeOutStop);
			_fadeOut.start();
			trace("Timer Done - Begin Transition Out");
		}
		
		private function fadeInStart(e:TweenEvent):void{
			_fadeIn.removeEventListener(TweenEvent.MOTION_START, fadeInStart);		
		}
		private function fadeInStop(e:TweenEvent):void{
			_fadeIn.removeEventListener(TweenEvent.MOTION_STOP, fadeInStop);		
		}
		
		private function fadeOutStart(e:TweenEvent):void{
			trace("Begin Transition of Next Video In");
			if(_CurrentVideoPosition+1 < _VideoListLength)
				_CurrentVideoPosition++;
			else
				_CurrentVideoPosition = 0;
			
			trace("Current Video POS: " + _CurrentVideoPosition);
			
			StartVideo(_CurrentVideoPosition);
			_fadeOut.removeEventListener(TweenEvent.MOTION_START, fadeOutStart);			
		}
		private function fadeOutStop(e:TweenEvent):void{
			trace("Remove Everything from Previous Video");
			_fadeOut.removeEventListener(TweenEvent.MOTION_STOP, fadeOutStop);
		}
		
		private function metaDataHandler(pObject:Object):void {
			for (var propName:String in pObject) {
				trace(propName + " = " + pObject[propName]);
			}

			if (pObject.duration != null)
				_videoDuration = pObject.duration;
				
				_Timer = new Timer((_videoDuration-2)*1000);
				_Timer.addEventListener(TimerEvent.TIMER, timerDone);
				_Timer.start();
		}
	}
	
}

source

tweet from php

<?php 
function tweet($message, $username, $password) 
{ 
  $context = stream_context_create(array( 
    'http' => array( 
      'method'  => 'POST', 
      'header'  => sprintf("Authorization: Basic %s
", base64_encode($username.':'.$password)). 
                   "Content-type: application/x-www-form-urlencoded
", 
      'content' => http_build_query(array('status' => $message)), 
      'timeout' => 5, 
    ), 
  )); 
  $ret = file_get_contents('<a href="http://twitter.com/statuses/update.xml'," >http://twitter.com/statuses/update.xml',</a> false, $context); 
  
  return false !== $ret; 
} 
?> 

Pretty easy, no? Using the tweet() function is of course a piece of cake: 

<?php 
tweet('From PHP, yeah...', 'fabpot', 'Pa$$'); 
?>

source

Convert OutputSream into an InputStream

final String dataId=//id of some data.
final InputStreamFromOutputStream<String> isos = new InputStreamFromOutputStream<String>() {
   @Override
   public String produce(final OutputStream dataSink) throws Exception {
      /*
       * call your application function who produces the data here
       * WARNING: we're in another thread here, so this method shouldn't 
       * write any class field or make assumptions on the state of the class. 
       */
      return produceMydata(dataId,dataSink)
   }
 };
 try {
  //now you can read from the InputStream the data that was written to the 
  //dataSink OutputStream
  byte[] readed=IOUtils.toByteArray(isos);
  //Use data here
 } catch (final IOException e) {
  //Handle exception here
 } finally {
  isos.close();
 }
  //You can get the result of produceMyData after the stream has been closed.
  String resultOfProduction = isos.getResult();
}

source

Read files from jar (getResourceAsStream) 2

Scanner scanner = new Scanner(getClass().getResourceAsStream("/" + path_to_file));

source

Read files from jar (getResourceAsStream)

BufferedReader br = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("html.htm")));
String line = br.readLine();
while(line!=null){
output+=line + "
";
line = br.readLine();
}

source

Stream to Byte Array

Private Function GetStreamAsByteArray(ByVal stream As System.IO.Stream) As Byte()

Dim streamLength As Integer = Convert.ToInt32(stream.Length)

Dim fileData As Byte() = New Byte(streamLength) {}

' Read the file into a byte array
stream.Read(fileData, 0, streamLength)
stream.Close()

Return fileData

End Function

source

Python – getFile Internet

package get.file.example;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class GetFileExample
{
public GetFileExample()
{
try
{
byte[] bite = new byte[2048];
int read;
URL url = new URL("http://switch.dl.sourceforge.net/sourceforge/pys60miniapps/FlickrS60_src_v0.1b.tar.bz2");

BufferedInputStream bis = new BufferedInputStream(url.openStream());
FileOutputStream fos = new FileOutputStream("/tmp/file.tar.bz2");

while((read = bis.read(bite))>0)
{
fos.write(bite, 0, read);
System.out.println("--");
}

fos.close();
bis.close();

System.out.println("FINE");

}
catch(MalformedURLException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
}

public static void main(String[] args)
{
new GetFileExample();
}
}

source