Assert &  writing code that should never be reached

hi dudes,
i thing i got that assertion-stuff right BUT there is one thing confusing me:
from my book:
"The following idiom can be employed to explicitly test that certain locations in the code will never be reached.
assert false : "This line should never be reached.";
but what is the point of writing code(at all) that will never be reached?
i mean if it should never be reached ill simply never write it.
even in this tricky EXAMPLE
int someMthd(int trinityMember)
switch (trinityMember) {
    case THE_FATHER:
        return psalm101;
    case THE_SON:
        return psalm102;
    case THE_HOLY_GHOST:
        return psalm103;
    default:
        assert false: trinityMember; //Ok BETTER WOULD BE throw new AssertionError(trinityMember);
}if no case match i would get COMPILE TIME error so that will indicate me that method could(possible) never return an int. So if a i can compile it it will be ok!?
so again what is the point of writing code that should never be reached[\b]?

if no case match i would get COMPILE TIME error so
that will indicate me that method could(possible)
never return an int. So if a i can compile it it will
be ok!?But without the default case you can't compile it, so you have to write a default case (or some other code). What code would it make sense to put there other than throwing an exception of some sort or returning a default value?
so again what is the point of writing code that
should never be reached[\b]?You probably believe the code should never be reached in your example because to you it only makes sense to pass either THE_FATHER, THE_SON or THE_HOLY_GHOST as a parameter. But what if somebody were to pass THE_FIRESTARTER to your someMthd method, having not realised that you haven't coded for that argument? What should your code do then? It can't do nothing, so it makes sense to provide a default case that lets the user know (by throwing an exception), that something unexpected has happened. Or, you might decide to return a default value that is useful and perhaps somehow informs client code of the unusual circumstance (for example a return value of -1 might indicate that there is no relevant psalmX).
So this is about robustness - making sure that in unexpected circumstances, your application does something reasonable.

Similar Messages

  • Best Practice: files that should never be moved or deleted

    Hi there.
    I've just gone through my computer for the first time in a couple of years and done a massive cleanup, but without really knowing the consequences I guess you could say and now things are acting a little strange.
    +(I feel silly even writing this, knowing that all the IT heads out there are sighing a unanimous 'what an idiot'.)+
    Can anyone please provide a sort of 'best practice' guide for the files/file types that should absolutely be on the harddrive, or in the apps folder, utilities folder, etc? and if there are any that should 'never' be deleted?
    .. or even some program that sort of saves you from yourself by keeping those files safe from being a.) moved and b.) deleted
    Would be a huge help!
    Thanks in advance ~
    Message was edited by: BluesySue
    Message was edited by: BluesySue

    Apple has already hidden about half of the folders on a typical OS X install. The ones that make up the Unix core of the OS. So unless you know how to find those, you'll never have to worry about them.
    Aside from that, you just want to keep away from the System folder and any of the Library folders. Nothing else should be too crucial to the OS running.
    Of course if you wanted to elaborate on "a little strange" we might be able to be a bit more helpful.

  • Apple Maps - Please reconsider and include Google Maps. As a long time Apple customer, I am disappointed iOS would regress the system and inconvenience millions because of a vendetta that should never hinder users. Not only does the transit feature I used

    Apple Maps - Please reconsider and include Google Maps. As a long time Apple customer, I am disappointed iOS would regress the system and inconvenience millions because of a vendetta that should never hinder users. Not only does the transit feature I used religiously no longer exist, but clicking on an address in a website now directs users to a poor Google Maps interface. I am surprised to see such a effortless update from a company squatting on the resources to make a change its customers are asking for.

    varjak paw wrote:
    Apple has documented an API to provide add-ons to the Maps app in the iOS 6 SDK, so that such add-ons are possible is absolutely not a guess that the capability is there. As to whether someone will indeed develop an add-on for any given transit system, that would be a guess, yes, but at a couple of companies at least have already announced plans to do so.
    In select cities and areas - so now I'm going from being able to supply this information myself to either wait for someone to supply an app or write an app myself... This is not feature progression but feature regression. Adding transit times or a specific overlay should not have to be something you need to do through code via an API. So no dice... Your guess that we will see better transit information is just that - a guess, nothing else.
    If you don't agree with that editorial, you are certainly free to do so. I provided the link as food for thought for those who have been questioning Apples' decision to drop Google's maps from iOS. Whether or not you agree with Brad's analysis or that of anyone else is up to you.
    But on that central issue the editorial fails - it's is not the true tale of why Apple made their move and therefore useless even as "food for thought" (because it's guesswork).

  • I turned on my I-pad and it automatically sent me to I-cloud instead of my normal I-pad screen, now I cannot log on because it is asking for a pass code that I never set up. How do I log on?

    I turned on my Ipad three days ago and instead of my normal screen, it displayed a totally different screen (I-cloud). I tried to logon but, now it is asking for a passcode that I never had to setup before and I can't use my Ipad. How can I access and use my Ipad?

    Hello kumajet27,
    Your iPad may have been put into what is called 'Lost Mode,' which is a feature of our iCloud service. The following article provides further information regarding this service.
    iCloud: Use Lost Mode
    http://support.apple.com/kb/PH2700
    Cheers,
    Allen

  • Would like help with treeset ,the codes that using for sorting, please ?

    hi every body. i faced a problem while writing this program, everything worked properly except this one. The program is related to Jframe and it asks the user to add three labels , three text field , one text area and three Jbuttons which are add sort and exit. i could deal with add and exit but sort, i couldn't do it properly because i don't know the codes that should be added in actionperfomed?
    These codes are :
    package gui;
    import javax.swing.SwingUtilities;
    import java.awt.BorderLayout;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import java.awt.Rectangle;
    import java.util.ArrayList;
    import javax.swing.JButton;
    import javax.swing.JTextField;
    import javax.swing.JTextArea;
    import sun.misc.Sort;
    import domain.Student;
    public class StudentFrame extends JFrame {
          * This method initializes btnAdd     
          * @return javax.swing.JButton     
         private JButton getBtnAdd() {
              if (btnAdd == null) {
                   btnAdd = new JButton();
                   btnAdd.setBounds(new Rectangle(13, 135, 59, 27));
                   btnAdd.setText("Add");
                   btnAdd.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                        btnAddClicked(); // TODO Auto-generated Event stub actionPerformed()
              return btnAdd;
         protected void btnAddClicked() {
              // TODO Auto-generated method stub
         String name = txtName.getText();
         String id = txtID.getText();
         String age = txtAge.getText();
         Student s = new Student(name , id , age);
         txtArea.setText(String.valueOf(s ));
          * This method initializes btnSort     
          * @return javax.swing.JButton     
         private JButton getBtnSort() {
              if (btnSort == null) {
                   btnSort = new JButton();
                   btnSort.setBounds(new Rectangle(95, 136, 62, 25));
                   btnSort.setText("Sort");
                   btnSort.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             btnSortClicked(); // TODO Auto-generated Event stub actionPerformed()
              return btnSort;
         protected void btnSortClicked() {
              // TODO Auto-generated method stub
          * This method initializes btnExit     
          * @return javax.swing.JButton     
         private JButton getBtnExit() {
              if (btnExit == null) {
                   btnExit = new JButton();
                   btnExit.setBounds(new Rectangle(173, 134, 61, 23));
                   btnExit.setText("Exit");
                   btnExit.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             System.exit(0); // TODO Auto-generated Event stub actionPerformed()
              return btnExit;
          * This method initializes txtName     
          * @return javax.swing.JTextField     
         private JTextField getTxtName() {
              if (txtName == null) {
                   txtName = new JTextField();
                   txtName.setBounds(new Rectangle(79, 11, 60, 23));
              return txtName;
          * This method initializes txtID     
          * @return javax.swing.JTextField     
         private JTextField getTxtID() {
              if (txtID == null) {
                   txtID = new JTextField();
                   txtID.setBounds(new Rectangle(73, 55, 65, 26));
              return txtID;
          * This method initializes txtAge     
          * @return javax.swing.JTextField     
         private JTextField getTxtAge() {
              if (txtAge == null) {
                   txtAge = new JTextField();
                   txtAge.setBounds(new Rectangle(74, 96, 61, 24));
              return txtAge;
          * This method initializes txtArea     
          * @return javax.swing.JTextArea     
         private JTextArea getTxtArea() {
              if (txtArea == null) {
                   txtArea = new JTextArea();
                   txtArea.setBounds(new Rectangle(138, 5, 154, 128));
              return txtArea;
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        StudentFrame thisClass = new StudentFrame();
                        thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        thisClass.setVisible(true);
          * This is the default constructor
         public StudentFrame() {
              super();
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setSize(300, 200);
              this.setContentPane(getJContentPane());
              this.setTitle("JFrame");
              return jContentPane;
    }Edited by: hypocrisy on Apr 26, 2009 6:51 PM

    There are three actionPerformed in that program.One for add Jbutton , Sort , and Exit
    the codes that i have added for add button after action performed are
    String name = txtName.getText();
    String id = txtID.getText();
    String age = txtAge.getText();
    Student s = new Student ( name , id , age);
    System.out.println(s);
    the codes for Exit button to make it works properly was :
    System.out.println(0);
    But when i came to Sort Button and i tried to enter many codes but it didn't sort properly so would you like to help me with the right codes :)

  • Need help with WMI code that will send output to db

    'm new to WMI code writing, so I need some help with writing code that we can store on our server. I want this code to run when a user logs into their computer
    and talks to our server. I also want the code to:
    * check the users computer and find all installed patches
    * the date the patches were installed
    * the serial number of the users computer
    * the computer name, os version, last boot up time, and mac address
    and then have all this output to a database file. At the command prompt I've tried:
    wmic qfe get description, hotfixid
    This does return the patch information I'm looking for, but how do I combine that line of code with:
    wmic os get version, csname, serialnumber, lastbootuptime
    and
    wmic nicconfig get macaddress
    and then get all this to output to a database file?

    Thank you for the links. I checked out http://technet.microsoft.com/en-us/scriptcenter/dd793612.aspx and
    found lots of good information. I also found a good command that will print information to a text file.
    Basically what I'm trying to do is retrieve a list of all installed updates (Windows updates and 3rd party updates). I do like that the below code because it gives me the KB numbers for the Windows updates. I need this information so my IT co-workers &
    I can keep track of which of our user computers need a patch/update installed and preferably which patch/update. The minimum we want to know is which patches / updates have been installed on which computer. If you wondering why we don't have Windows automatic
    updates enable, that's because we are not allowed to.   
    This is my code so far. 
    #if you want the computer name, use this command
    get-content env:computername
    $computer = get-content env:computername
    #list of installed patches
    Get-Hotfix -ComputerName $computer#create a text file listing this information
    Get-Hotfix > 'C:\users\little e\Documents\WMI help\PowerShell\printOutPatchList.txt'
    I know you don't want to tell me the code that will print this out to a database (regardless if it's Access or SQL), and that's find. But maybe you can tell me this. Is it possible to have the results of this sent to a database file or do I need to go into
    SQL and write code for SQL to go out and grab the data from an Excel file or txt file? If I'm understanding this stuff so far, then I suspect that it can be done both ways, but the code needs to be written correctly for this to happen. If it's true, then which
    way is best (code in PowerShell to send information to SQL or SQL go get the information from the text file or Excel file)?

  • Help - index page has disappeared after removing code that was recommended regarding Flash

    After inserting some conditional comments regarding earlier versions of IE not displaying bulleted lists properly. I received a message about Javascript code that should be removed regarding my Flash element.
    When I removed the code that was indicated, my index page changed to a gray screen that had some copy about needing to update the Flash player, so I thought I'd totally take out the code relating to the Flash element and I would reinsert the Flash movie. However when I preview it everything is gone except a gray background. In Live View the original page is there. When I try to look at in in design view preview or view it in a IE browser it is just a gray background.
    I'm attaching the code for the page to see if I accidently removed some element that needed to be in to display the page. Please advise ASAP. Thank you.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Total Care Nursing Services</title>
    <link href="css/twoColFixRtHdr.css" rel="stylesheet" type="text/css" /><!--[if IE 5]>
    <style type="text/css">
    /* place css box model fixes for all versions of IE in this conditional comment */
    .twoColFixRtHdr #sidebar1 { width: 190px; }
    </style>
    <![endif]--><!--[if IE]>
    <style type="text/css">
    /* place css fixes for all versions of IE in this conditional comment */
    .twoColFixRtHdr #sidebar1 { padding-top: 10px; }
    .twoColFixRtHdr #mainContent { zoom: 1; }
    /* the above proprietary zoom property gives IE the hasLayout it needs to avoid several bugs */
    </style>
    <![endif]-->
    <!--[if lte IE 7]>
    <style>
    .twoColFixRtHdr #container #sidebar1 ul {
    margin-left: 25px
    </style>
    <! [endif]-->
    <style type="text/css">
    <!--
    body,td,th {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 14px;
    body {
    background-color: #242D80;
    margin-right: 0px;
    a:link {
    color: #DC3505;
    text-decoration: none;
    a:visited {
    text-decoration: none;
    color: #4A6FBB;
    a:hover {
    text-decoration: none;
    color: #038F0E;
    a:active {
    text-decoration: none;
    h1,h2,h3,h4,h5,h6 {
    font-family: Palatino Linotype, Book Antiqua, Palatino, serif;
    font-weight: bold;
    -->
    </style>
    <link href="css/global.css" rel="stylesheet" type="text/css" /><style type="text/css">
    <!--
    a {
    font-weight: bold;
    -->
    </style>
    <script src="SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
    <script src="Scripts/swfobject_modified.js" type="text/javascript"></script>
    <link href="SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
    </head>
    <body class="twoColFixRtHdr">
    <a href="tcns_members.html"></a>
    <div id="container">
      <div class="twoColFixRtHdr" id="header">
    <!-- end #header -->
    <ul id="MenuBar1" class="MenuBarHorizontal">
      <li><a href="index.html">Home</a>    </li>
      <li><a href="about_us.html">About Us</a></li>
      <li><a href="staffing.html">Staffing Services</a>    </li>
      <li><a href="join_us.html">Join Us</a></li>
      <li><a href="contact_us.html">Contact Us</a></li>
      <li><a href="nursing_news.html">Nursing News</a></li>
      <li><a href="tcns_members.html">TCNS Members</a></li>
    </ul>
      </div>
      <div class="twoColFixRtHdr" id="sidebar1">
        <h3 class="sidebarTitle"><span class="sidebarTitle">TCNS MEDICAL PROFESSIONALS</span></h3>
        <ul>
          <li class="spacedList">Registered Nurses</li>
          <li class="spacedList">Licensed Practical Nurses</li>
          <li class="spacedList">Certified Nursing Assistants</li>
          <li class="spacedList">Radiological Technicians</li>
          <li class="spacedList">Physical Therapists</li>
          <li class="spacedList">Respiratory Therapists</li>
          <li class="spacedList">Home Health Assistants</li>
        </ul>
    <p class="sidebarCopy">Interested in a career at TCNS? <a href="contact_us.html">Contact us</a> to learn more today!</p>
        <p class="sidebarCopy">Are you a facility looking for health care staffing in South Florida? <a href="staffing.html">Click here</a>.</p>
      </div>
      <div id="mainContent">
        <h1>
      Offering Compassionate Care with a Committment to Excellence</h1>
        <p><span class="company">
        </span><span class="company">TOTAL CARE NURSING SERVICES</span> was founded as a bridge  between health care professionals and the many institutions in the health-care  industry, with the primary objective of promoting the patient’s well being and  satisfaction.</p>
    <p>With a nationwide nurse shortage approaching 800,000 and  projected to worsen as the baby boomer generation enters retirement age, the  need for skilled nurses and other health care professionals is rapidly  increasing. However, the greater challenge for health care facilities is to  recruit and retain motivated, dedicated professionals who will help deliver the  quality care that is demanded of them by every aspect of the industry. <span class="company">TOTAL  CARE NURSING SERVICES</span> has the vision to answer this challenge and provide the  needed personnel to its clients at reasonable cost.
      <!-- end #mainContent -->
    </p>
      </div>
    <!-- This clearing element should immediately follow the #mainContent div in order to force the #container div to contain all child floats --><br class="clearfloat" />
      <div id="footer">
        <p><span class="spaceFooter"><a href="index.html">Home</a></span>l <span class="spaceFooter"><a href="mailto:[email protected]">E-Mail</a></span>l <span class="spaceFooter"><a href="links.html">Links</a></span>l <span class="spaceFooter"><a href="search.html">Search</a></span><br />
          Copyright 2009 - Total Care Nursing Services, LLC
    <!-- end #footer -->
        </p>
    </div>
    <!-- end #container -->
    </div>
    </body>
    </html>

    2.
    Deleting and getting the file should solve this problem.
    3.
    You should only require 2 IE conditional statement (for css code), one for less than IE 8 and one for less than IE 7.
    Both or just one of these should be inside the <head> </head> tags not anywhere else.
    The conditional statment in flash are for <object> code.
    Here is an example of how the flash code should look for your webpage:
    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="250" height="204" id="FlashID" title="name of your swf file here without .swf">
            <param name="movie" value="link to your swf file here" />
            <param name="quality" value="high" />
            <param name="wmode" value="opaque" />
            <param name="swfversion" value="8.0.35.0" />
            <!-- This param tag prompts users with Flash Player 6.0 r65 and higher to download the latest version of Flash Player. Delete it if you don’t want users to see the prompt. -->
            <param name="expressinstall" value="../Scripts/expressInstall.swf" />
            <!-- Next object tag is for non-IE browsers. So hide it from IE using IECC. -->
            <!--[if !IE]>-->
            <object type="application/x-shockwave-flash" data="link to your swf file here" width="250" height="204">
              <!--<![endif]-->
              <param name="quality" value="high" />
              <param name="wmode" value="opaque" />
              <param name="swfversion" value="8.0.35.0" />
              <param name="expressinstall" value="../Scripts/expressInstall.swf" />
              <!-- The browser displays the following alternative content for users with Flash Player 6.0 and older. -->
              <div>
                <h4>Content on this page requires a newer version of Adobe Flash
                  Player.</h4>
                <p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p>
              </div>
              <!--[if !IE]>-->
            </object>
            <!--<![endif]-->
          </object>
    The width and height values to be changed to what you require.
    NO other code is required.
    PZ

  • HI, I need your help. How can I delete all data, when I do not have the special security code, which I didn´t remember ? I also think, that I never create this code before. But I cannot put my settings back.

    HI, I need your help. How can I delete all data, when I do not have the special security code, which I didn´t remember ? I also think, that I never create this code before. But I cannot put my settings back.

    You must remember the code, if you can't then take the phone and proof of purchase to an Apple Store.

  • After i installed ios7, my ipad ask for paascode that i never set it up with and now is locked. what should i do to unlock it !?

    My ipad after installing ios 7 is locked and asking for passcode that i never gave it to. what should i di to unlock it. Thnx

    Are your sure that the iPad is not asking you to CREATE a passcode. It will do this as part of the iOS 7 upgrade. If the device is truly asking for a passcode and it is now locked take a look at this Apple support page
    http://support.apple.com/kb/ht1212

  • HT6058 Hello I have a iPhone 4 that's never been updated and I see there are three available, Should I just go with the most recent update ?

    Hello I have a iPhone 4 that's never been updated and I see there are three available, Should I just go with the most recent update ?

    You don't get a choice. If you decide to update, your phone will be updated to the latest iOS version available for your phone. For you, that's iOS 7.0.4.
    Make sure you follow the directions here:
    http://support.apple.com/kb/ht4972
    The update to iOS 5.0 & higher is an erase/restore deal.

  • HT201210 but what should i do if the error code that i got is not here? i had 2003 as the error code.

    please please please i need your help
    recently i was trying to update my ipod touch software
    and everything went ok
    but then i tryed to restore it and
    a message appeared saying that an error hapenned
    the error code was 2003
    then i asked for more info
    and this website appeared
    and said something about.....
    "if an error appeared while you were trying to restore your device,
    then look for the error code that appeared"
    and i did so, but my error code was not there
    what should i do then??
    my ipod touch is a second generation by the way

    Error 2000-2009 (2001, 2002, 2005, 2006, 2009, and so on)
    If you experience this issue on a Mac, disconnect third-party devices, hubs, spare cables, displays, reset the SMC, and then try to restore. If you are using a Windows computer, remove all USB devices and spare cables other than your keyboard, mouse, and the device, restart the computer, and try to restore. If that does not resolve the issue, try the USB issue-resolution steps and articles listed for Error 1604 above. If the issue persists, it may be related to conflicting security software.

  • Sms code for verification does not reach to my mobile. ? i can not access my e-mail because of code that does not sent right now. code that related to my alternated e-mail was sent , but not to mobile

    sms code for verification does not reach to my mobile. ? i can not access my e-mail because of code that does not sent right now. code that related to my alternated e-mail was sent , but not to mobile

    Bugzilla is not the place for this sort of problem. Forwarded this post to the relevant team.

  • Problem while executing the code( that covert jpeg images to movie)

    http://java.sun.com/products/java-media/jmf/2.1.1/solutions/JpegImagesToMovie.html
    here is the code:
    * @(#)JpegImagesToMovie.java     1.3 01/03/13
    * Copyright (c) 1999-2001 Sun Microsystems, Inc. All Rights Reserved.
    * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
    * modify and redistribute this software in source and binary code form,
    * provided that i) this copyright notice and license appear on all copies of
    * the software; and ii) Licensee does not utilize the software in a manner
    * which is disparaging to Sun.
    * This software is provided "AS IS," without a warranty of any kind. ALL
    * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
    * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
    * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
    * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
    * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
    * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
    * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
    * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
    * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
    * POSSIBILITY OF SUCH DAMAGES.
    * This software is not designed or intended for use in on-line control of
    * aircraft, air traffic, aircraft navigation or aircraft communications; or in
    * the design, construction, operation or maintenance of any nuclear
    * facility. Licensee represents and warrants that it will not use or
    * redistribute the Software for such purposes.
    import java.io.*;
    import java.util.*;
    import java.awt.Dimension;
    import javax.media.*;
    import javax.media.control.*;
    import javax.media.protocol.*;
    import javax.media.protocol.DataSource;
    import javax.media.datasink.*;
    import javax.media.format.VideoFormat;
    * This program takes a list of JPEG image files and convert them into
    * a QuickTime movie.
    public class JpegImagesToMovie3 implements ControllerListener, DataSinkListener {
    public boolean doIt(int width, int height, int frameRate, Vector inFiles, MediaLocator outML) {
         ImageDataSource ids = new ImageDataSource(width, height, frameRate, inFiles);
         Processor p;
         try {
         System.err.println("- create processor for the image datasource ...");
         p = Manager.createProcessor(ids);
         } catch (Exception e) {
         System.err.println("Yikes! Cannot create a processor from the data source.");
         return false;
         p.addControllerListener(this);
         // Put the Processor into configured state so we can set
         // some processing options on the processor.
         p.configure();
         if (!waitForState(p, p.Configured)) {
         System.err.println("Failed to configure the processor.");
         return false;
         // Set the output content descriptor to QuickTime.
         p.setContentDescriptor(new ContentDescriptor(FileTypeDescriptor.QUICKTIME));
         // Query for the processor for supported formats.
         // Then set it on the processor.
         TrackControl tcs[] = p.getTrackControls();
         Format f[] = tcs[0].getSupportedFormats();
         if (f == null || f.length <= 0) {
         System.err.println("The mux does not support the input format: " + tcs[0].getFormat());
         return false;
         tcs[0].setFormat(f[0]);
         System.err.println("Setting the track format to: " + f[0]);
         // We are done with programming the processor. Let's just
         // realize it.
         p.realize();
         if (!waitForState(p, p.Realized)) {
         System.err.println("Failed to realize the processor.");
         return false;
         // Now, we'll need to create a DataSink.
         DataSink dsink;
         if ((dsink = createDataSink(p, outML)) == null) {
         System.err.println("Failed to create a DataSink for the given output MediaLocator: " + outML);
         return false;
         dsink.addDataSinkListener(this);
         fileDone = false;
         System.err.println("start processing...");
         // OK, we can now start the actual transcoding.
         try {
         p.start();
         dsink.start();
         } catch (IOException e) {
         System.err.println("IO error during processing");
         return false;
         // Wait for EndOfStream event.
         waitForFileDone();
         // Cleanup.
         try {
         dsink.close();
         } catch (Exception e) {}
         p.removeControllerListener(this);
         System.err.println("...done processing.");
         return true;
    * Create the DataSink.
    DataSink createDataSink(Processor p, MediaLocator outML) {
         DataSource ds;
         if ((ds = p.getDataOutput()) == null) {
         System.err.println("Something is really wrong: the processor does not have an output DataSource");
         return null;
         DataSink dsink;
         try {
         System.err.println("- create DataSink for: " + outML);
         dsink = Manager.createDataSink(ds, outML);
         dsink.open();
         } catch (Exception e) {
         System.err.println("Cannot create the DataSink: " + e);
         return null;
         return dsink;
    Object waitSync = new Object();
    boolean stateTransitionOK = true;
    * Block until the processor has transitioned to the given state.
    * Return false if the transition failed.
    boolean waitForState(Processor p, int state) {
         synchronized (waitSync) {
         try {
              while (p.getState() < state && stateTransitionOK)
              waitSync.wait();
         } catch (Exception e) {}
         return stateTransitionOK;
    * Controller Listener.
    public void controllerUpdate(ControllerEvent evt) {
         if (evt instanceof ConfigureCompleteEvent ||
         evt instanceof RealizeCompleteEvent ||
         evt instanceof PrefetchCompleteEvent) {
         synchronized (waitSync) {
              stateTransitionOK = true;
              waitSync.notifyAll();
         } else if (evt instanceof ResourceUnavailableEvent) {
         synchronized (waitSync) {
              stateTransitionOK = false;
              waitSync.notifyAll();
         } else if (evt instanceof EndOfMediaEvent) {
         evt.getSourceController().stop();
         evt.getSourceController().close();
    Object waitFileSync = new Object();
    boolean fileDone = false;
    boolean fileSuccess = true;
    * Block until file writing is done.
    boolean waitForFileDone() {
         synchronized (waitFileSync) {
         try {
              while (!fileDone)
              waitFileSync.wait();
         } catch (Exception e) {}
         return fileSuccess;
    * Event handler for the file writer.
    public void dataSinkUpdate(DataSinkEvent evt) {
         if (evt instanceof EndOfStreamEvent) {
         synchronized (waitFileSync) {
              fileDone = true;
              waitFileSync.notifyAll();
         } else if (evt instanceof DataSinkErrorEvent) {
         synchronized (waitFileSync) {
              fileDone = true;
              fileSuccess = false;
              waitFileSync.notifyAll();
    public static void main(String args[]) {
         if (args.length == 0)
         prUsage();
         // Parse the arguments.
         int i = 0;
         int width = -1, height = -1, frameRate = 1;
         Vector inputFiles = new Vector();
         String outputURL = null;
         while (i < args.length) {
         if (args.equals("-w")) {
              i++;
              if (i >= args.length)
              prUsage();
              width = new Integer(args[i]).intValue();
         } else if (args[i].equals("-h")) {
              i++;
              if (i >= args.length)
              prUsage();
              height = new Integer(args[i]).intValue();
         } else if (args[i].equals("-f")) {
              i++;
              if (i >= args.length)
              prUsage();
              frameRate = new Integer(args[i]).intValue();
         } else if (args[i].equals("-o")) {
              i++;
              if (i >= args.length)
              prUsage();
              outputURL = args[i];
         } else {
              inputFiles.addElement(args[i]);
         i++;
         if (outputURL == null || inputFiles.size() == 0)
         prUsage();
         // Check for output file extension.
         if (!outputURL.endsWith(".mov") && !outputURL.endsWith(".MOV")) {
         System.err.println("The output file extension should end with a .mov extension");
         prUsage();
         if (width < 0 || height < 0) {
         System.err.println("Please specify the correct image size.");
         prUsage();
         // Check the frame rate.
         if (frameRate < 1)
         frameRate = 1;
         // Generate the output media locators.
         MediaLocator oml;
         if ((oml = createMediaLocator(outputURL)) == null) {
         System.err.println("Cannot build media locator from: " + outputURL);
         System.exit(0);
         JpegImagesToMovie3 imageToMovie3 = new JpegImagesToMovie3();
         imageToMovie3.doIt(width, height, frameRate, inputFiles, oml);
         System.exit(0);
    static void prUsage() {
         System.err.println("Usage: java JpegImagesToMovie -w <width> -h <height> -f <frame rate> -o <output URL> <input JPEG file 1> <input JPEG file 2> ...");
         System.exit(-1);
    * Create a media locator from the given string.
    static MediaLocator createMediaLocator(String url) {
         MediaLocator ml;
         if (url.indexOf(":") > 0 && (ml = new MediaLocator(url)) != null)
         return ml;
         if (url.startsWith(File.separator)) {
         if ((ml = new MediaLocator("file:" + url)) != null)
              return ml;
         } else {
         String file = "file:" + System.getProperty("user.dir") + File.separator + url;
         if ((ml = new MediaLocator(file)) != null)
              return ml;
         return null;
    // Inner classes.
    * A DataSource to read from a list of JPEG image files and
    * turn that into a stream of JMF buffers.
    * The DataSource is not seekable or positionable.
    class ImageDataSource extends PullBufferDataSource {
         ImageSourceStream streams[];
         ImageDataSource(int width, int height, int frameRate, Vector images) {
         streams = new ImageSourceStream[1];
         streams[0] = new ImageSourceStream(width, height, frameRate, images);
         public void setLocator(MediaLocator source) {
         public MediaLocator getLocator() {
         return null;
         * Content type is of RAW since we are sending buffers of video
         * frames without a container format.
         public String getContentType() {
         return ContentDescriptor.RAW;
         public void connect() {
         public void disconnect() {
         public void start() {
         public void stop() {
         * Return the ImageSourceStreams.
         public PullBufferStream[] getStreams() {
         return streams;
         * We could have derived the duration from the number of
         * frames and frame rate. But for the purpose of this program,
         * it's not necessary.
         public Time getDuration() {
         return DURATION_UNKNOWN;
         public Object[] getControls() {
         return new Object[0];
         public Object getControl(String type) {
         return null;
    * The source stream to go along with ImageDataSource.
    class ImageSourceStream implements PullBufferStream {
         Vector images;
         int width, height;
         VideoFormat format;
         int nextImage = 0;     // index of the next image to be read.
         boolean ended = false;
         public ImageSourceStream(int width, int height, int frameRate, Vector images) {
         this.width = width;
         this.height = height;
         this.images = images;
         format = new VideoFormat(VideoFormat.JPEG,
                        new Dimension(width, height),
                        Format.NOT_SPECIFIED,
                        Format.byteArray,
                        (float)frameRate);
         * We should never need to block assuming data are read from files.
         public boolean willReadBlock() {
         return false;
         * This is called from the Processor to read a frame worth
         * of video data.
         public void read(Buffer buf) throws IOException {
         // Check if we've finished all the frames.
         if (nextImage >= images.size()) {
              // We are done. Set EndOfMedia.
              System.err.println("Done reading all images.");
              buf.setEOM(true);
              buf.setOffset(0);
              buf.setLength(0);
              ended = true;
              return;
         String imageFile = (String)images.elementAt(nextImage);
         nextImage++;
         System.err.println(" - reading image file: " + imageFile);
         // Open a random access file for the next image.
         RandomAccessFile raFile;
         raFile = new RandomAccessFile(imageFile, "r");
         byte data[] = null;
         // Check the input buffer type & size.
         if (buf.getData() instanceof byte[])
              data = (byte[])buf.getData();
         // Check to see the given buffer is big enough for the frame.
         if (data == null || data.length < raFile.length()) {
              data = new byte[(int)raFile.length()];
              buf.setData(data);
         // Read the entire JPEG image from the file.
         raFile.readFully(data, 0, (int)raFile.length());
         System.err.println(" read " + raFile.length() + " bytes.");
         buf.setOffset(0);
         buf.setLength((int)raFile.length());
         buf.setFormat(format);
         buf.setFlags(buf.getFlags() | buf.FLAG_KEY_FRAME);
         // Close the random access file.
         raFile.close();
         * Return the format of each video frame. That will be JPEG.
         public Format getFormat() {
         return format;
         public ContentDescriptor getContentDescriptor() {
         return new ContentDescriptor(ContentDescriptor.RAW);
         public long getContentLength() {
         return 0;
         public boolean endOfStream() {
         return ended;
         public Object[] getControls() {
         return new Object[0];
         public Object getControl(String type) {
         return null;
    on executing with the command:
    java JpegImagesToMovie -w <width> -h <height> -f <frame rate per sec.> -o <output URL> <input JPEG file 1> <input JPEG file 2> ...
    comes this......
    Exception in thread"JMF thread:SendEventQueue:com.sun.media.processor.unknown Handler" java.lang.NullPointerException"
    plz help

    Don't forget to use the "Code Formatting Tags",
    see http://forum.java.sun.com/help.jspa?sec=formatting,
    so the posted code retains its original formatting.

  • IPhone 6 Trade-In Promotion Code That Works

    Okay, loads of posts about not getting the promotional amount and so on. I am in the same boat EXCEPT I haven't shipped my old iPhone back yet. I have been on the phone with Verizon three times trying to figure out how to get the trade-in page on their site to get the credit correctly stated so the shipping materials can be sent.
    I received this promo code from a Verizon Customer Service rep this morning who actually called me back. It was accepted by the vzw site and prints a receipt with the appraisal amount as well as the difference between that value and $200 so it totals up to what was advertised in the promotion. It is working as of today, November 5th, and I don't know for how much longer it will continue to do so.
    The website to use is: www.trade-in.vzw.com
    The promo code you enter that is currently working is: CAREIPHONE6200-Z3PG-8DV4
    IF you're planning on getting the trade-in promo amount of $200 they (Verizon-VZW) tells me I have until December 15th to send my old iPhone to them. Problem was NO promotional code. The old one didn't work after the promotion's end date. Of the posts I've read, most seem to be having trouble getting the full $200 pop for at least these common reasons/excuses from VZW (a contractor they have handling trade-ins). The list (likely not complete):
    1) Cracked screen
    2) Won't power on
    3) Case cracked
    4) Bad, missing or non-functional buttons
    5) Lock code still active (prevents access--yes, it does)
    6) Still connected to iCloud
    7)Find My iPhone still active
    Without documentation of the phone's condition the whole thing becomes a finger-pointing game. I've decided to do the following and recommend you do something similar if and before you send your old iPhone back:
    1) On the old phone, go to Settings/General
    2) In the right column of the General options at the very bottom is a Reset option
    3) Use this option and select Reset Phone And Erase All Data (wording may different but it's close enough)
    4) If you have an access code on the iPhone you'll have to enter it to do the process
    5) Two, "Are you sure?," style prompts must be pressed to verify you REALLY want to do this.
    6) After the second Are You Sure prompt is answered, the Apple shows up on the screen and following a complete reset and erase you're greeted with the Hello screen where you'd begin setup. At this point, the phone should no longer have an access code and should have been logged out of iCloud.
    7) Go through the setup screens and skip the ones that ask you to create a lock code, skip setting up an Apple ID and password, skip connecting to WiFi, DO SKIP turning on Find My iPhone. When you successfully reach what will now be an original Home screen, RUN THE RESET AND ERASE AGAIN. This verifies for you that there is no iCloud connection, and no access code.
    8) Take close up pics of the screen, the back, the sides, the buttons, the data/power port, everything. Even better, record a video and go from inspecting the iPhone's condition to and through a setup as described above to show there is no connection to iCloud or any access code. Then go begin the Reset and Erase process (still while recording video).
    9) Lots of users here write of the poor quality of packaging provided for shipping the trade-in, so if you still have the original box put the phone in that. Otherwise use some bubble wrap or another small sturdy box so the screen doesn't get broken or buttons stop working from poor handling by USPS or other shippers.
    Why pics and/or video? If you have to take the matter to arbitration or seek remedy from the BBB or other consumer resource there is nothing more convincing than good documentation.

        I can absolutely see the confusion regarding your trade in promotion, chimera09. But no worries! The iPhone trade in offer has a unique detail that will allow you to wait until you've received your iPhone 6. You can disregard the 30 days from submission that applies to the usual trade in program. The original portion you listed "return your old device to Verizon Wireless within 7 days after receiving your new iPhone 6 or iPhone 6 Plus, but no later than 12/01/14" is correct.
    JenniferH_VZW
    Follow us on Twitter www.twitter.com/vzwsupport

  • How can I write a code that triggers when clicking on Save button

    I want to hide certain fields inside my tracking list, if the login user is not part of the “Managers” group.
    To do so I want to add the following Page-load code inside a web part :-
    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
    using (SPWeb web = site.OpenWeb())
    {SPGroup group = site.Groups["Managers"];
    bool isUser = site.IsCurrentUserMemberOfGroup(group.ID);
    if (isUser)
    {textbox.Visible=false;}}
    And the following custom code that triggers when saving the form :-
    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
    using (SPWeb web = site.OpenWeb())
    SPList list = web.Lists["ListName"];web.AllowUnsafeUpdates = true;
    SPListItem item = list.Items[SPContext.Current.ListItem.UniqueId];
    txtTitle.Text = item["Title"] as string;item.Update();web.AllowUnsafeUpdates = false;
    But I am not sure where exactly I should add the custom code for the save button ? I tried writing it inside the Oninit method , but I got many errors as shown below:-
    So can anyone advice how i should write the web part to include the Page load & the custom save button code?
    second question in general is my above approach considered valid , i mean to hide/show list columns using web parts ?

    Hi,
    According to your post, my understanding is that you want to hide/show list columns based on specify the permission for Users, SharePoint Groups or Active Directory Groups.
    Here is a solution from CodePlex for your reference:
    SharePoint 2013 Column & View Permission
    https://sp2013columnpermission.codeplex.com/
    Best Regards
    Dennis Guo
    TechNet Community Support

Maybe you are looking for

  • Locked Out of Blackberry ID and password Please Please Help

    I updated my blackberry messenger and its asking me for my id and password I have tried doing another ID but its not letting me do anything now my messenger has gone and I have tried accessing my app word but it keeps saying that I am locked out for

  • Error loading plugins CC 2014

    I have build a plugin with AI SDK CC 2014 on Win 7. But the plugin cannot be loaded by one customer (CC2014 18.1.0, Win7 ultimate 64-bit).  Only a message pops up with 'Error loading plugins xxx.aip'. The plugin works fine on other machines with the

  • HT201232 How to disable USB mass storage in MAC 10.10

    Hi Everyone , Can you tell me How I can disable USB mass storage in MAC 10.10 ? It will be very helpfull if you send it to me in SOP format .

  • Error parsing using SAXP

    Hi all, I would like your help in the following: If I pass a file name as an argument of a parse method, it gives me an error like: java.net.MalformedURLException: unknown protocol: c However, if I pass an URL as an argument, it gives me an error lik

  • Crash after installing 10.6.8 update

    After installing the 10.6.8 update on my Macbook Pro, it now crashes on startup every time. I can boot only if I do a safe start by holding down the shift key. I've tried repairig permissios and reinstalling several times. Anyone have any other ideas