Search Results

Search found 1096 results on 44 pages for 'never quit'.

Page 6/44 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Quitting application in Android

    - by Danail
    I want to quit application in Android. Just put a "quit" button, which kills my app. I know I shouldn't do this. I know that this is not the philosophy of the OS. If you know how it can be done, pls share. In the app, I have many opened activities, so "finish()" will not do the job. Thank you for your information in advance. Danail

    Read the article

  • JMS Step 2 - Using the QueueSend.java Sample Program to Send a Message to a JMS Queue

    - by John-Brown.Evans
    JMS Step 2 - Using the QueueSend.java Sample Program to Send a Message to a JMS Queue .c21_2{vertical-align:top;width:487.3pt;border-style:solid;border-color:#000000;border-width:1pt;padding:5pt 5pt 5pt 5pt} .c15_2{vertical-align:top;width:487.3pt;border-style:solid;border-color:#ffffff;border-width:1pt;padding:5pt 5pt 5pt 5pt} .c0_2{padding-left:0pt;direction:ltr;margin-left:36pt} .c20_2{list-style-type:circle;margin:0;padding:0} .c10_2{list-style-type:disc;margin:0;padding:0} .c6_2{background-color:#ffffff} .c17_2{padding-left:0pt;margin-left:72pt} .c3_2{line-height:1.0;direction:ltr} .c1_2{font-size:10pt;font-family:"Courier New"} .c16_2{color:#1155cc;text-decoration:underline} .c13_2{color:inherit;text-decoration:inherit} .c7_2{background-color:#ffff00} .c9_2{border-collapse:collapse} .c2_2{font-family:"Courier New"} .c18_2{font-size:18pt} .c5_2{font-weight:bold} .c19_2{color:#ff0000} .c12_2{background-color:#f3f3f3;border-style:solid;border-color:#000000;border-width:1pt;} .c14_2{font-size:24pt} .c8_2{direction:ltr;background-color:#ffffff} .c11_2{font-style:italic} .c4_2{height:11pt} .title{padding-top:24pt;line-height:1.15;text-align:left;color:#000000;font-size:36pt;font-family:"Arial";font-weight:bold;padding-bottom:6pt}.subtitle{padding-top:18pt;line-height:1.15;text-align:left;color:#666666;font-style:italic;font-size:24pt;font-family:"Georgia";padding-bottom:4pt} li{color:#000000;font-size:10pt;font-family:"Arial"} p{color:#000000;font-size:10pt;margin:0;font-family:"Arial"} h1{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-size:24pt;font-family:"Arial";font-weight:normal;padding-bottom:0pt} h2{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-size:18pt;font-family:"Arial";font-weight:normal;padding-bottom:0pt} h3{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-size:14pt;font-family:"Arial";font-weight:normal;padding-bottom:0pt} h4{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-size:12pt;font-family:"Arial";font-weight:normal;padding-bottom:0pt} h5{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-size:11pt;font-family:"Arial";font-weight:normal;padding-bottom:0pt} h6{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-size:10pt;font-family:"Arial";font-weight:normal;padding-bottom:0pt} This post is the second in a series of JMS articles which demonstrate how to use JMS queues in a SOA context. In the previous post JMS Step 1 - How to Create a Simple JMS Queue in Weblogic Server 11g I showed you how to create a JMS queue and its dependent objects in WebLogic Server. In this article, we will use a sample program to write a message to that queue. Please review the previous post if you have not created those objects yet, as they will be required later in this example. The previous post also includes useful background information and links to the Oracle documentation for addional research. The following post in this series will show how to read the message from the queue again. 1. Source code The following java code will be used to write a message to the JMS queue. It is based on a sample program provided with the WebLogic Server installation. The sample is not installed by default, but needs to be installed manually using the WebLogic Server Custom Installation option, together with many, other useful samples. You can either copy-paste the following code into your editor, or install all the samples. The knowledge base article in My Oracle Support: How To Install WebLogic Server and JMS Samples in WLS 10.3.x (Doc ID 1499719.1) describes how to install the samples. QueueSend.java package examples.jms.queue; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Hashtable; import javax.jms.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; /** This example shows how to establish a connection * and send messages to the JMS queue. The classes in this * package operate on the same JMS queue. Run the classes together to * witness messages being sent and received, and to browse the queue * for messages. The class is used to send messages to the queue. * * @author Copyright (c) 1999-2005 by BEA Systems, Inc. All Rights Reserved. */ public class QueueSend { // Defines the JNDI context factory. public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory"; // Defines the JMS context factory. public final static String JMS_FACTORY="jms/TestConnectionFactory"; // Defines the queue. public final static String QUEUE="jms/TestJMSQueue"; private QueueConnectionFactory qconFactory; private QueueConnection qcon; private QueueSession qsession; private QueueSender qsender; private Queue queue; private TextMessage msg; /** * Creates all the necessary objects for sending * messages to a JMS queue. * * @param ctx JNDI initial context * @param queueName name of queue * @exception NamingException if operation cannot be performed * @exception JMSException if JMS fails to initialize due to internal error */ public void init(Context ctx, String queueName) throws NamingException, JMSException { qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY); qcon = qconFactory.createQueueConnection(); qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queue = (Queue) ctx.lookup(queueName); qsender = qsession.createSender(queue); msg = qsession.createTextMessage(); qcon.start(); } /** * Sends a message to a JMS queue. * * @param message message to be sent * @exception JMSException if JMS fails to send message due to internal error */ public void send(String message) throws JMSException { msg.setText(message); qsender.send(msg); } /** * Closes JMS objects. * @exception JMSException if JMS fails to close objects due to internal error */ public void close() throws JMSException { qsender.close(); qsession.close(); qcon.close(); } /** main() method. * * @param args WebLogic Server URL * @exception Exception if operation fails */ public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: java examples.jms.queue.QueueSend WebLogicURL"); return; } InitialContext ic = getInitialContext(args[0]); QueueSend qs = new QueueSend(); qs.init(ic, QUEUE); readAndSend(qs); qs.close(); } private static void readAndSend(QueueSend qs) throws IOException, JMSException { BufferedReader msgStream = new BufferedReader(new InputStreamReader(System.in)); String line=null; boolean quitNow = false; do { System.out.print("Enter message (\"quit\" to quit): \n"); line = msgStream.readLine(); if (line != null && line.trim().length() != 0) { qs.send(line); System.out.println("JMS Message Sent: "+line+"\n"); quitNow = line.equalsIgnoreCase("quit"); } } while (! quitNow); } private static InitialContext getInitialContext(String url) throws NamingException { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY); env.put(Context.PROVIDER_URL, url); return new InitialContext(env); } } 2. How to Use This Class 2.1 From the file system on UNIX/Linux Log in to a machine with a WebLogic installation and create a directory to contain the source and code matching the package name, e.g. $HOME/examples/jms/queue. Copy the above QueueSend.java file to this directory. Set the CLASSPATH and environment to match the WebLogic server environment. Go to $MIDDLEWARE_HOME/user_projects/domains/base_domain/bin  and execute . ./setDomainEnv.sh Collect the following information required to run the script: The JNDI name of a JMS queue to use In the Weblogic server console > Services > Messaging > JMS Modules > (Module name, e.g. TestJMSModule) > (JMS queue name, e.g. TestJMSQueue)Select the queue and note its JNDI name, e.g. jms/TestJMSQueue The JNDI name of a connection factory to connect to the queue Follow the same path as above to get the connection factory for the above queue, e.g. TestConnectionFactory and its JNDI namee.g. jms/TestConnectionFactory The URL and port of the WebLogic server running the above queue Check the JMS server for the above queue and the managed server it is targeted to, for example soa_server1. Now find the port this managed server is listening on, by looking at its entry under Environment > Servers in the WLS console, e.g. 8001 The URL for the server to be given to the QueueSend program in this example will therefore be t3://host.domain:8001 e.g. t3://jbevans-lx.de.oracle.com:8001 Edit QueueSend.java and enter the above queue name and connection factory respectively under ...public final static String  JMS_FACTORY=" jms/TestConnectionFactory "; ... public final static String QUEUE=" jms/TestJMSQueue "; ... Compile QueueSend.java using javac QueueSend.java Go to the source’s top-level directory and execute it using java examples.jms.queue.QueueSend t3://jbevans-lx.de.oracle.com:8001 This will prompt for a text input or “quit” to end. In the WLS console, go to the queue and select Monitoring to confirm that a new message was written to the queue. 2.2 From JDeveloper Create a new application in JDeveloper, called, for example JMSTests. When prompted for a project name, enter QueueSend and select Java as the technology Default Package = examples.jms.queue (but you can enter anything here as you will overwrite it in the code later). Leave the other values at their defaults. Press Finish Create a new Java class called QueueSend and use the default values This will create a file called QueueSend.java. Open QueueSend.java, if it is not already open and replace all its contents with the QueueSend java code listed above Some lines might have warnings due to unfound objects. These are due to missing libraries in the JDeveloper project. Add the following libraries to the JDeveloper project: right-click the QueueSend  project in the navigation menu and select Libraries and Classpath , then Add JAR/Directory  Go to the folder containing the JDeveloper installation and find/choose the file javax.jms_1.1.1.jar , e.g. at D:\oracle\jdev11116\modules\javax.jms_1.1.1.jar Do the same for the weblogic.jar file located, for example in D:\oracle\jdev11116\wlserver_10.3\server\lib\weblogic.jar Now you should be able to compile the project, for example by selecting the Make or Rebuild icons   If you try to execute the project, you will get a usage message, as it requires a parameter pointing to the WLS installation containing the JMS queue, for example t3://jbevans-lx.de.oracle.com:8001 . You can automatically pass this parameter to the program from JDeveloper by editing the project’s Run/Debug/Profile. Select the project properties, select Run/Debug/Profile and edit the Default run configuration and add the connection parameter to the Program Arguments field If you execute it again, you will see that it has passed the parameter to the start command If you get a ClassNotFoundException for the class weblogic.jndi.WLInitialContextFactory , then check that the weblogic.jar file was correctly added to the project in one of the earlier steps above. Set the values of JMS_FACTORY and QUEUE the same way as described above in the description of how to use this from a Linux file system, i.e. ...public final static String  JMS_FACTORY=" jms/TestConnectionFactory "; ... public final static String QUEUE=" jms/TestJMSQueue "; ... You need to make one more change to the project. If you execute it now, it will prompt for the payload for the JMS message, but you won’t be able to enter it by default in JDeveloper. You need to enable program input for the project first. Select the project’s properties, then Tool Settings, then check the Allow Program Input checkbox at the bottom and Save. Now when you execute the project, you will get a text entry field at the bottom into which you can enter the payload. You can enter multiple messages until you enter “quit”, which will cause the program to stop. The following screen shot shows the TestJMSQueue’s Monitoring page, after a message was sent to the queue: This concludes the sample. In the following post I will show you how to read the message from the queue again.

    Read the article

  • C++ SDL State Machine Segfault

    - by user1602079
    The code compiles and builds fine, but it immediately segfaults. I've looked at this for a while and have no idea why. Any help is appreciated. Thank you! Here's the code: main.cpp #include "SDL/SDL.h" #include "Globals.h" #include "Core.h" #include "GameStates.h" #include "Introduction.h" int main(int argc, char** args) { if(core.Initilize() == false) { SDL_Quit(); } while(core.desiredstate != core.Quit) { currentstate->EventHandling(); currentstate->Logic(); core.ChangeState(); currentstate->Render(); currentstate->Update(); } SDL_Quit(); } Core.h #ifndef CORE_H #define CORE_H #include "SDL/SDL.h" #include <string> class Core { public: SDL_Surface* Load(std::string filename); void ApplySurface(int X, int Y, SDL_Surface* source, SDL_Surface* destination); void SetState(int newstate); void ChangeState(); enum state { Intro, STATES_NULL, Quit }; int desiredstate, stateID; bool Initilize(); }; #endif Core.cpp #include "Core.h" #include "SDL/SDL.h" #include "Globals.h" #include "Introduction.h" #include <string> /* Initilizes SDL subsystems */ bool Core::Initilize() { //Inits subsystems, reutrns false upon error if(SDL_Init(SDL_INIT_EVERYTHING) == -1) { return false; } SDL_WM_SetCaption("Game", NULL); return true; } /* Loads surfaces and optimizes them */ SDL_Surface* Core::Load(std::string filename) { //The surface to be optimized SDL_Surface* original = SDL_LoadBMP(filename.c_str()); //The optimized surface SDL_Surface* optimized = NULL; //Optimizes the image if it loaded properly if(original != NULL) { optimized = SDL_DisplayFormat(original); SDL_FreeSurface(original); } else { //returns NULL upon error return NULL; } return optimized; } /* Blits surfaces */ void Core::ApplySurface(int X, int Y, SDL_Surface* source, SDL_Surface* destination) { //Stores the coordinates of the surface SDL_Rect offsets; offsets.x = X; offsets.y = Y; //Bits the surface if both surfaces are present if(source != NULL && destination != NULL) { SDL_BlitSurface(source, NULL, destination, &offsets); } } /* Sets desiredstate to newstate */ void Core::SetState(int newstate) { if(desiredstate != Quit) { desiredstate = newstate; } } /* Changes the game state */ void Core::ChangeState() { if(desiredstate != STATES_NULL && desiredstate != Quit) { delete currentstate; switch(desiredstate) { case Intro: currentstate = new Introduction(); break; } stateID = desiredstate; desiredstate = core.STATES_NULL; } } Globals.h #ifndef GLOBALS_H #define GLOBALS_H #include "SDL/SDL.h" #include "Core.h" #include "GameStates.h" extern SDL_Surface* screen; extern Core core; extern GameStates* currentstate; #endif Globals.cpp #include "Globals.h" #include "SDL/SDL.h" #include "GameStates.h" SDL_Surface* screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE); Core core; GameStates* currentstate = NULL; GameStates.h #ifndef GAMESTATES_H #define GAMESTATES_H class GameStates { public: virtual void EventHandling() = 0; virtual void Logic() = 0; virtual void Render() = 0; virtual void Update() = 0; }; #endif Introduction.h #ifndef INTRODUCTION_H #define INTRODUCTION_H #include "GameStates.h" #include "Globals.h" class Introduction : public GameStates { public: Introduction(); private: void EventHandling(); void Logic(); void Render(); void Update(); ~Introduction(); SDL_Surface* test; }; #endif Introduction.cpp #include "SDL/SDL.h" #include "Core.h" #include "Globals.h" #include "Introduction.h" /* Loads all the assets */ Introduction::Introduction() { test = core.Load("test.bmp"); } void Introduction::EventHandling() { SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: core.SetState(core.Quit); break; } } } void Introduction::Logic() { //to be coded } void Introduction::Render() { core.ApplySurface(30, 30, test, screen); } void Introduction::Update() { SDL_Flip(screen); } Introduction::~Introduction() { SDL_FreeSurface(test); } Sorry if the formatting is a bit off... Having to put four spaces for it to be put into a code block offset it a bit. I ran it through gdb and this is what I got: Program received signal SIGSEGV, Segmentation fault. 0x0000000000400e46 in main () Which isn't incredibly useful... Any help is appreciated. Thank you!

    Read the article

  • Couldn't match expected type - Haskell Code

    - by wvyar
    I'm trying to learn Haskell, but the small bit of sample code I tried to write is running into a fairly large amount of "Couldn't match expected type" errors. Can anyone give me some guidance as to what I'm doing wrong/how I should go about this? These are the errors, but I'm not really sure how I should be writing my code. toDoSchedulerSimple.hs:6:14: Couldn't match expected type `[t0]' with actual type `IO String' In the return type of a call of `readFile' In a stmt of a 'do' block: f <- readFile inFile In the expression: do { f <- readFile inFile; lines f } toDoSchedulerSimple.hs:27:9: Couldn't match expected type `[a0]' with actual type `IO ()' In the return type of a call of `putStr' In a stmt of a 'do' block: putStr "Enter task name: " In the expression: do { putStr "Enter task name: "; task <- getLine; return inFileArray : task } toDoSchedulerSimple.hs:34:9: Couldn't match expected type `IO ()' with actual type `[a0]' In a stmt of a 'do' block: putStrLn "Your task is: " ++ (inFileArray !! i) In the expression: do { i <- randomRIO (0, (length inFileArray - 1)); putStrLn "Your task is: " ++ (inFileArray !! i) } In an equation for `getTask': getTask inFileArray = do { i <- randomRIO (0, (length inFileArray - 1)); putStrLn "Your task is: " ++ (inFileArray !! i) } toDoSchedulerSimple.hs:41:9: Couldn't match expected type `[a0]' with actual type `IO ()' In the return type of a call of `putStr' In a stmt of a 'do' block: putStr "Enter the task you would like to end: " In the expression: do { putStr "Enter the task you would like to end: "; task <- getLine; filter (endTaskCheck task) inFileArray } toDoSchedulerSimple.hs:60:53: Couldn't match expected type `IO ()' with actual type `[String] -> IO ()' In a stmt of a 'do' block: schedulerSimpleMain In the expression: do { (getTask inFileArray); schedulerSimpleMain } In a case alternative: "get-task" -> do { (getTask inFileArray); schedulerSimpleMain } This is the code itself. I think it's fairly straightforward, but the idea is to run a loop, take input, and perform actions based off of it by calling other functions. import System.Random (randomRIO) import Data.List (lines) initializeFile :: [char] -> [String] initializeFile inFile = do f <- readFile inFile let parsedFile = lines f return parsedFile displayHelp :: IO() displayHelp = do putStrLn "Welcome to To Do Scheduler Simple, written in Haskell." putStrLn "Here are some commands you might find useful:" putStrLn " 'help' : Display this menu." putStrLn " 'quit' : Exit the program." putStrLn " 'new-task' : Create a new task." putStrLn " 'get-task' : Randomly select a task." putStrLn " 'end-task' : Mark a task as finished." putStrLn " 'view-tasks' : View all of your tasks." quit :: IO() quit = do putStrLn "We're very sad to see you go...:(" putStrLn "Come back soon!" createTask :: [String] -> [String] createTask inFileArray = do putStr "Enter task name: " task <- getLine return inFileArray:task getTask :: [String] -> IO() getTask inFileArray = do i <- randomRIO (0, (length inFileArray - 1)) putStrLn "Your task is: " ++ (inFileArray !! i) endTaskCheck :: String -> String -> Bool endTaskCheck str1 str2 = str1 /= str2 endTask :: [String] -> [String] endTask inFileArray = do putStr "Enter the task you would like to end: " task <- getLine return filter (endTaskCheck task) inFileArray viewTasks :: [String] -> IO() viewTasks inFileArray = case inFileArray of [] -> do putStrLn "\nEnd of tasks." _ -> do putStrLn (head inFileArray) viewTasks (tail inFileArray) schedulerSimpleMain :: [String] -> IO() schedulerSimpleMain inFileArray = do putStr "SchedulerSimple> " input <- getLine case input of "help" -> displayHelp "quit" -> quit "new-task" -> schedulerSimpleMain (createTask inFileArray) "get-task" -> do (getTask inFileArray); schedulerSimpleMain "end-task" -> schedulerSimpleMain (endTask inFileArray) "view-tasks" -> do (viewTasks inFileArray); schedulerSimpleMain _ -> do putStrLn "Invalid input."; schedulerSimpleMain main :: IO() main = do putStr "What is the name of the schedule? " sName <- getLine schedulerSimpleMain (initializeFile sName) Thanks, and apologies if this isn't the correct place to be asking such a question.

    Read the article

  • Help me create a Firefox extension (Javascript XPCOM Component)

    - by Johnny Grass
    I've been looking at different tutorials and I know I'm close but I'm getting lost in implementation details because some of them are a little bit dated and a few things have changed since Firefox 3. I have already written the javascript for the firefox extension, now I need to make it into an XPCOM component. This is the functionality that I need: My Javascript file is simple, I have two functions startServer() and stopServer. I need to run startServer() when the browser starts and stopServer() when firefox quits. Edit: I've updated my code with a working solution (thanks to Neil). The following is in MyExtension/components/myextension.js. Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); const CI = Components.interfaces, CC = Components.classes, CR = Components.results; // class declaration function MyExtension() {} MyExtension.prototype = { classDescription: "My Firefox Extension", classID: Components.ID("{xxxx-xxxx-xxx-xxxxx}"), contractID: "@example.com/MyExtension;1", QueryInterface: XPCOMUtils.generateQI([CI.nsIObserver]), // add to category manager _xpcom_categories: [{ category: "profile-after-change" }], // start socket server startServer: function () { /* socket initialization code */ }, // stop socket server stopServer: function () { /* stop server */ }, observe: function(aSubject, aTopic, aData) { var obs = CC["@mozilla.org/observer-service;1"].getService(CI.nsIObserverService); switch (aTopic) { case "quit-application": this.stopServer(); obs.removeObserver(this, "quit-application"); break; case "profile-after-change": this.startServer(); obs.addObserver(this, "quit-application", false); break; default: throw Components.Exception("Unknown topic: " + aTopic); } } }; var components = [MyExtension]; function NSGetModule(compMgr, fileSpec) { return XPCOMUtils.generateModule(components); }

    Read the article

  • 'SImple' 2 class Java calculator doesn't accept inputs or do calculations

    - by Tony O'Keeffe
    Hi, I'm trying to get a two class java calculator working (new to java) to work but so far i'm having no success. the two classes are outlined below, calcFrame is for the interface and calEngine should do the actual calculations but i can't get them to talk to one another. i'd really appreciate any assistance on same. Thanks. CalcFrame Code - import java.awt.; import javax.swing.; import javax.swing.border.; import java.awt.event.; /** *A Class that operates as the framework for a calculator. *No calculations are performed in this section */ public class CalcFrame implements ActionListener { private CalcEngine calc; private JFrame frame; private JTextField display; private JLabel status; /** * Constructor for objects of class GridLayoutExample */ public CalcFrame() { makeFrame(); //calc = engine; } /** * This allows you to quit the calculator. */ // Alows the class to quit. private void quit() { System.exit(0); } // Calls the dialog frame with the information about the project. private void showAbout() { JOptionPane.showMessageDialog(frame, "Group Project", "About Calculator Group Project", JOptionPane.INFORMATION_MESSAGE); } private void makeFrame() { frame = new JFrame("Group Project Calculator"); makeMenuBar(frame); JPanel contentPane = (JPanel)frame.getContentPane(); contentPane.setLayout(new BorderLayout(8, 8)); contentPane.setBorder(new EmptyBorder( 10, 10, 10, 10)); /** * Insert a text field */ display = new JTextField(); contentPane.add(display, BorderLayout.NORTH); //Container contentPane = frame.getContentPane(); contentPane.setLayout(new GridLayout(4, 4)); JPanel buttonPanel = new JPanel(new GridLayout(4, 4)); contentPane.add(new JButton("1")); contentPane.add(new JButton("2")); contentPane.add(new JButton("3")); contentPane.add(new JButton("4")); contentPane.add(new JButton("5")); contentPane.add(new JButton("6")); contentPane.add(new JButton("7")); contentPane.add(new JButton("8")); contentPane.add(new JButton("9")); contentPane.add(new JButton("0")); contentPane.add(new JButton("+")); contentPane.add(new JButton("-")); contentPane.add(new JButton("/")); contentPane.add(new JButton("*")); contentPane.add(new JButton("=")); contentPane.add(new JButton("C")); contentPane.add(buttonPanel, BorderLayout.CENTER); //status = new JLabel(calc.getAuthor()); //contentPane.add(status, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } /** * Create the main frame's menu bar. * The frame that the menu bar should be added to. */ private void makeMenuBar(JFrame frame) { final int SHORTCUT_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); JMenuBar menubar = new JMenuBar(); frame.setJMenuBar(menubar); JMenu menu; JMenuItem item; // create the File menu menu = new JMenu("File"); menubar.add(menu); // create the Quit menu with a shortcut "Q" key. item = new JMenuItem("Quit"); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK)); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { quit(); } }); menu.add(item); // Adds an about menu. menu = new JMenu("About"); menubar.add(menu); // Displays item = new JMenuItem("Calculator Project"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showAbout(); } }); menu.add(item); } /** * An interface action has been performed. * Find out what it was and handle it. * @param event The event that has occured. */ public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if(command.equals("0") || command.equals("1") || command.equals("2") || command.equals("3") || command.equals("4") || command.equals("5") || command.equals("6") || command.equals("7") || command.equals("8") || command.equals("9")) { int number = Integer.parseInt(command); calc.numberPressed(number); } else if(command.equals("+")) { calc.plus(); } else if(command.equals("-")) { calc.minus(); } else if(command.equals("=")) { calc.equals(); } else if(command.equals("C")) { calc.clear(); } else if(command.equals("?")) { } // else unknown command. redisplay(); } /** * Update the interface display to show the current value of the * calculator. */ private void redisplay() { display.setText("" + calc.getDisplayValue()); } /** * Toggle the info display in the calculator's status area between the * author and version information. */ } CalcEngine - public class CalcEngine { // The calculator's state is maintained in three fields: // buildingDisplayValue, haveLeftOperand, and lastOperator. // The current value (to be) shown in the display. private int displayValue; // The value of an existing left operand. private int leftOperand; /** * Create a CalcEngine. */ public CalcEngine() { clear(); } public int getDisplayValue() { return displayValue; } /** * A number button was pressed. * Either start a new operand, or incorporate this number as * the least significant digit of an existing one. * @param number The number pressed on the calculator. */ public void numberPressed(int number) { if(buildingDisplayValue) { // Incorporate this digit. displayValue = displayValue*10 + number; } else { // Start building a new number. displayValue = number; buildingDisplayValue = true; } } /** * The 'plus' button was pressed. */ public void plus() { applyOperator('+'); } /** * The 'minus' button was pressed. */ public void minus() { applyOperator('-'); } /** * The '=' button was pressed. */ public void equals() { // This should completes the building of a second operand, // so ensure that we really have a left operand, an operator // and a right operand. if(haveLeftOperand && lastOperator != '?' && buildingDisplayValue) { calculateResult(); lastOperator = '?'; buildingDisplayValue = false; } else { keySequenceError(); } } /** * The 'C' (clear) button was pressed. * Reset everything to a starting state. */ public void clear() { lastOperator = '?'; haveLeftOperand = false; buildingDisplayValue = false; displayValue = 0; } /** * @return The title of this calculation engine. */ public String getTitle() { return "Java Calculator"; } /** * @return The author of this engine. */ public String getAuthor() { return "David J. Barnes and Michael Kolling"; } /** * @return The version number of this engine. */ public String getVersion() { return "Version 1.0"; } /** * Combine leftOperand, lastOperator, and the * current display value. * The result becomes both the leftOperand and * the new display value. */ private void calculateResult() { switch(lastOperator) { case '+': displayValue = leftOperand + displayValue; haveLeftOperand = true; leftOperand = displayValue; break; case '-': displayValue = leftOperand - displayValue; haveLeftOperand = true; leftOperand = displayValue; break; default: keySequenceError(); break; } } /** * Apply an operator. * @param operator The operator to apply. */ private void applyOperator(char operator) { // If we are not in the process of building a new operand // then it is an error, unless we have just calculated a // result using '='. if(!buildingDisplayValue && !(haveLeftOperand && lastOperator == '?')) { keySequenceError(); return; } if(lastOperator != '?') { // First apply the previous operator. calculateResult(); } else { // The displayValue now becomes the left operand of this // new operator. haveLeftOperand = true; leftOperand = displayValue; } lastOperator = operator; buildingDisplayValue = false; } /** * Report an error in the sequence of keys that was pressed. */ private void keySequenceError() { System.out.println("A key sequence error has occurred."); // Reset everything. clear(); } }

    Read the article

  • small code redundancy within while-loops (doesn't feel clean)

    - by wallacoloo
    So, in Python (though I think it can be applied to many languages), I find myself with something like this quite often: the_input = raw_input("what to print?\n") while the_input != "quit": print the_input the_input = raw_input("what to print?\n") Maybe I'm being too picky, but I don't like how the line the_input = raw_input("what to print?\n") has to get repeated. It decreases maintainability and organization. But I don't see any workarounds for avoiding the duplicate code without further decreasing the problem. In some languages, I could write something like this: while ((the_input=raw_input("what to print?\n")) != "quit") { print the_input } This is definitely not Pythonic, and Python doesn't even allow for assignment within loop conditions AFAIK. This valid code fixes the redundancy, while 1: the_input = raw_input("what to print?\n") if the_input == "quit": break print the_input But doesn't feel quite right either. The while 1 implies that this loop will run forever; I'm using a loop, but giving it a fake condition and putting the real one inside it. Am I being too picky? Is there a better way to do this? Perhaps there's some language construct designed for this that I don't know of?

    Read the article

  • media.set_xx giving me grief!

    - by Firas
    New guy here. I asked a while back about a sprite recolouring program that I was having difficulty with and got some great responses. Basically, I tried to write a program that would recolour pixels of all the pictures in a given folder from one given colour to another. I believe I have it down, but, now the program is telling me that I have an invalid value specified for the red component of my colour. (ValueError: Invalid red value specified.), even though it's only being changed from 64 to 56. Any help on the matter would be appreciated! (Here's the code, in case I messed up somewhere else; It's in Python): import os import media import sys def recolour(old, new, folder): old_list = old.split(' ') new_list = new.split(' ') folder_location = os.path.join('C:\', 'Users', 'Owner', 'Spriting', folder) for filename in os.listdir (folder): current_file = media.load_picture(folder_location + '\\' + filename) for pix in current_file: if (media.get_red(pix) == int(old_list[0])) and \ (media.get_green(pix) == int(old_list[1])) and \ (media.get_blue(pix) == int(old_list[2])): media.set_red(pix, new_list[0]) media.set_green(pix, new_list[1]) media.set_blue(pix, new_list[2]) media.save(pic) if name == 'main': while 1: old = str(raw_input('Please insert the original RGB component, separated by a single space: ')) if old == 'quit': sys.exit(0) new = str(raw_input('Please insert the new RGB component, separated by a single space: ')) if new == 'quit': sys.exit(0) folder = str(raw_input('Please insert the name of the folder you wish to modify: ')) if folder == 'quit': sys.exit(0) else: recolour(old, new, folder)

    Read the article

  • How to keep the CPU usage down while running an SDL program?

    - by budwiser
    I've done a very basic window with SDL and want to keep it running until I press the X on window. #include "SDL.h" const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; int main(int argc, char **argv) { SDL_Init( SDL_INIT_VIDEO ); SDL_Surface* screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, 0, SDL_HWSURFACE | SDL_DOUBLEBUF ); SDL_WM_SetCaption( "SDL Test", 0 ); SDL_Event event; bool quit = false; while (quit != false) { if (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { quit = true; } } SDL_Delay(80); } SDL_Quit(); return 0; } I tried adding SDL_Delay() at the end of the while-clause and it worked quite well. However, 80 ms seemed to be the highest value I could use to keep the program running smoothly and even then the CPU usage is about 15-20%. Is this the best way to do this and do I have to just live with the fact that it eats this much CPU already on this point?

    Read the article

  • Error Expected Loop VBScript

    - by Yoko21
    I have a script that opens up an excel file if the password provided is correct. If its wrong, it prompts a message. It works perfectly when I add a loop at the end. However, the problem is whenever the password is wrong the script won't stop asking for the password because of the loop. What I want is the script to quit/close if the password is wrong. I tried to remove the loop and replaced it with "wscript.quit" but it always prompts the message "expected loop". Here is the code I made. password = "pass" do ask=inputbox ("Please enter password:","DProject") select case ask case password answer=true Set xl = CreateObject("Excel.application") xl.Application.Workbooks.Open "C:\Users\test1\Desktop\test.xlsx" xl.Application.Visible = True Set xl = Nothing wscript.quit end select answer=false x=msgbox("Password incorrect... Aborting") loop until answer=true Is it possible to put a message like that counts when aborting. like "Aborting in 3.... 2... 1".

    Read the article

  • Monitoring slow nginx/unicorn requests

    - by injekt
    I'm currently using Nginx to proxy requests to a Unicorn server running a Sinatra application. The application only has a couple of routes defined, those of which make fairly simple (non costly) queries to a PostgreSQL database, and finally return data in JSON format, these services are being monitored by God. I'm currently experiencing extremely slow response times from this application server. I have another two Unicorn servers being proxied via Nginx, and these are responding perfectly fine, so I think I can rule out any wrong doing from Nginx. Here is my God configuration: # God configuration APP_ROOT = File.expand_path '../', File.dirname(__FILE__) God.watch do |w| w.name = "app_name" w.interval = 30.seconds # default w.start = "cd #{APP_ROOT} && unicorn -c #{APP_ROOT}/config/unicorn.rb -D" # -QUIT = graceful shutdown, waits for workers to finish their current request before finishing w.stop = "kill -QUIT `cat #{APP_ROOT}/tmp/unicorn.pid`" w.restart = "kill -USR2 `cat #{APP_ROOT}/tmp/unicorn.pid`" w.start_grace = 10.seconds w.restart_grace = 10.seconds w.pid_file = "#{APP_ROOT}/tmp/unicorn.pid" # User under which to run the process w.uid = 'web' w.gid = 'web' # Cleanup the pid file (this is needed for processes running as a daemon) w.behavior(:clean_pid_file) # Conditions under which to start the process w.start_if do |start| start.condition(:process_running) do |c| c.interval = 5.seconds c.running = false end end # Conditions under which to restart the process w.restart_if do |restart| restart.condition(:memory_usage) do |c| c.above = 150.megabytes c.times = [3, 5] # 3 out of 5 intervals end restart.condition(:cpu_usage) do |c| c.above = 50.percent c.times = 5 end end w.lifecycle do |on| on.condition(:flapping) do |c| c.to_state = [:start, :restart] c.times = 5 c.within = 5.minute c.transition = :unmonitored c.retry_in = 10.minutes c.retry_times = 5 c.retry_within = 2.hours end end end Here is my Unicorn configuration: # Unicorn configuration file APP_ROOT = File.expand_path '../', File.dirname(__FILE__) worker_processes 8 preload_app true pid "#{APP_ROOT}/tmp/unicorn.pid" listen 8001 stderr_path "#{APP_ROOT}/log/unicorn.stderr.log" stdout_path "#{APP_ROOT}/log/unicorn.stdout.log" before_fork do |server, worker| old_pid = "#{APP_ROOT}/tmp/unicorn.pid.oldbin" if File.exists?(old_pid) && server.pid != old_pid begin Process.kill("QUIT", File.read(old_pid).to_i) rescue Errno::ENOENT, Errno::ESRCH # someone else did our job for us end end end I have checked God status logs but it appears CPU and Memory Usage are never out of bounds. I also have something to kill high memory workers, which can be found on the GitHub blog page here. When running a tail -f on the Unicorn logs I see some requests, but they're far and few between, when I was at around 60-100 a second before this trouble seemed to have arrived. This log also shows workers being reaped and started as expected. So my question is, how would I go about debugging this? What are the next steps I should be taking? I'm extremely baffled that the server will sometimes respond quickly, but at others time it's very slow, for long periods of time (which may or may not be peak traffic times). Any advice is much appreciated.

    Read the article

  • Exim - Sender verify failed - rejected RCPT

    - by Newtonx
    While checking on Exim's log messages I found many entries of the following message "Sender verify failed" "rejected RCPT" ... I 'm not an exim expert... I'm afraid Exim is not delivering 100% emails to recipients, because our Email Marketing Application its getting a lower OPEN RATE. Can someone helpe understand this log messages? Is it my server saying "No Such User Here" or a remote server? 174.111.111.11 represents my server IP. Thanks Exim log 2010-10-02 14:00:19 SMTP connection from myserverdomain.com.br () [174.111.111.11]:54514 I=[174.111.111.11]:25 closed by QUIT 2010-10-02 14:00:19 SMTP connection from [174.111.111.11]:54515 I=[174.111.111.11]:25 (TCP/IP connection count = 2) 2010-10-02 14:00:19 H=myserverdomain.com.br () [174.111.111.11]:54515 I=[174.111.111.11]:25 Warning: Sender rate 672.4 / 1h 2010-10-02 14:00:19 H=myserverdomain.com.br () [174.111.111.11]:54515 I=[174.111.111.11]:25 sender verify fail for <[email protected]>: No Such User Here 2010-10-02 14:00:19 H=myserverdomain.com.br () [174.111.111.11]:54515 I=[174.111.111.11]:25 F=<[email protected]> rejected RCPT <[email protected]>: Sender verify failed 2010-10-02 14:00:19 SMTP connection from myserverdomain.com.br () [174.111.111.11]:54515 I=[174.111.111.11]:25 closed by QUIT 2010-10-02 14:00:19 SMTP connection from [174.111.111.11]:54516 I=[174.111.111.11]:25 (TCP/IP connection count = 2) 2010-10-02 14:00:19 H=myserverdomain.com.br () [174.111.111.11]:54516 I=[174.111.111.11]:25 Warning: Sender rate 673.3 / 1h 2010-10-02 14:00:19 H=myserverdomain.com.br () [174.111.111.11]:54516 I=[174.111.111.11]:25 sender verify fail for <[email protected]>: No Such User Here 2010-10-02 14:00:19 H=myserverdomain.com.br () [174.111.111.11]:54516 I=[174.111.111.11]:25 F=<[email protected]> rejected RCPT <[email protected]>: Sender verify failed 2010-10-02 14:00:19 SMTP connection from myserverdomain.com.br () [174.111.111.11]:54516 I=[174.111.111.11]:25 closed by QUIT 2010-10-02 14:00:19 SMTP connection from [174.111.111.11]:54517 I=[174.111.111.11]:25 (TCP/IP connection count = 2) 2010-10-02 14:00:19 H=myserverdomain.com.br () [174.111.111.11]:54517 I=[174.111.111.11]:25 Warning: Sender rate 674.3 / 1h 2010-10-02 14:00:20 H=myserverdomain.com.br () [174.111.111.11]:54517 I=[174.111.111.11]:25 sender verify fail for <Luciene_souza_vasconcellos=hotmail.com--2723--bounce@e-mydomain.com.br>: No Such User Here 2010-10-02 14:00:20 H=myserverdomain.com.br () [174.111.111.11]:54517 I=[174.111.111.11]:25 F=<Luciene_souza_vasconcellos=hotmail.com--2723--bounce@e-mydomain.com.br> rejected RCPT <[email protected]>: Sender verify failed

    Read the article

  • Qmail Installation CentosI386

    - by tike
    I was trying to install qmailtoster in my centos server, i did all of the following not for once but repetitively as i got error and continued but i felt i need some help. i did follow all the steps of this wiki documentation. http://wiki.qmailtoaster.com/index.php/CentOS_5_QmailToaster_Install#Begin_Install followed all procedure when i came in a point to install i always got this error. cnt50-install-script.sh: line 80: rpmbuild: command not found error: File not found by glob: /usr/src/redhat/RPMS/i386/daemontools-toaster*.rpm Installing ucspi-tcp-toaster . . . Shall we continue? (yes, skip, quit) [y]/s/q: cnt50-install-script.sh.4: line 90: rpmbuild: command not found error: File not found by glob: /usr/src/redhat/RPMS/i386/ucspi-tcp-toaster*.rpm Installing vpopmail-toaster . . . Shall we continue? (yes, skip, quit) [y]/s/q: any suggestions please?

    Read the article

  • Trouble typing accented letters at the terminal prompt after launching Python

    - by Nicojo
    Edit: Using Mac OSX 10.6, whether I use Terminal.app or iTerm.app, when I launch Python, I can no longer type accented letters (e.g.é or ä). Any ideas? ORIGINAL POST: I am using iTerm 0.10. I would like to type in a string with accented characters (e.g. é) but when I do so at the iTerm prompt, no character appears. This does not occur in Terminal. Could someone help me find out what the problem is, and eventually fix it? EDIT: In Terminal.app, I can use accented characters. However, when I launch the Python 2.71 prompt, I can no longer type in accented characters. When I quit python and return to the terminal prompt, I can again type accented characters. In iTerm, although I quit Python and restarted iTerm, I cannot type in accented characters (I do not know if I could before).

    Read the article

  • MBP becomes very hot after using Xcode

    - by Globalhawk
    Hardware: MBP early 2011 version OS: Mountain lion App: Xcode 4.5.2 Problem: Every time when I start Xcode, 2 or 3 processes called "git" start running. But when I quit Xcode the "git" process won't quit and are still using a lot of CPU. Then the computer becomes quite hot and the battery gets drained very quickly. If I manually kill these processes the problem is gone. I tried to reinstall Xcode several times but the problem comes back every time. It drives me crazy. Any help will be appreciated!

    Read the article

  • What tool can I use to definitely kill a process on Windows?

    - by Moak
    Can anyone recommend an application (preferably usb-portable that doesn't require setup) That really kills a process immediately in windows XP? I ask this because often when I need to use the XP task manager it seems to want to go about it "the polite way" and sometimes crashed programs don't quit or take a minute to shut down. I need a real stone cold killer, not a pushover-could-you-please-quit-now-no?-ok-sorry-program Edit I'm sorry if it wasn't clear previously but I did mean the situation when even the "End process" command in Process tab of the task manager doesn't kill a program, however one of the answers did point me to the "End Process Tree" command which I've never noticed (when right clicking on the process)

    Read the article

  • A Service specific error occured:1 on trying to start apache 2.0 server.(Windows 7)

    - by user2297366
    I installed apache on my computer(localhost) and it worked fine. Then I went to download some other stuff and later noticed that the apache server stopped. So I went to command prompt(as administrator) and typed net start apache2. It says The Apache2 Service is starting. But before it finishes, I get the error A Service Specific Error Occurred: 1. It says that you can type in something for more info, but that doesn't help at all. Things I have tried: 1: Quit Google Drive Sync 2: Quit any and all programs using port 80(port my server is on) 3. I even tried changing the port of the server and got same error message, so I don't think it has anything to do with something else being in the port. None of those things have worked. I am confused at why it worked earlier, but now it won't work. Any help is greatly appreciated.

    Read the article

  • Undefined referencec to ...

    - by Patrick LaChance
    I keep getting this error message every time I try to compile, and I cannot find out what the problem is. any help would be greatly appreciated: C:\DOCUME~1\Patrick\LOCALS~1\Temp/ccL92mj9.o:main.cpp:(.txt+0x184): undefined reference to 'List::List()' C:\DOCUME~1\Patrick\LOCALS~1\Temp/ccL92mj9.o:main.cpp:(.txt+0x184): undefined reference to 'List::add(int)' collect2: ld returned 1 exit status code: //List.h ifndef LIST_H define LIST_H include //brief Definition of linked list class class List { public: /** \brief Exception for operating on empty list */ class Empty : public std::exception { public: virtual const char* what() const throw(); }; /** \brief Exception for invalid operations other than operating on an empty list */ class InvalidOperation : public std::exception { public: virtual const char* what() const throw(); }; /** \brief Node within List */ class Node { public: /** data element stored in this node */ int element; /** next node in list / Node next; /** previous node in list / Node previous; Node (int element); ~Node(); void print() const; void printDebug() const; }; List(); ~List(); void add(int element); void remove(int element); int first()const; int last()const; int removeFirst(); int removeLast(); bool isEmpty()const; int size()const; void printForward() const; void printReverse() const; void printDebug() const; /** enables extra output for debugging purposes */ static bool traceOn; private: /** head of list */ Node* head; /** tail of list */ Node* tail; /** count of number of nodes */ int count; }; endif //List.cpp I only included the parts of List.cpp that might be the issue include "List.h" include include using namespace std; List::List() { //List::size = NULL; head = NULL; tail = NULL; } List::~List() { Node* current; while(head != NULL) { current = head- next; delete current-previous; if (current-next!=NULL) { head = current; } else { delete current; } } } void List::add(int element) { Node* newNode; Node* current; newNode-element = element; if(newNode-element head-element) { current = head-next; } else { head-previous = newNode; newNode-next = head; newNode-previous = NULL; return; } while(newNode-element current-element) { current = current-next; } if(newNode-element <= current-element) { newNode-previous = current-previous; newNode-next = current; } } //main.cpp include "List.h" include include using namespace std; //void add(int element); int main (char** argv, int argc) { List* MyList = new List(); bool quit = false; string value; int element; while(quit==false) { cinvalue; if(value == "add") { cinelement; MyList-add(element); } if(value=="quit") { quit = true; } } return 0; } I'm doing everything I think I'm suppose to be doing. main.cpp isn't complete yet, just trying to get the add function to work first. Any help will be greatly appreciated.

    Read the article

  • FTP into a server using specific usernames

    - by user1854765
    I am trying to ftp into a server, once I'm there, I want to get a file, then put it back after sleeping for 5 minutes. I have that part correct, but i added to the code, two variables that will be inputted when the code is executed. The user will input the username they want to connect with. I am having trouble connecting though. When I input the username t14pb, it still goes to the the first if statement, as if I said t14pmds. here is the code: #!/usr/bin/perl use Net::FTP; $host = "fd00p02"; $username = "$ARGV[0]"; $ftpdir = "/"; $file = "$ARGV[1]"; print "$username\n"; print "$file\n"; if ($username == t14pmds) { $password = "test1"; $ftp = Net::FTP->new($host) or die "Error connecting to $host: $!"; $ftp->login($username, $password) or die "Login failed: $!"; $ftp->cwd($ftpdir) or die "Can't go to $ftpdir: $!"; $ftp->get($file) or die "Can't get $file: $!"; sleep 5; $ftp->put($file) or die "Can't put $file: $!"; $ftp->quit or die "Error closing ftp connection: $!"; } if ($username == t14pb) { $password = "test2"; $ftp = Net::FTP->new($host) or die "Error connecting to $host: $!"; $ftp->login($username, $password) or die "Login failed: $!"; $ftp->cwd($ftpdir) or die "Can't go to $ftpdir: $!"; $ftp->get($file) or die "Can't get $file: $!"; sleep 5; $ftp->put($file) or die "Can't put $file: $!"; $ftp->quit or die "Error closing ftp connection: $!"; } if ($username == t14pmds_out) { $password = "test3"; $ftp = Net::FTP->new($host) or die "Error connecting to $host: $!"; $ftp->login($username, $password) or die "Login failed: $!"; $ftp->cwd($ftpdir) or die "Can't go to $ftpdir: $!"; $ftp->get($file) or die "Can't get $file: $!"; sleep 5; $ftp->put($file) or die "Can't put $file: $!"; $ftp->quit or die "Error closing ftp connection: $!"; } if ($username == t14fiserv) { $password = "test4"; $ftp = Net::FTP->new($host) or die "Error connecting to $host: $!"; $ftp->login($username, $password) or die "Login failed: $!"; $ftp->cwd($ftpdir) or die "Can't go to $ftpdir: $!"; $ftp->get($file) or die "Can't get $file: $!"; sleep 5; $ftp->put($file) or die "Can't put $file: $!"; $ftp->quit or die "Error closing ftp connection: $!"; }

    Read the article

  • reading a random access file

    - by user1067332
    The file I create has text in it, but when i try to read it, the output is null. here is the file the creates the text file, it creates the file and puts it in the right postion import java.util.*; import java.io.*; public class CreateCustomerFile { public static void main(String[] args) throws IOException { int pos; RandomAccessFile it = new RandomAccessFile("CustomerFile.txt", "rw"); Scanner input = new Scanner(System.in); int id; String name; int zip; final int RECORDSIZE = 100; final int NUMRECORDS = 1000; final int STOP = 99; try { for(int x = 0; x < NUMRECORDS; ++x) { it.writeInt(0); it.writeUTF(""); it.writeInt(0); } } catch(IOException e) { System.out.println("Error: " + e.getMessage()); } finally { it.close(); } it = new RandomAccessFile("CustomerFile.txt","rw"); try { System.out.print("Enter ID number" + " or " + STOP + " to quit "); id = input.nextInt(); while(id != STOP) { input.nextLine(); System.out.print("Enter last name"); name = input.nextLine(); System.out.print("Enter zipcode "); zip = input.nextInt(); pos = id - 1; it.seek(pos * RECORDSIZE); it.writeInt(id); it.writeUTF(name); it.writeInt(zip); System.out.print("Enter ID number" + " or " + STOP + " to quit "); id = input.nextInt(); } } catch(IOException e) { System.out.println("Error: " + e.getMessage()); } finally { it.close(); } } } Here is the file to read, the pos is correct but ouput always goes to the error: null. import javax.swing.*; import java.io.*; public class CustomerItemOrder { public static void main(String[] args) throws IOException { int pos; RandomAccessFile it = new RandomAccessFile("CustomerFile.txt","rw"); String inputString; int id, zip; String name; final int RECORDSIZE = 100; final int STOP = 99; inputString = JOptionPane.showInputDialog(null, "Enter id or "+ STOP + " to quit"); id = Integer.parseInt(inputString); try { while(id != STOP) { pos = id -1 ; it.seek(pos * RECORDSIZE ); id = it.readInt(); name = it.readLine(); zip = it.readInt(); JOptionPane.showMessageDialog(null, "ID:" + id + " last name is " + name + " and zipcode is " + zip); inputString = JOptionPane.showInputDialog(null, "Enter id or " + STOP + " to quit"); id = Integer.parseInt(inputString); } } catch(IOException e) { System.out.println("Error: " + e.getMessage()); } finally { it.close(); } } }

    Read the article

  • pygame double buffering

    - by BaldDude
    I am trying to use double buffering in pygame. What I'm trying to do is display a red then green screen, and switch from one to the other. Unfortunately, all I have is a black screen. I looked through many sites, but have been unable to find a solution. Any help would be appreciated. import pygame, sys from pygame.locals import * RED = (255, 0, 0) GREEN = ( 0, 255, 0) bob = 1 pygame.init() #DISPLAYSURF = pygame.display.set_mode((500, 400), 0, 32) DISPLAYSURF = pygame.display.set_mode((1920, 1080), pygame.OPENGL | pygame.DOUBLEBUF | pygame.HWSURFACE | pygame.FULLSCREEN) glClear(GL_COLOR_BUFFER_BIT) glMatrixMode(GL_MODELVIEW) glLoadIdentity() running = True while running: if bob==1: #pygame.draw.rect(DISPLAYSURF, RED, (0, 0, 1920, 1080)) #pygame.display.flip() glBegin(GL_QUADS) glColor3f(1.0, 0.0, 0.0) glVertex2f(-1.0, 1.0) glVertex2f(-1.0, -1.0) glVertex2f(1.0, -1.0) glVertex2f(1.0, 1.0) glEnd() pygame.dis bob = 0 else: #pygame.draw.rect(DISPLAYSURF, GREEN, (0, 0, 1920, 1080)) #pygame.display.flip() glBegin(GL_QUADS) glColor3f(0.0, 1.0, 0.0) glVertex2f(-1.0, 1.0) glVertex2f(-1.0, -1.0) glVertex2f(1.0, -1.0) glVertex2f(1.0, 1.0) glEnd() pygame.dis bob = 1 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == KEYDOWN: if event.key == K_ESCAPE: running = False pygame.quit() sys.exit() I'm using Python 2.7 and my code need to be os independent. Thanks for your help.

    Read the article

  • Add collison detection to enemy sprites?

    - by xBroak
    i'd like to add the same collision detection used by the player sprite to the enemy sprites or 'creeps' ive added all the relevant code I can see yet collisons are still not being detected and handled, please find below the class, I have no idea what is wrong currently, the list of walls to collide with is 'wall_list' import pygame import pauseScreen as dm import re from pygame.sprite import Sprite from pygame import Rect, Color from random import randint, choice from vec2d import vec2d from simpleanimation import SimpleAnimation import displattxt black = (0,0,0) white = (255,255,255) blue = (0,0,255) green = (101,194,151) global currentEditTool currentEditTool = "Tree" global editMap editMap = False open('MapMaker.txt', 'w').close() def draw_background(screen, tile_img): screen.fill(black) img_rect = tile_img.get_rect() global rect rect = img_rect nrows = int(screen.get_height() / img_rect.height) + 1 ncols = int(screen.get_width() / img_rect.width) + 1 for y in range(nrows): for x in range(ncols): img_rect.topleft = (x * img_rect.width, y * img_rect.height) screen.blit(tile_img, img_rect) def changeTool(): if currentEditTool == "Tree": None elif currentEditTool == "Rock": None def pauseGame(): red = 255, 0, 0 green = 0,255, 0 blue = 0, 0,255 screen.fill(black) pygame.display.update() if editMap == False: choose = dm.dumbmenu(screen, [ 'Resume', 'Enable Map Editor', 'Quit Game'], 64,64,None,32,1.4,green,red) if choose == 0: print("hi") elif choose ==1: global editMap editMap = True elif choose ==2: print("bob") elif choose ==3: print("bob") elif choose ==4: print("bob") else: None else: choose = dm.dumbmenu(screen, [ 'Resume', 'Disable Map Editor', 'Quit Game'], 64,64,None,32,1.4,green,red) if choose == 0: print("Resume") elif choose ==1: print("Dis ME") global editMap editMap = False elif choose ==2: print("bob") elif choose ==3: print("bob") elif choose ==4: print("bob") else: None class Wall(pygame.sprite.Sprite): # Constructor function def __init__(self,x,y,width,height): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([width, height]) self.image.fill(green) self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x class insertTree(pygame.sprite.Sprite): def __init__(self,x,y,width,height, typ): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("images/map/tree.png").convert() self.image.set_colorkey(white) self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x class insertRock(pygame.sprite.Sprite): def __init__(self,x,y,width,height, typ): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("images/map/rock.png").convert() self.image.set_colorkey(white) self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x class Creep(pygame.sprite.Sprite): """ A creep sprite that bounces off walls and changes its direction from time to time. """ change_x=0 change_y=0 def __init__( self, screen, creep_image, explosion_images, field, init_position, init_direction, speed): """ Create a new Creep. screen: The screen on which the creep lives (must be a pygame Surface object, such as pygame.display) creep_image: Image (surface) object for the creep explosion_images: A list of image objects for the explosion animation. field: A Rect specifying the 'playing field' boundaries. The Creep will bounce off the 'walls' of this field. init_position: A vec2d or a pair specifying the initial position of the creep on the screen. init_direction: A vec2d or a pair specifying the initial direction of the creep. Must have an angle that is a multiple of 45 degres. speed: Creep speed, in pixels/millisecond (px/ms) """ Sprite.__init__(self) self.screen = screen self.speed = speed self.field = field self.rect = creep_image.get_rect() # base_image holds the original image, positioned to # angle 0. # image will be rotated. # self.base_image = creep_image self.image = self.base_image self.explosion_images = explosion_images # A vector specifying the creep's position on the screen # self.pos = vec2d(init_position) # The direction is a normalized vector # self.direction = vec2d(init_direction).normalized() self.state = Creep.ALIVE self.health = 15 def is_alive(self): return self.state in (Creep.ALIVE, Creep.EXPLODING) def changespeed(self,x,y): self.change_x+=x self.change_y+=y def update(self, time_passed, walls): """ Update the creep. time_passed: The time passed (in ms) since the previous update. """ if self.state == Creep.ALIVE: # Maybe it's time to change the direction ? # self._change_direction(time_passed) # Make the creep point in the correct direction. # Since our direction vector is in screen coordinates # (i.e. right bottom is 1, 1), and rotate() rotates # counter-clockwise, the angle must be inverted to # work correctly. # self.image = pygame.transform.rotate( self.base_image, -self.direction.angle) # Compute and apply the displacement to the position # vector. The displacement is a vector, having the angle # of self.direction (which is normalized to not affect # the magnitude of the displacement) # displacement = vec2d( self.direction.x * self.speed * time_passed, self.direction.y * self.speed * time_passed) self.pos += displacement # When the image is rotated, its size is changed. # We must take the size into account for detecting # collisions with the walls. # self.image_w, self.image_h = self.image.get_size() bounds_rect = self.field.inflate( -self.image_w, -self.image_h) if self.pos.x < bounds_rect.left: self.pos.x = bounds_rect.left self.direction.x *= -1 elif self.pos.x > bounds_rect.right: self.pos.x = bounds_rect.right self.direction.x *= -1 elif self.pos.y < bounds_rect.top: self.pos.y = bounds_rect.top self.direction.y *= -1 elif self.pos.y > bounds_rect.bottom: self.pos.y = bounds_rect.bottom self.direction.y *= -1 # collision detection old_x=bounds_rect.left new_x=old_x+self.direction.x bounds_rect.left = new_x # hit a wall? collide = pygame.sprite.spritecollide(self, walls, False) if collide: # yes bounds_rect.left=old_x old_y=self.pos.y new_y=old_y+self.direction.y self.pos.y = new_y collide = pygame.sprite.spritecollide(self, walls, False) if collide: # yes self.pos.y=old_y elif self.state == Creep.EXPLODING: if self.explode_animation.active: self.explode_animation.update(time_passed) else: self.state = Creep.DEAD self.kill() elif self.state == Creep.DEAD: pass #------------------ PRIVATE PARTS ------------------# # States the creep can be in. # # ALIVE: The creep is roaming around the screen # EXPLODING: # The creep is now exploding, just a moment before dying. # DEAD: The creep is dead and inactive # (ALIVE, EXPLODING, DEAD) = range(3) _counter = 0 def _change_direction(self, time_passed): """ Turn by 45 degrees in a random direction once per 0.4 to 0.5 seconds. """ self._counter += time_passed if self._counter > randint(400, 500): self.direction.rotate(45 * randint(-1, 1)) self._counter = 0 def _point_is_inside(self, point): """ Is the point (given as a vec2d) inside our creep's body? """ img_point = point - vec2d( int(self.pos.x - self.image_w / 2), int(self.pos.y - self.image_h / 2)) try: pix = self.image.get_at(img_point) return pix[3] > 0 except IndexError: return False def _decrease_health(self, n): """ Decrease my health by n (or to 0, if it's currently less than n) """ self.health = max(0, self.health - n) if self.health == 0: self._explode() def _explode(self): """ Starts the explosion animation that ends the Creep's life. """ self.state = Creep.EXPLODING pos = ( self.pos.x - self.explosion_images[0].get_width() / 2, self.pos.y - self.explosion_images[0].get_height() / 2) self.explode_animation = SimpleAnimation( self.screen, pos, self.explosion_images, 100, 300) global remainingCreeps remainingCreeps-=1 if remainingCreeps == 0: print("all dead") def draw(self): """ Blit the creep onto the screen that was provided in the constructor. """ if self.state == Creep.ALIVE: # The creep image is placed at self.pos. To allow for # smooth movement even when the creep rotates and the # image size changes, its placement is always # centered. # self.draw_rect = self.image.get_rect().move( self.pos.x - self.image_w / 2, self.pos.y - self.image_h / 2) self.screen.blit(self.image, self.draw_rect) # The health bar is 15x4 px. # health_bar_x = self.pos.x - 7 health_bar_y = self.pos.y - self.image_h / 2 - 6 self.screen.fill( Color('red'), (health_bar_x, health_bar_y, 15, 4)) self.screen.fill( Color('green'), ( health_bar_x, health_bar_y, self.health, 4)) elif self.state == Creep.EXPLODING: self.explode_animation.draw() elif self.state == Creep.DEAD: pass def mouse_click_event(self, pos): """ The mouse was clicked in pos. """ if self._point_is_inside(vec2d(pos)): self._decrease_health(3) #begin new player class Player(pygame.sprite.Sprite): change_x=0 change_y=0 frame = 0 def __init__(self,x,y): pygame.sprite.Sprite.__init__(self) # LOAD PLATER IMAGES # Set height, width self.images = [] for i in range(1,17): img = pygame.image.load("images/player/" + str(i)+".png").convert() #player images img.set_colorkey(white) self.images.append(img) self.image = self.images[0] self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x self.health = 15 self.image_w, self.image_h = self.image.get_size() health_bar_x = self.rect.x - 7 health_bar_y = self.rect.y - self.image_h / 2 - 6 screen.fill( Color('red'), (health_bar_x, health_bar_y, 15, 4)) screen.fill( Color('green'), ( health_bar_x, health_bar_y, self.health, 4)) def changespeed(self,x,y): self.change_x+=x self.change_y+=y def _decrease_health(self, n): """ Decrease my health by n (or to 0, if it's currently less than n) """ self.health = max(0, self.health - n) if self.health == 0: self._explode() def update(self,walls): # collision detection old_x=self.rect.x new_x=old_x+self.change_x self.rect.x = new_x # hit a wall? collide = pygame.sprite.spritecollide(self, walls, False) if collide: # yes self.rect.x=old_x old_y=self.rect.y new_y=old_y+self.change_y self.rect.y = new_y collide = pygame.sprite.spritecollide(self, walls, False) if collide: # yes self.rect.y=old_y # right to left if self.change_x < 0: self.frame += 1 if self.frame > 3*4: self.frame = 0 # Grab the image, divide by 4 # every 4 frames. self.image = self.images[self.frame//4] # Move left to right. # images 4...7 instead of 0...3. if self.change_x > 0: self.frame += 1 if self.frame > 3*4: self.frame = 0 self.image = self.images[self.frame//4+4] if self.change_y > 0: self.frame += 1 if self.frame > 3*4: self.frame = 0 self.image = self.images[self.frame//4+4+4] if self.change_y < 0: self.frame += 1 if self.frame > 3*4: self.frame = 0 self.image = self.images[self.frame//4+4+4+4] score = 0 # initialize pyGame pygame.init() # 800x600 sized screen global screen screen = pygame.display.set_mode([800, 600]) screen.fill(black) #bg_tile_img = pygame.image.load('images/map/grass.png').convert_alpha() #draw_background(screen, bg_tile_img) #pygame.display.flip() # Set title pygame.display.set_caption('Test') #background = pygame.Surface(screen.get_size()) #background = background.convert() #background.fill(black) # Create the player player = Player( 50,50 ) player.rect.x=50 player.rect.y=50 movingsprites = pygame.sprite.RenderPlain() movingsprites.add(player) # Make the walls. (x_pos, y_pos, width, height) global wall_list wall_list=pygame.sprite.RenderPlain() wall=Wall(0,0,10,600) # left wall wall_list.add(wall) wall=Wall(10,0,790,10) # top wall wall_list.add(wall) #wall=Wall(10,200,100,10) # poke wall wall_list.add(wall) wall=Wall(790,0,10,600) #(x,y,thickness, height) wall_list.add(wall) wall=Wall(10,590,790,10) #(x,y,thickness, height) wall_list.add(wall) f = open('MapMaker.txt') num_lines = sum(1 for line in f) print(num_lines) lineCount = 0 with open("MapMaker.txt") as infile: for line in infile: f = open('MapMaker.txt') print(line) coords = line.split(',') #print(coords[0]) #print(coords[1]) #print(coords[2]) #print(coords[3]) #print(coords[4]) if "tree" in line: print("tree in") wall=insertTree(int(coords[0]),int(coords[1]), int(coords[2]),int(coords[3]),coords[4]) wall_list.add(wall) elif "rock" in line: print("rock in") wall=insertRock(int(coords[0]),int(coords[1]), int(coords[2]),int(coords[3]),coords[4] ) wall_list.add(wall) width = 20 height = 540 height = height - 48 for i in range(0,23): width = width + 32 name = insertTree(width,540,790,10,"tree") #wall_list.add(name) name = insertTree(width,height,690,10,"tree") #wall_list.add(name) CREEP_SPAWN_TIME = 200 # frames creep_spawn = CREEP_SPAWN_TIME clock = pygame.time.Clock() bg_tile_img = pygame.image.load('images/map/grass.png').convert() img_rect = bg_tile_img FIELD_RECT = Rect(50, 50, 700, 500) CREEP_FILENAMES = [ 'images/player/1.png', 'images/player/1.png', 'images/player/1.png'] N_CREEPS = 3 creep_images = [ pygame.image.load(filename).convert_alpha() for filename in CREEP_FILENAMES] explosion_img = pygame.image.load('images/map/tree.png').convert_alpha() explosion_images = [ explosion_img, pygame.transform.rotate(explosion_img, 90)] creeps = pygame.sprite.RenderPlain() done = False #bg_tile_img = pygame.image.load('images/map/grass.png').convert() #draw_background(screen, bg_tile_img) totalCreeps = 0 remainingCreeps = 3 while done == False: creep_images = pygame.image.load("images/player/1.png").convert() creep_images.set_colorkey(white) draw_background(screen, bg_tile_img) if len(creeps) != N_CREEPS: if totalCreeps < N_CREEPS: totalCreeps = totalCreeps + 1 print(totalCreeps) creeps.add( Creep( screen=screen, creep_image=creep_images, explosion_images=explosion_images, field=FIELD_RECT, init_position=( randint(FIELD_RECT.left, FIELD_RECT.right), randint(FIELD_RECT.top, FIELD_RECT.bottom)), init_direction=(choice([-1, 1]), choice([-1, 1])), speed=0.01)) for creep in creeps: creep.update(60,wall_list) creep.draw() for event in pygame.event.get(): if event.type == pygame.QUIT: done=True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: player.changespeed(-2,0) creep.changespeed(-2,0) if event.key == pygame.K_RIGHT: player.changespeed(2,0) creep.changespeed(2,0) if event.key == pygame.K_UP: player.changespeed(0,-2) creep.changespeed(0,-2) if event.key == pygame.K_DOWN: player.changespeed(0,2) creep.changespeed(0,2) if event.key == pygame.K_ESCAPE: pauseGame() if event.key == pygame.K_1: global currentEditTool currentEditTool = "Tree" changeTool() if event.key == pygame.K_2: global currentEditTool currentEditTool = "Rock" changeTool() if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: player.changespeed(2,0) creep.changespeed(2,0) if event.key == pygame.K_RIGHT: player.changespeed(-2,0) creep.changespeed(-2,0) if event.key == pygame.K_UP: player.changespeed(0,2) creep.changespeed(0,2) if event.key == pygame.K_DOWN: player.changespeed(0,-2) creep.changespeed(0,-2) if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]: for creep in creeps: creep.mouse_click_event(pygame.mouse.get_pos()) if editMap == True: x,y = pygame.mouse.get_pos() if currentEditTool == "Tree": name = insertTree(x-10,y-25, 10 , 10, "tree") wall_list.add(name) wall_list.draw(screen) f = open('MapMaker.txt', "a+") image = pygame.image.load("images/map/tree.png").convert() screen.blit(image, (30,10)) pygame.display.flip() f.write(str(x) + "," + str(y) + ",790,10, tree\n") #f.write("wall=insertTree(" + str(x) + "," + str(y) + ",790,10)\nwall_list.add(wall)\n") elif currentEditTool == "Rock": name = insertRock(x-10,y-25, 10 , 10,"rock") wall_list.add(name) wall_list.draw(screen) f = open('MapMaker.txt', "a+") f.write(str(x) + "," + str(y) + ",790,10,rock\n") #f.write("wall=insertRock(" + str(x) + "," + str(y) + ",790,10)\nwall_list.add(wall)\n") else: None #pygame.display.flip() player.update(wall_list) movingsprites.draw(screen) wall_list.draw(screen) pygame.display.flip() clock.tick(60) pygame.quit()

    Read the article

  • Nautilus crashes after Ubuntu Tweak Package Cleaner [fixed]

    - by Ka7anax
    Few days ago I started having some problems with nautilus. Basically when I'm trying to get into a folder it crashes. It's not happening all the time, but in 85% it does... Sometimes, after the crash all my desktop icons are also gone. The only thing that I think causes this is Ubuntu Tweak - I'm not sure, but the issues started after I did the Package cleaner from Ubuntu Tweaks... Any ideas? ------- EDIT 2 - IMPORTANT !!! ---------- It seems I fixed this problem doing these: 1) I uninstall this nautilus script - http://mundogeek.net/nautilus-scripts/#nautilus-send-gmail 2) I installed nautilus elementary So far is back to normal... If anything bad happens again I will come back! -------- EDIT 1 ---------- First time, after running the command (nautilus --quit; nautilus --no-desktop) 3 times all the system crashed (except the mouse, I could move the mouse). After restart I run it and obtain this: ----- Initializing nautilus-gdu extension Initializing nautilus-dropbox 0.6.7 (nautilus:2966): GConf-CRITICAL **: gconf_value_free: assertion value != NULL' failed (nautilus:2966): GConf-CRITICAL **: gconf_value_free: assertionvalue != NULL' failed Nautilus-Share-Message: Called "net usershare info" but it failed: 'net usershare' returned error 255: net usershare: cannot open usershare directory /var/lib/samba/usershares. Error No such file or directory Please ask your system administrator to enable user sharing. and then this: cristi@cris-laptop:~$ nautilus --quit; nautilus --no-desktop (nautilus:3810): Unique-DBus-WARNING **: Error while sending message: Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.

    Read the article

  • Nautilus crashes after Ubuntu Tweak Package Cleaner

    - by Ka7anax
    Few days ago I started having some problems with nautilus. Basically when I'm trying to get into a folder it crashes. It's not happening all the time, but in 85% it does... Sometimes, after the crash all my desktop icons are also gone. The only thing that I think causes this is Ubuntu Tweak - I'm not sure, but the issues started after I did the Package cleaner from Ubuntu Tweaks... Any ideas? -------- EDIT ---------- First time, after running the command (nautilus --quit; nautilus --no-desktop) 3 times all the system crashed (except the mouse, I could move the mouse). After restart I run it and obtain this: ----- Initializing nautilus-gdu extension Initializing nautilus-dropbox 0.6.7 (nautilus:2966): GConf-CRITICAL **: gconf_value_free: assertion value != NULL' failed (nautilus:2966): GConf-CRITICAL **: gconf_value_free: assertionvalue != NULL' failed Nautilus-Share-Message: Called "net usershare info" but it failed: 'net usershare' returned error 255: net usershare: cannot open usershare directory /var/lib/samba/usershares. Error No such file or directory Please ask your system administrator to enable user sharing. and then this: cristi@cris-laptop:~$ nautilus --quit; nautilus --no-desktop (nautilus:3810): Unique-DBus-WARNING **: Error while sending message: Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.

    Read the article

  • Software Center empty "No usefulness from server" "no username in config file"

    - by Theron G. Burrough
    I upgraded to 12.04 LTS and ran Software Center while a few things were running, and crashed. (2 GB RAM on a Netbook.) On reboot, Ubuntu One interface would not find any programs, neither installed (to run) nor available for download. So I launched Software Center, which opens, but does nothing. I click "Close" button and get a "Force Quit?" box. So I quit. Did research, learned to run Software Center from Terminal: 2012-04-29 23:14:36,978 - softwarecenter.backend.reviews - WARNING - Could not get usefulness from server, no username in config file Then tried the below without success: Reinstallation of software center: sudo apt-get install --reinstall software-center Didn't work. Found this in a post: remove the config file for software-center then log out and back in sudo rm -rf ~/.config/software-center Didn't work. Reinstalled Software Center with Synaptic Package Manager. Still no dice! And I am a Linux newbie, so I don't know where the Dickens that config file is. Help appreciated.

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >