Search Results

Search found 1255 results on 51 pages for 'todo'.

Page 9/51 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • How to label a cuboid?

    - by usha
    Hi this is how my 3dcuboid looks, I have attached the complete code. I want to label this cuboid using different names across sides, how is this possible using opengl on android? public class MyGLRenderer implements Renderer { Context context; Cuboid rect; private float mCubeRotation; // private static float angleCube = 0; // Rotational angle in degree for cube (NEW) // private static float speedCube = -1.5f; // Rotational speed for cube (NEW) public MyGLRenderer(Context context) { rect = new Cuboid(); this.context = context; } public void onDrawFrame(GL10 gl) { // TODO Auto-generated method stub gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); gl.glLoadIdentity(); // Reset the model-view matrix gl.glTranslatef(0.2f, 0.0f, -8.0f); // Translate right and into the screen gl.glScalef(0.8f, 0.8f, 0.8f); // Scale down (NEW) gl.glRotatef(mCubeRotation, 1.0f, 1.0f, 1.0f); // gl.glRotatef(angleCube, 1.0f, 1.0f, 1.0f); // rotate about the axis (1,1,1) (NEW) rect.draw(gl); mCubeRotation -= 0.15f; //angleCube += speedCube; } public void onSurfaceChanged(GL10 gl, int width, int height) { // TODO Auto-generated method stub if (height == 0) height = 1; // To prevent divide by zero float aspect = (float)width / height; // Set the viewport (display area) to cover the entire window gl.glViewport(0, 0, width, height); // Setup perspective projection, with aspect ratio matches viewport gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix gl.glLoadIdentity(); // Reset projection matrix // Use perspective projection GLU.gluPerspective(gl, 45, aspect, 0.1f, 100.f); gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix gl.glLoadIdentity(); // Reset } public void onSurfaceCreated(GL10 gl, EGLConfig config) { // TODO Auto-generated method stub gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set color's clear-value to black gl.glClearDepthf(1.0f); // Set depth's clear-value to farthest gl.glEnable(GL10.GL_DEPTH_TEST); // Enables depth-buffer for hidden surface removal gl.glDepthFunc(GL10.GL_LEQUAL); // The type of depth testing to do gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST); // nice perspective view gl.glShadeModel(GL10.GL_SMOOTH); // Enable smooth shading of color gl.glDisable(GL10.GL_DITHER); // Disable dithering for better performance }} public class Cuboid{ private FloatBuffer mVertexBuffer; private FloatBuffer mColorBuffer; private ByteBuffer mIndexBuffer; private float vertices[] = { //width,height,depth -2.5f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -2.5f, 1.0f, -1.0f, -2.5f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -2.5f, 1.0f, 1.0f }; private float colors[] = { // R,G,B,A COLOR 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.0f, 1.0f, 1.0f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f }; private byte indices[] = { // VERTEX 0,1,2,3,4,5,6,7 REPRESENTATION FOR FACES 0, 4, 5, 0, 5, 1, 1, 5, 6, 1, 6, 2, 2, 6, 7, 2, 7, 3, 3, 7, 4, 3, 4, 0, 4, 7, 6, 4, 6, 5, 3, 0, 1, 3, 1, 2 }; public Cuboid() { ByteBuffer byteBuf = ByteBuffer.allocateDirect(vertices.length * 4); byteBuf.order(ByteOrder.nativeOrder()); mVertexBuffer = byteBuf.asFloatBuffer(); mVertexBuffer.put(vertices); mVertexBuffer.position(0); byteBuf = ByteBuffer.allocateDirect(colors.length * 4); byteBuf.order(ByteOrder.nativeOrder()); mColorBuffer = byteBuf.asFloatBuffer(); mColorBuffer.put(colors); mColorBuffer.position(0); mIndexBuffer = ByteBuffer.allocateDirect(indices.length); mIndexBuffer.put(indices); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CW); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer); gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColorBuffer); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glDrawElements(GL10.GL_TRIANGLES, 36, GL10.GL_UNSIGNED_BYTE, mIndexBuffer); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } } public class Draw3drect extends Activity { private GLSurfaceView glView; // Use GLSurfaceView // Call back when the activity is started, to initialize the view @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); glView = new GLSurfaceView(this); // Allocate a GLSurfaceView glView.setRenderer(new MyGLRenderer(this)); // Use a custom renderer this.setContentView(glView); // This activity sets to GLSurfaceView } // Call back when the activity is going into the background @Override protected void onPause() { super.onPause(); glView.onPause(); } // Call back after onPause() @Override protected void onResume() { super.onResume(); glView.onResume(); } }

    Read the article

  • Threads are facing deadlock in socket program [migrated]

    - by ankur.trapasiya
    I am developing one program in which a user can download a number of files. Now first I am sending the list of files to the user. So from the list user selects one file at a time and provides path where to store that file. In turn it also gives the server the path of file where does it exist. I am following this approach because I want to give stream like experience without file size limitation. Here is my code.. 1) This is server which gets started each time I start my application public class FileServer extends Thread { private ServerSocket socket = null; public FileServer() { try { socket = new ServerSocket(Utils.tcp_port); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void run() { try { System.out.println("request received"); new FileThread(socket.accept()).start(); } catch (IOException ex) { ex.printStackTrace(); } } } 2) This thread runs for each client separately and sends the requested file to the user 8kb data at a time. public class FileThread extends Thread { private Socket socket; private String filePath; public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public FileThread(Socket socket) { this.socket = socket; System.out.println("server thread" + this.socket.isConnected()); //this.filePath = filePath; } @Override public void run() { // TODO Auto-generated method stub try { ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); try { //************NOTE filePath=(String) ois.readObject(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } File f = new File(this.filePath); byte[] buf = new byte[8192]; InputStream is = new FileInputStream(f); BufferedInputStream bis = new BufferedInputStream(is); ObjectOutputStream oos = new ObjectOutputStream( socket.getOutputStream()); int c = 0; while ((c = bis.read(buf, 0, buf.length)) > 0) { oos.write(buf, 0, c); oos.flush(); // buf=new byte[8192]; } oos.close(); //socket.shutdownOutput(); // client.shutdownOutput(); System.out.println("stop"); // client.shutdownOutput(); ois.close(); // Thread.sleep(500); is.close(); bis.close(); socket.close(); } catch (IOException ex) { ex.printStackTrace(); } } } NOTE: here filePath represents the path of the file where it exists on the server. The client who is connecting to the server provides this path. I am managing this through sockets and I am successfully receiving this path. 3) FileReceiverThread is responsible for receiving the data from the server and constructing file from this buffer data. public class FileReceiveThread extends Thread { private String fileStorePath; private String sourceFile; private Socket socket = null; public FileReceiveThread(String ip, int port, String fileStorePath, String sourceFile) { this.fileStorePath = fileStorePath; this.sourceFile = sourceFile; try { socket = new Socket(ip, port); System.out.println("receive file thread " + socket.isConnected()); } catch (IOException ex) { ex.printStackTrace(); } } @Override public void run() { try { ObjectOutputStream oos = new ObjectOutputStream( socket.getOutputStream()); oos.writeObject(sourceFile); oos.flush(); // oos.close(); File f = new File(fileStorePath); OutputStream os = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(os); byte[] buf = new byte[8192]; int c = 0; //************ NOTE ObjectInputStream ois = new ObjectInputStream( socket.getInputStream()); while ((c = ois.read(buf, 0, buf.length)) > 0) { // ois.read(buf); bos.write(buf, 0, c); bos.flush(); // buf = new byte[8192]; } ois.close(); oos.close(); // os.close(); bos.close(); socket.close(); //Thread.sleep(500); } catch (IOException ex) { ex.printStackTrace(); } } } NOTE : Now the problem that I am facing is at the first time when the file is requested the outcome of the program is same as my expectation. I am able to transmit any size of file at first time. Now when the second file is requested (e.g. I have sent file a,b,c,d to the user and user has received file a successfully and now he is requesting file b) the program faces deadlock at this situation. It is waiting for socket's input stream. I put breakpoint and tried to debug it but it is not going in FileThread's run method second time. I could not find out the mistake here. Basically I am making a LAN Messenger which works on LAN. I am using SWT as UI framework.

    Read the article

  • how to label a cuboid using open gl?

    - by usha
    hi this is how my 3dcuboid looks ,i have attached complete code , i want to label this cuboid using different name across sides how is it possible using opengl in android...plz help me out public class MyGLRenderer implements Renderer { Context context; Cuboid rect; private float mCubeRotation; // private static float angleCube = 0; // Rotational angle in degree for cube (NEW) // private static float speedCube = -1.5f; // Rotational speed for cube (NEW) public MyGLRenderer(Context context) { rect = new Cuboid(); this.context = context; } public void onDrawFrame(GL10 gl) { // TODO Auto-generated method stub gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); gl.glLoadIdentity(); // Reset the model-view matrix gl.glTranslatef(0.2f, 0.0f, -8.0f); // Translate right and into the screen gl.glScalef(0.8f, 0.8f, 0.8f); // Scale down (NEW) gl.glRotatef(mCubeRotation, 1.0f, 1.0f, 1.0f); // gl.glRotatef(angleCube, 1.0f, 1.0f, 1.0f); // rotate about the axis (1,1,1) (NEW) rect.draw(gl); mCubeRotation -= 0.15f; //angleCube += speedCube; } public void onSurfaceChanged(GL10 gl, int width, int height) { // TODO Auto-generated method stub if (height == 0) height = 1; // To prevent divide by zero float aspect = (float)width / height; // Set the viewport (display area) to cover the entire window gl.glViewport(0, 0, width, height); // Setup perspective projection, with aspect ratio matches viewport gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix gl.glLoadIdentity(); // Reset projection matrix // Use perspective projection GLU.gluPerspective(gl, 45, aspect, 0.1f, 100.f); gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix gl.glLoadIdentity(); // Reset } public void onSurfaceCreated(GL10 gl, EGLConfig config) { // TODO Auto-generated method stub gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set color's clear-value to black gl.glClearDepthf(1.0f); // Set depth's clear-value to farthest gl.glEnable(GL10.GL_DEPTH_TEST); // Enables depth-buffer for hidden surface removal gl.glDepthFunc(GL10.GL_LEQUAL); // The type of depth testing to do gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST); // nice perspective view gl.glShadeModel(GL10.GL_SMOOTH); // Enable smooth shading of color gl.glDisable(GL10.GL_DITHER); // Disable dithering for better performance }} public class Cuboid{ private FloatBuffer mVertexBuffer; private FloatBuffer mColorBuffer; private ByteBuffer mIndexBuffer; private float vertices[] = { //width,height,depth -2.5f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -2.5f, 1.0f, -1.0f, -2.5f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -2.5f, 1.0f, 1.0f }; private float colors[] = { // R,G,B,A COLOR 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.0f, 1.0f, 1.0f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f }; private byte indices[] = { // VERTEX 0,1,2,3,4,5,6,7 REPRESENTATION FOR FACES 0, 4, 5, 0, 5, 1, 1, 5, 6, 1, 6, 2, 2, 6, 7, 2, 7, 3, 3, 7, 4, 3, 4, 0, 4, 7, 6, 4, 6, 5, 3, 0, 1, 3, 1, 2 }; public Cuboid() { ByteBuffer byteBuf = ByteBuffer.allocateDirect(vertices.length * 4); byteBuf.order(ByteOrder.nativeOrder()); mVertexBuffer = byteBuf.asFloatBuffer(); mVertexBuffer.put(vertices); mVertexBuffer.position(0); byteBuf = ByteBuffer.allocateDirect(colors.length * 4); byteBuf.order(ByteOrder.nativeOrder()); mColorBuffer = byteBuf.asFloatBuffer(); mColorBuffer.put(colors); mColorBuffer.position(0); mIndexBuffer = ByteBuffer.allocateDirect(indices.length); mIndexBuffer.put(indices); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CW); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer); gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColorBuffer); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glDrawElements(GL10.GL_TRIANGLES, 36, GL10.GL_UNSIGNED_BYTE, mIndexBuffer); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } } public class Draw3drect extends Activity { private GLSurfaceView glView; // Use GLSurfaceView // Call back when the activity is started, to initialize the view @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); glView = new GLSurfaceView(this); // Allocate a GLSurfaceView glView.setRenderer(new MyGLRenderer(this)); // Use a custom renderer this.setContentView(glView); // This activity sets to GLSurfaceView } // Call back when the activity is going into the background @Override protected void onPause() { super.onPause(); glView.onPause(); } // Call back after onPause() @Override protected void onResume() { super.onResume(); glView.onResume(); } }

    Read the article

  • Implementing Linked Lists in C#

    - by nijhawan.saurabh
    Why? The question is why you need Linked Lists and why it is the foundation of any Abstract Data Structure. Take any of the Data Structures - Stacks, Queues, Heaps, Trees; there are two ways to go about implementing them - Using Arrays Using Linked Lists Now you use Arrays when you know about the size of the Nodes in the list at Compile time and Linked Lists are helpful where you are free to add as many Nodes to the List as required at Runtime.   How? Now, let's see how we go about implementing a Simple Linked List in C#. Note: We'd be dealing with singly linked list for time being, there's also another version of linked lists - the Doubly Linked List which maintains two pointers (NEXT and BEFORE).   Class Diagram Let's see the Class Diagram first:     Code     1 // -----------------------------------------------------------------------     2 // <copyright file="Node.cs" company="">     3 // TODO: Update copyright text.     4 // </copyright>     5 // -----------------------------------------------------------------------     6      7 namespace CSharpAlgorithmsAndDS     8 {     9     using System;    10     using System.Collections.Generic;    11     using System.Linq;    12     using System.Text;    13     14     /// <summary>    15     /// TODO: Update summary.    16     /// </summary>    17     public class Node    18     {    19         public Object data { get; set; }    20     21         public Node Next { get; set; }    22     }    23 }    24         1 // -----------------------------------------------------------------------     2 // <copyright file="LinkedList.cs" company="">     3 // TODO: Update copyright text.     4 // </copyright>     5 // -----------------------------------------------------------------------     6      7 namespace CSharpAlgorithmsAndDS     8 {     9     using System;    10     using System.Collections.Generic;    11     using System.Linq;    12     using System.Text;    13     14     /// <summary>    15     /// TODO: Update summary.    16     /// </summary>    17     public class LinkedList    18     {    19         private Node Head;    20     21         public void AddNode(Node n)    22         {    23             n.Next = this.Head;    24             this.Head = n;    25     26         }    27     28         public void printNodes()    29         {    30     31             while (Head!=null)    32             {    33                 Console.WriteLine(Head.data);    34                 Head = Head.Next;    35     36             }    37     38         }    39     }    40 }    41          1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5      6 namespace CSharpAlgorithmsAndDS     7 {     8     class Program     9     {    10         static void Main(string[] args)    11         {    12             LinkedList ll = new LinkedList();    13             Node A = new Node();    14             A.data = "A";    15     16             Node B = new Node();    17             B.data = "B";    18     19             Node C = new Node();    20             C.data = "C";    21             ll.AddNode(A);    22             ll.AddNode(B);    23             ll.AddNode(C);    24     25             ll.printNodes();    26         }    27     }    28 }    29        Final Words This is just a start, I will add more posts on Linked List covering more operations like Delete etc. and will also explore Doubly Linked List / Implementing Stacks/ Heaps/ Trees / Queues and what not using Linked Lists.   Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0in; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;}

    Read the article

  • Seekbar: two instances of OnSeekBarChangeListener issues

    - by fordays
    Hi, I'm using two SeekBar widgets and I am encountering some trouble having them coexist at the same time. Can anyone suggest how to modify my code to work on the same Activity? SeekBar ageSeek = (SeekBar)findViewById(R.id.ageSeek); ageSeek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if(fromUser) { age = progress; EditAge.setText(Integer.toString(age)); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); SeekBar serumSeek = (SeekBar)findViewById(R.id.serumSeek); serumSeek.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){ @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if(fromUser) { serum = progress; EditSerum.setText(Double.toString(serum)); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); }

    Read the article

  • Use bug tracker to get things done and manage personal tasks?

    - by Frank
    This is slightly off-topic, but can only be answered by programmers and is useful to many programmers: Do you think it is useful to use a bug tracking system to keep track of personal todo items and to Get Things Done? I have not tried that; in fact, I don't have much experience with bug tracking systems. For my todo lists, I have played around with Google Tasks and Remember The Milk, but both of them have shortcomings: Google Tasks: I like that you can create todo lists easily, can reorder items in the list and easily create hierarchies. But it is way too simplistic and does not allow to tag tasks or move tasks from one list to another. Remember The Milk: It is nice and sleek, but you cannot create hierarchies of tasks, cannot arbitrarily reorder tasks and cannot set dependencies of tasks. That's where a bug tracking system should come in: Since I think (maybe too much?) like a programmer, my tasks have a natural hierarchy and a tree of dependencies, like in a Makefile. Here are two examples: The task of writing my thesis is done when several milestones are done. Some of these milestones can run in parallel (writing background chapter, running experiments A, running experiments B), others depend on each other (writing main chapter depends on first getting results from experiments A). The same is true for more personal goals: I want to host a dinner party, which requires finding a good date, finishing the guest list, making invitations, finding nice recipes, cooking, ... For me, all these tasks involve hierarchical dependencies and milestones that bug tracking systems should be able to handle? Here is an article that explains how to do advanced GTD with Remember The Milk, but he has to use several workarounds: (1) add a general tag 'wait' to tasks that are waiting for others to be completed but you cannot enter the IDs of the tasks that they are waiting for, (2) starting some special tasks with "." so that they are at the top of the alphabetically sorted list and signal that others are 'below' it as subgoals. Bug tracking systems should be able to handle these things much more naturally? Does anyone have experience and can recommend a lightweight bug tracking system that might be good for this? Other requirements: Should run as web app, should allow me to tag a task with several tags (like 'work', 'fun', 'short-task', 'errands', ...).

    Read the article

  • AES code throwing NoSuchPaddingException: Padding NoPaddin unknown

    - by Tom Brito
    The following code is a try to encrypt data using AES with asymmetric key: import java.io.OutputStream; import java.math.BigInteger; import java.security.Key; import java.security.KeyFactory; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.RSAPrivateKeySpec; import java.security.spec.RSAPublicKeySpec; import javax.crypto.Cipher; public class AsyncronousKeyTest { private final Cipher cipher; private final KeyFactory keyFactory; private final RSAPrivateKey privKey; private AsyncronousKeyTest() throws Exception { cipher = Cipher.getInstance("AES/CBC/NoPaddin", "BC"); keyFactory = KeyFactory.getInstance("AES", "BC"); // create the keys // TODO should this numbers be random? RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(new BigInteger( "d46f473a2d746537de2056ae3092c451", 16), new BigInteger("57791d5430d593164082036ad8b29fb1", 16)); privKey = (RSAPrivateKey) keyFactory.generatePrivate(privKeySpec); } public void generateAuthorizationAct(OutputStream outputStream) throws Exception { // TODO Ticket #14 - GenerateAuthorization action KeyFactory keyFactory = KeyFactory.getInstance("AES", "BC"); // TODO should this numbers be random? RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger("d46f473a2d746537de2056ae3092c451", 16), new BigInteger("11", 16)); RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec); byte[] data = new byte[] {0x01}; byte[] encrypted = encryptAO(pubKey, data); outputStream.write(encrypted); } /** Encrypt the AuthorizationObject. */ public byte[] encryptAO(Key pubKey, byte[] data) throws Exception { cipher.init(Cipher.ENCRYPT_MODE, pubKey); byte[] cipherText = cipher.doFinal(data); return cipherText; } public byte[] decrypt(byte[] cipherText) throws Exception { cipher.init(Cipher.DECRYPT_MODE, privKey); byte[] decyptedData = cipher.doFinal(cipherText); return decyptedData; } public static void main(String[] args) throws Exception { System.out.println("start"); AsyncronousKeyTest auth = new AsyncronousKeyTest(); auth.generateAuthorizationAct(System.out); System.out.println("done"); } } but at line cipher = Cipher.getInstance(AesEncrypter.getTransformation(), "BC"); it throws NoSuchPaddingException: Padding NoPaddin unknown. What is this? And how to solve?

    Read the article

  • Eclipse code template to insert a bookmark?

    - by Mike
    Eclipse has a nifty feature which allows you to define "templates" for code. I have created one to automatically put in a println and add a "TODO" comment. I'd like for this to also add a bookmark so I can easily find it again. (The codebase I am working with makes it unfeasible to use just the Task List to find what I need to do since there are a lot of TODOs laying around.) My current template is simply System.out.println("don't commit me!"); //TODO: fix this ${cursor}.

    Read the article

  • java NullPointerException when parsing XML

    - by behrk2
    Hi Everyone, I keep receiving a java.lang.NullPointerException while trying to parse out the values of ths tags in the following XML sample: <?xml version="1.0" standalone="yes"?> <autocomplete> <autocomplete_item> <title short="Forrest Gump"></title> </autocomplete_item> <autocomplete_item> <title short="Forrest Landis"></title> </autocomplete_item> <autocomplete_item> <title short="Finding Forrester"></title> </autocomplete_item> <autocomplete_item> <title short="Menotti: The Medium: Maureen Forrester"></title> </autocomplete_item> </autocomplete> Here is my parsing code, can anyone see where I am going wrong? Thanks! public String parse(String element) { Document doc = null; String result = null; DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = null; try { docBuilder = docBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } docBuilder.isValidating(); try { doc = docBuilder.parse(input); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } doc.getDocumentElement().normalize(); NodeList list = doc.getElementsByTagName(element); _node = new String(); _element = new String(); for (int i = 0; i < list.getLength(); i++) { Node value = list.item(i).getChildNodes().item(0); _node = list.item(i).getNodeName(); _element = value.getNodeValue(); result = _element; SearchResults searchResults = new SearchResults(); searchResults.setTitles(result); Vector test = searchResults.getTitles(); for (int p = 0; p < test.size(); p++) { System.out.println("STUFF: " + test.elementAt(p)); } }// end for return result; }

    Read the article

  • Managing of shared resources between classes?

    - by Axarydax
    Imagine that I have a several Viewer component that are used for displaying text and they have few modes that user can switch (different font presets for viewing text/binary/hex). What would be the best approach for managing shared objects - for example fonts, find dialog, etc? I figured that static class with lazily initialized objects would be OK, but this might be the wrong idea. static class ViewerStatic { private static Font monospaceFont; public static Font MonospaceFont { get { if (monospaceFont == null) //TODO read font settings from configuration monospaceFont = new Font(FontFamily.GenericMonospace, 9, FontStyle.Bold); return monospaceFont; } } private static Font sansFont; public static Font SansFont { get { if (sansFont == null) //TODO read font settings from configuration sansFont = new Font(FontFamily.GenericSansSerif, 9, FontStyle.Bold); return sansFont; } } }

    Read the article

  • How do encrypt a long or int using the Bouncy Castle crypto routines for BlackBerry?

    - by DanG
    How do encrypt/decrypt a long or int using the Bouncy Castle crypto routines for BlackBerry? I know how to encrypt/decrypt a String. I can encrypt a long but can't get a long to decrypt properly. Some of this is poorly done, but I'm just trying stuff out at the moment. I've included my entire crypto engine here: import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.engines.AESFastEngine; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; public class CryptoEngine { // Global Variables // Global Objects private static AESFastEngine engine; private static BufferedBlockCipher cipher; private static KeyParameter key; public static boolean setEncryptionKey(String keyText) { // adding in spaces to force a proper key keyText += " "; // cutting off at 128 bits (16 characters) keyText = keyText.substring(0, 16); keyText = HelperMethods.cleanUpNullString(keyText); byte[] keyBytes = keyText.getBytes(); key = new KeyParameter(keyBytes); engine = new AESFastEngine(); cipher = new PaddedBufferedBlockCipher(engine); // just for now return true; } public static String encryptString(String plainText) { try { byte[] plainArray = plainText.getBytes(); cipher.init(true, key); byte[] cipherBytes = new byte[cipher.getOutputSize(plainArray.length)]; int cipherLength = cipher.processBytes(plainArray, 0, plainArray.length, cipherBytes, 0); cipher.doFinal(cipherBytes, cipherLength); String cipherString = new String(cipherBytes); return cipherString; } catch (DataLengthException e) { Logger.logToConsole(e); } catch (IllegalArgumentException e) { Logger.logToConsole(e); } catch (IllegalStateException e) { Logger.logToConsole(e); } catch (InvalidCipherTextException e) { Logger.logToConsole(e); } catch (Exception ex) { Logger.logToConsole(ex); } // else return "";// default bad value } public static String decryptString(String encryptedText) { try { byte[] cipherBytes = encryptedText.getBytes(); cipher.init(false, key); byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)]; int decryptedLength = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0); cipher.doFinal(decryptedBytes, decryptedLength); String decryptedString = new String(decryptedBytes); // crop accordingly int index = decryptedString.indexOf("\u0000"); if (index >= 0) { decryptedString = decryptedString.substring(0, index); } return decryptedString; } catch (DataLengthException e) { Logger.logToConsole(e); } catch (IllegalArgumentException e) { Logger.logToConsole(e); } catch (IllegalStateException e) { Logger.logToConsole(e); } catch (InvalidCipherTextException e) { Logger.logToConsole(e); } catch (Exception ex) { Logger.logToConsole(ex); } // else return "";// default bad value } private static byte[] convertLongToByteArray(long longToConvert) { return new byte[] { (byte) (longToConvert >>> 56), (byte) (longToConvert >>> 48), (byte) (longToConvert >>> 40), (byte) (longToConvert >>> 32), (byte) (longToConvert >>> 24), (byte) (longToConvert >>> 16), (byte) (longToConvert >>> 8), (byte) (longToConvert) }; } private static long convertByteArrayToLong(byte[] byteArrayToConvert) { long returnable = 0; for (int counter = 0; counter < byteArrayToConvert.length; counter++) { returnable += ((byteArrayToConvert[byteArrayToConvert.length - counter - 1] & 0xFF) << counter * 8); } if (returnable < 0) { returnable++; } return returnable; } public static long encryptLong(long plainLong) { try { String plainString = String.valueOf(plainLong); String cipherString = encryptString(plainString); byte[] cipherBytes = cipherString.getBytes(); long returnable = convertByteArrayToLong(cipherBytes); return returnable; } catch (Exception e) { Logger.logToConsole(e); } // else return Integer.MIN_VALUE;// default bad value } public static long decryptLong(long encryptedLong) { byte[] cipherBytes = convertLongToByteArray(encryptedLong); cipher.init(false, key); byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)]; int decryptedLength = cipherBytes.length; try { cipher.doFinal(decryptedBytes, decryptedLength); } catch (DataLengthException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidCipherTextException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } long plainLong = convertByteArrayToLong(decryptedBytes); return plainLong; } public static boolean encryptBoolean(int plainBoolean) { return false; } public static boolean decryptBoolean(int encryptedBoolean) { return false; } public static boolean testLongToByteArrayConversion() { boolean returnable = true; // fails out of the bounds of an integer, the conversion to long from byte // array does not hold, need to figure out a better solution for (long counter = -1000000; counter < 1000000; counter++) { long test = counter; byte[] bytes = convertLongToByteArray(test); long result = convertByteArrayToLong(bytes); if (result != test) { returnable = false; Logger.logToConsole("long conversion failed"); Logger.logToConsole("test = " + test + "\n result = " + result); } // regardless } // the end Logger.logToConsole("final returnable result = " + returnable); return returnable; } }

    Read the article

  • Why cant i draw an elipse in with code?

    - by bvivek88
    package test; import java.awt.*; import java.awt.event.*; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import javax.swing.*; public class test_bmp extends JPanel implements MouseListener,MouseMotionListener,ActionListener { static BufferedImage image; Color color; Point start=new Point(); Point end =new Point(); JButton elipse=new JButton("Elipse"); JButton rectangle=new JButton("Rectangle"); JButton line=new JButton("Line"); String selected; public test_bmp() { color = Color.black; setBorder(BorderFactory.createLineBorder(Color.black)); addMouseListener(this); addMouseMotionListener(this); } public void paintComponent(Graphics g) { //super.paintComponent(g); g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; g2.setPaint(Color.black); if(selected=="elipse") { g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); System.out.println("Start : "+start.x+","+start.y); System.out.println("End : "+end.x+","+end.y); } if(selected=="line") g2.drawLine(start.x,start.y,end.x,end.y); } //Draw on Buffered image public void draw() { Graphics2D g2 = image.createGraphics(); g2.setPaint(color); System.out.println("draw"); if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); if(selected=="elipse") { g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); System.out.println("Start : "+start.x+","+start.y); System.out.println("End : "+end.x+","+end.y); } repaint(); g2.dispose(); } public JPanel addButtons() { JPanel buttonpanel=new JPanel(); buttonpanel.setBackground(color.lightGray); buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS)); elipse.addActionListener(this); rectangle.addActionListener(this); line.addActionListener(this); buttonpanel.add(elipse); buttonpanel.add(Box.createRigidArea(new Dimension(15,15))); buttonpanel.add(rectangle); buttonpanel.add(Box.createRigidArea(new Dimension(15,15))); buttonpanel.add(line); return buttonpanel; } public static void main(String args[]) { test_bmp application=new test_bmp(); //Main window JFrame frame=new JFrame("Whiteboard"); frame.setLayout(new BorderLayout()); frame.add(application.addButtons(),BorderLayout.WEST); frame.add(application); //size of the window frame.setSize(600,400); frame.setLocation(0,0); frame.setVisible(true); int w = frame.getWidth(); int h = frame.getHeight(); image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); g2.setPaint(Color.white); g2.fillRect(0,0,w,h); g2.dispose(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent event) { start = event.getPoint(); } @Override public void mouseReleased(MouseEvent event) { end = event.getPoint(); draw(); } @Override public void mouseDragged(MouseEvent e) { end=e.getPoint(); repaint(); } @Override public void mouseMoved(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==elipse) selected="elipse"; if(e.getSource()==line) selected="line"; draw(); } } I need to create a paint application, when i draw elipse by dragging mouse from left to right it displays nothing, why?? should i use any other function here?

    Read the article

  • Various GPS Android Functionality Questions..

    - by Tyler
    Hello - I have a few questions (so far) with the the LocationManager on Android and GPS in general.. Feel free to answer any number of the questions below, and I appreciate your help in advance! (I noticed this stuff doesn't appear to be documented very well, so hopefully these questions will help others out too!) 1) I am using the following code, but I think there may be extra fluff in here that I do not need. Can you tell me if I can delete any of this? LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); LocationListener locationListener = new MyLocationListener(); lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); LocationProvider locationProvider = lm.getProvider("gps"); Location currentLocation = lm.getLastKnownLocation(locationProvider.getName()); 2) Is there a way to hold off on the last step (accessing "getLastKnownLocation" until after I am sure I have a GPS lock? What happens if this is called and GPS is still looking for signal? 3) MOST importantly, I want to ensure I have a GPS lock before I proceed to my next method, so is there a way to check to see if GPS is locked on and getLastKnownLocation is up to date? 4) Is there a way to 'shut down' the GPS listener once it does receive a lock and getLastKnownLocation is updated? I don't see a need to keep this running for my application once I have obtained a lock.. 5) Can you please confirm my assumption that "getLastKnownLocation" is updated frequently as the receiver moves? 6) In my code, I also have a class called "MyLocationListener" (code below) that I honestly just took from another example.. Is this actually needed? I assume this updates my location manager whenever the location changes, but it sure doesn't appear that there is much to the class itself! private class MyLocationListener implements LocationListener { @Override public void onLocationChanged(Location loc) { if (loc != null) { //Toast.makeText(getBaseContext(), "Location changed : Lat: " + loc.getLatitude() + " Lng: " + loc.getLongitude(), Toast.LENGTH_SHORT).show(); } } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } }

    Read the article

  • Switch activity from a AlertDialog button

    - by Fahim Ahmed
    Let's say , I have three classes : MapsActivity , MyItemizedOverlay & GetDirectionActivity . In MyItemizedOverlay , I want to switch to GetDirectionActivity after the positive dialog button is clicked . ActiveDialog is placed under onTap method , so that I can get the GeoPoint. For this , what I've done : In ItemizedOverlay class : @Override public boolean onTap(GeoPoint p, MapView mapView) { // TODO Auto-generated method stub int lat = p.getLatitudeE6(); int lot = p.getLongitudeE6(); AlertDialog.Builder dialog = new AlertDialog.Builder(mContext); dialog.setTitle("Confirmation"); dialog.setMessage("Confirm this as end point ?"); dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int arg1) { // TODO Auto-generated method stub Intent intent = new Intent(mContext, GetDestination.class); startActivity(intent); } }); dialog.setNegativeButton("No", null); dialog.show(); return true ; } here IDE shows that I have a error in startActivity(intent) line . I've tried that also : In MyItemizedOverlay class : @Override public boolean onTap(GeoPoint p, MapView mapView) { return super.onTap(p, mapView); } In MapsActivity class : GeoPoint point2 = null ; confirmationOverlay.onTap(point2, mapView) ; int latt = point.getLatitudeE6() ; int longt = point.getLongitudeE6(); final int endpointArray [] = {latt , longt}; if(some condition to show the alert dialog after tapping) { AlertDialog.Builder dialog = new AlertDialog.Builder(MapsActivity.this); dialog.setTitle("Confirmation"); dialog.setMessage("Confirm this location as end point ?"); dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int arg1) { // TODO Auto-generated method stub Intent intent = new Intent(MapsActivity.this,GetDestination.class); intent.putExtra("geopoint" , endpointArray); startActivity(intent); } }); dialog.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int arg1) { } }); dialog.show(); } For the if statement what sort of condition I can use ? If I set it just like lat0 then the alertdialog appears without tapping on the map. I know this is very silly , but since I am new in both android & java , I hope you guys will consider it. Please help !

    Read the article

  • Adding an overlay to Google maps with path taken

    - by user341652
    Hi, I am trying to write a class to track a person's location(s), and to draw the path they've taken on a MapView. This feature of the program is for the user to track their speed, distance, path, etc. while running/cycling (or whatever else) using their Android phone. This is my first Android application, and I am not sure how to do the Overlay object for the MapView. I also wanted to see if anyone had opinions on the GPS-Tracking part I have written (if it would work, if there is a better way of doing it, code examples would be helpful). I currently have this for my GPSTrackerService: package org.drexel.itrain.logic; import java.util.Vector; import org.drexel.itrain.Constants; import android.app.Notification; import android.app.NotificationManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.GpsStatus.Listener; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; public class GPSTrackingService extends Service { private static final int MAX_REASONABLE_SPEED = 60; private static final String TAG = "OGT.TrackingService"; private Context mContext; private LocationManager mLocationManager; private NotificationManager mNotificationManager; private Notification mNotification; private int mSatellites = 0; private int mTrackingState = Constants.GPS_TRACKING_UNKNOWN; private float mCurrentSpeed = 0; private float mTotalDistance = 0; private Location mPreviousLocation; private Vector<Location> mTrackedLocations; private LocationListener mLocationListener = null; private Listener mStatusListener = null; private IBinder binder = null; @Override public void onCreate() { super.onCreate(); this.mContext = getApplicationContext(); this.mLocationManager = (LocationManager) this.mContext.getSystemService( Context.LOCATION_SERVICE ); this.mNotificationManager = (NotificationManager) this.mContext.getSystemService( Context.NOTIFICATION_SERVICE ); this.mTrackedLocations = new Vector<Location>(); this.binder = new Binder(); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.mContext); binder = new Binder(); if(mTrackingState != Constants.GPS_TRACKING_UNKNOWN) { createListeners(); } } @Override public void onDestroy() { destroyListeneres(); } @Override public IBinder onBind(Intent intent) { return binder; } @Override public boolean onUnbind(Intent intent) { return true; } public boolean acceptLocation(Location proposedLocation) { if(!(proposedLocation.hasSpeed() || proposedLocation.hasAccuracy())) { return false; } else if(proposedLocation.getSpeed() >= MAX_REASONABLE_SPEED) { return false; } return true; } public void updateNotification() { //TODO Alert that no GPS sattelites are available (or are available) } public void startTracking() { this.mTrackingState = Constants.GPS_TRACKING_STARTED; this.mTotalDistance = 0; this.mCurrentSpeed = 0; this.mTrackedLocations = new Vector<Location>(); this.mPreviousLocation = null; createListeners(); } public void pauseTracking() { this.mTrackingState = Constants.GPS_TRACKING_PAUSED; this.mPreviousLocation = null; this.mCurrentSpeed = 0; } public void resumeTracking() { if(this.mTrackingState == Constants.GPS_TRACKING_STOPPED){ this.startTracking(); } this.mTrackingState = Constants.GPS_TRACKING_STARTED; } public void stopTracking() { this.mTrackingState = Constants.GPS_TRACKING_STOPPED; destroyListeneres(); } private void createListeners() { /** * LocationListener receives locations from */ this.mLocationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onLocationChanged(Location location) { if(mTrackingState == Constants.GPS_TRACKING_STARTED && acceptLocation(location)) { if(mPreviousLocation != null) { //Add the distance between the new location and the previous location mTotalDistance += mPreviousLocation.distanceTo(location); } if(location.hasSpeed()) { mCurrentSpeed = location.getSpeed(); } else { mCurrentSpeed = -1; //-1 means speed N/A } mPreviousLocation = location; mTrackedLocations.add(location); } } }; /** * Receives updates reguarding the GPS Status */ this.mStatusListener = new GpsStatus.Listener() { @Override public synchronized void onGpsStatusChanged(int event) { switch( event ) { case GpsStatus.GPS_EVENT_SATELLITE_STATUS: { GpsStatus status = mLocationManager.getGpsStatus( null ); mSatellites = 0; Iterable<GpsSatellite> list = status.getSatellites(); for( GpsSatellite satellite : list ) { if( satellite.usedInFix() ) { mSatellites++; } } updateNotification(); break; } default: break; } } }; } /** * Destroys the LocationListenere and the GPSStatusListener */ private void destroyListeneres() { this.mLocationListener = null; this.mStatusListener = null; } /** * Gets the total distance traveled by the * * @return the total distance traveled (in meters) */ public float getDistance() { return mTotalDistance; } /** * Gets the current speed of the last good location * * @return the current speed (in meters/second) */ public float getSpeed() { return mCurrentSpeed; } } Any assistance would be much appreciated. This is my group's first Android app, and we are a little pressed for time at the moment. The project is for a class, and is available from SourceForge (currently called iTrain, soon to be renamed). Thanks in Advance, Steve

    Read the article

  • How to automatically insert a class notation using eclipse templates?

    - by João Paulo G. Piccinini
    Does anybody know how to insert a "@RunWith anotation" above the class signature, using eclipse templates? Ex.: @RunWith(Parameterized.class) public class MyClassTest { ... @Parameters public static Collection<Object[]> parameters() { List<Object[]> list = new ArrayList<Object[]>(); list.add(new Object[] { "mind!", "find!" }); list.add(new Object[] { "misunderstood", "understood" }); return list; } ... } __ Template: // TODO: move this '@RunWith(Parameterized.class)' to class anotation @Parameters public static Collection<Object[]> parameters() { ${type:elemType(collection)}<Object[]> parametersList = new ${type:elemType(collection)}<Object[]>(); ${cursor}// TODO: populate collection return parametersList; } __ Thanks for the help!

    Read the article

  • Unable to get the DspStatus Field in the Task document properties.

    - by Pari
    Hi, I am using Interop.Domino.dll API to read the NSF file and able to read the properties of the Task Document. When i view the Task Document properties in the Lotus Notes, i am able to view the Status Field, Importance Field and few others, but when i programatically dump all the Field Names and their values i am unable to get few of them as mentioned above. So, how to get all the Field Names and their values as i iterate through all the document properties. Is this the problem of IBM Lotus Notes Application or the Domino API ? Here is my sample code to iterate the TODO document properties : object[] TaskItems = docTodoDoc.Items as object[]; foreach (NotesItem objItem in TaskItems) { m_objLogFile.Debug(objItem.Name + " - "); m_objLogFile.Debug("Values :: " + ((object[])docTodoDoc.GetItemValue(objItem.Name))[0] as String); } Please help me out to over come this issue as i need to access the status value of the TODO Item from the NSF file. Thanks.

    Read the article

  • Under what circumstances would a LINQ-to-SQL Entity "lose" a changed field?

    - by John Rudy
    I'm going nuts over what should be a very simple situation. In an ASP.NET MVC 2 app (not that I think this matters), I have an edit action which takes a very small entity and makes a few changes. The key portion (outside of error handling/security) looks like this: Todo t = Repository.GetTodoByID(todoID); UpdateModel(t); Repository.Save(); Todo is the very simple, small entity with the following fields: ID (primary key), FolderID (foreign key), PercentComplete, TodoText, IsDeleted and SaleEffortID (foreign key). Each of these obviously corresponds to a field in the database. When UpdateModel(t) is called, t does get correctly updated for all fields which have changed. When Repository.Save() is called, by the time the SQL is written out, FolderID reverts back to its original value. The complete code to Repository.Save(): public void Save() { myDataContext.SubmitChanges(); } myDataContext is an instance of the DataContext class created by the LINQ-to-SQL designer. Nothing custom has been done to this aside from adding some common interfaces to some of the entities. I've validated that the FolderID is getting lost before the call to Repository.Save() by logging out the generated SQL: UPDATE [Todo].[TD_TODO] SET [TD_PercentComplete] = @p4, [TD_TodoText] = @p5, [TD_IsDeleted] = @p6 WHERE ([TD_ID] = @p0) AND ([TD_TDF_ID] = @p1) AND /* Folder ID */ ([TD_PercentComplete] = @p2) AND ([TD_TodoText] = @p3) AND (NOT ([TD_IsDeleted] = 1)) AND ([TD_SE_ID] IS NULL) /* SaleEffort ID */ -- @p0: Input BigInt (Size = -1; Prec = 0; Scale = 0) [5] -- @p1: Input BigInt (Size = -1; Prec = 0; Scale = 0) [1] /* this SHOULD be 4 and in the update list */ -- @p2: Input TinyInt (Size = -1; Prec = 0; Scale = 0) [90] -- @p3: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [changing text] -- @p4: Input TinyInt (Size = -1; Prec = 0; Scale = 0) [0] -- @p5: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [changing text foo] -- @p6: Input Bit (Size = -1; Prec = 0; Scale = 0) [True] -- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 4.0.30319.1 So somewhere between UpdateModel(t) (where I've validated in the debugger that FolderID updated) and the output of this SQL, the FolderID reverts. The other fields all save. (Well, OK, I haven't validated SaleEffortID yet, because that subsystem isn't really ready yet, but everything else saves.) I've exhausted my own means of research on this: Does anyone know of conditions which would cause a partial entity reset (EG, something to do with long foreign keys?), and/or how to work around this?

    Read the article

  • Problem when trying to connect to a desktop server from android on wifi

    - by thiagolee
    Hello, I am trying to send a file from the phone running Android 1.5 to a server on a desktop. I wrote some code, which works on emulator, but on the phone it doesn't. I'm connecting to the network through WiFi. It works, I can access the internet through my phone and I've configured my router. The application stops when I'm trying to connect. I have the permissions. Someone have any ideas, below is my code. Running on Android package br.ufs.reconhecimento; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.Socket; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.ImageButton; /** * Sample code that invokes the speech recognition intent API. */ public class Reconhecimento extends Activity implements OnClickListener { static final int VOICE_RECOGNITION_REQUEST_CODE = 1234; static final String LOG_VOZ = "UFS-Reconhecimento"; final int INICIAR_GRAVACAO = 01; int porta = 5158; // Porta definida no servidor int tempoEspera = 1000; String ipConexao = "172.20.0.189"; EditText ipEdit; /** * Called with the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Inflate our UI from its XML layout description. setContentView(R.layout.main); // Get display items for later interaction ImageButton speakButton = (ImageButton) findViewById(R.id.btn_speak); speakButton.setPadding(10, 10, 10, 10); speakButton.setOnClickListener(this); //Alerta para o endereço IP AlertDialog.Builder alerta = new AlertDialog.Builder(this); alerta.setTitle("IP");//+mainWifi.getWifiState()); ipEdit = new EditText(this); ipEdit.setText(ipConexao); alerta.setView(ipEdit); alerta.setMessage("Por favor, Confirme o endereço IP."); alerta.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ipConexao = ipEdit.getText().toString(); Log.d(LOG_VOZ, "Nova Atribuição do Endreço IP: " + ipConexao); } }); alerta.create(); alerta.show(); } /** * Handle the click on the start recognition button. */ public void onClick(View v) { if (v.getId() == R.id.btn_speak) { //startVoiceRecognitionActivity(); Log.d(LOG_VOZ, "Iniciando a próxima tela"); Intent recordIntent = new Intent(this, GravacaoAtivity.class); Log.d(LOG_VOZ, "Iniciando a tela (instancia criada)"); startActivityForResult(recordIntent, INICIAR_GRAVACAO); Log.d(LOG_VOZ, "Gravação iniciada ..."); } } /** * Handle the results from the recognition activity. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(LOG_VOZ, "Iniciando onActivityResult()"); if (requestCode == INICIAR_GRAVACAO && resultCode == RESULT_OK) { String path = data.getStringExtra(GravacaoAtivity.RETORNO); conexaoSocket(path); } else Log.e(LOG_VOZ, "Resultado Inexperado ..."); } private void conexaoSocket(String path) { Socket socket = SocketOpener.openSocket(ipConexao, porta, tempoEspera); if(socket == null) return; try { DataOutputStream conexao = new DataOutputStream(socket.getOutputStream()); Log.d(LOG_VOZ, "Acessando arquivo ..."); File file = new File(path); DataInputStream arquivo = new DataInputStream(new FileInputStream(file)); Log.d(LOG_VOZ, "Iniciando Transmissão ..."); conexao.writeLong(file.length()); for(int i = 0; i < file.length(); i++) conexao.writeByte(arquivo.readByte()); Log.d(LOG_VOZ, "Transmissão realizada com sucesso..."); Log.d(LOG_VOZ, "Fechando a conexão..."); conexao.close(); socket.close(); Log.d(LOG_VOZ, "============ Processo finalizado com Sucesso =============="); } catch (IOException e) { Log.e(LOG_VOZ, "Erro ao fazer a conexão via Socket. " + e.getMessage()); // TODO Auto-generated catch block } } } class SocketOpener implements Runnable { private String host; private int porta; private Socket socket; public SocketOpener(String host, int porta) { this.host = host; this.porta = porta; socket = null; } public static Socket openSocket(String host, int porta, int timeOut) { SocketOpener opener = new SocketOpener(host, porta); Thread t = new Thread(opener); t.start(); try { t.join(timeOut); } catch(InterruptedException e) { Log.e(Reconhecimento.LOG_VOZ, "Erro ao fazer o join da thread do socket. " + e.getMessage()); //TODO: Mensagem informativa return null; } return opener.getSocket(); } public void run() { try { socket = new Socket(host, porta); }catch(IOException e) { Log.e(Reconhecimento.LOG_VOZ, "Erro na criação do socket. " + e.getMessage()); //TODO: Mensagem informativa } } public Socket getSocket() { return socket; } } Running on the desktop Java: import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class ServidorArquivo { private static int porta = 5158; static String ARQUIVO = "voz.amr"; /** * Caminho que será gravado o arquivo de audio */ static String PATH = "/home/iade/Trabalho/lib/"; public static void main(String[] args) { int i = 1; try { System.out.println("Iniciando o Servidor Socket - Android."); ServerSocket s = new ServerSocket(porta); System.out.println("Servidor Iniciado com Sucesso..."); System.out.println("Aguardando conexões na porta: " + porta); while(true) { Socket recebendo = s.accept(); System.out.println("Aceitando conexão de nº " + i); new ThreadedHandler(recebendo).start(); i++; } } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); e.printStackTrace(); } } } class ThreadedHandler extends Thread { private Socket socket; public ThreadedHandler(Socket so) { socket = so; } public void run() { DataInputStream entrada = null; DataOutputStream arquivo = null; try { entrada = new DataInputStream(socket.getInputStream()); System.out.println("========== Iniciando a leitura dos dados via Sockets =========="); long tamanho = entrada.readLong(); System.out.println("Tamanho do vetor " + tamanho); File file = new File(ServidorArquivo.PATH + ServidorArquivo.ARQUIVO); if(!file.exists()) file.createNewFile(); arquivo = new DataOutputStream(new FileOutputStream(file)); for(int j = 0; j < tamanho; j++) { arquivo.write(entrada.readByte()); } System.out.println("========== Dados recebidos com sucesso =========="); } catch (Exception e) { System.out.println("Erro ao tratar do socket: " + e.getMessage()); e.printStackTrace(); } finally { System.out.println("**** Fechando as conexões ****"); try { entrada.close(); socket.close(); arquivo.close(); } catch (IOException e) { System.out.println("Erro ao fechar conex&#65533;es " + e.getMessage()); e.printStackTrace(); } } System.out.println("============= Fim da Gravação ==========="); // tratar o arquivo String cmd1 = "ffmpeg -i voz.amr -ab 12288 -ar 16000 voz.wav"; String cmd2 = "soundstretch voz.wav voz2.wav -tempo=100"; String dir = "/home/iade/Trabalho/lib"; File workDir = new File(dir); File f1 = new File(dir+"/voz.wav"); File f2 = new File(dir+"/voz2.wav"); f1.delete(); f2.delete(); try { executeCommand(cmd1, workDir); System.out.println("realizou cmd1"); executeCommand(cmd2, workDir); System.out.println("realizou cmd2"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void executeCommand(String cmd1, File workDir) throws IOException, InterruptedException { String s; Process p = Runtime.getRuntime().exec(cmd1,null,workDir); int i = p.waitFor(); if (i == 0) { BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); // read the output from the command while ((s = stdInput.readLine()) != null) { System.out.println(s); } } else { BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command while ((s = stdErr.readLine()) != null) { System.out.println(s); } } } } Thanks in advance.

    Read the article

  • How to sort list items for Date field value (Apex, Salesforce)

    - by Channa
    With Salesforce's Apex, is there any way to sort list items, for Date field value. Please refer the TODO section of the following code, thanks. /** * Select list of jobOccurrences belongs to particular list of jobs */ private List<Job_Occurrence__c> getJobsByJobCode(List<Job__c> jobList) { // Select relevant Job Occurrence objects List<Job_Occurrence__c> jobOccuList = new List<Job_Occurrence__c>(); for (Job__c job : jobList) { Job_Occurrence__c jobOccurrence = [SELECT Id, Job__c, Schedule_Start_Date__c FROM Job_Occurrence__c WHERE Job__c =: job.Id]; if((jobOccurrence != null) && (jobOccurrence.Id != null)) { jobOccuList.add(jobOccurrence); } } if((jobOccuList != null) && (jobOccuList.size() > 0)) { // TODO // How I sort the 'jobOccuList' with Date field 'Schedule_Start_Date__c', // for select the items according to sequence of latest jobOccurrence return jobOccuList; } else { throw new RecordNotFoundException ('Could not found any jobOccurrence for given list of jobs'); } }

    Read the article

  • How can i do the same thing with Gallery in Android

    - by Maxood
    I am navigating images with the clicks of next and previous buttons.Here is my code: package com.myapps.imagegallery; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class ImageGallery extends Activity { /** Called when the activity is first created. */ int imgs[] = {R.drawable.bluehills,R.drawable.lilies,R.drawable.sunset,R.drawable.winter}; String desc[] = {"Blue Hills", "Lillies", "Sunset", "Winter" }; int counter=0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final ImageView imgView = (ImageView)findViewById(R.id.ImageView01); imgView.setImageResource(imgs[counter]); final TextView tvDesc = (TextView)findViewById(R.id.tvDesc); Button btnNext = (Button)findViewById(R.id.btnNext); btnNext.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View arg0) { try{ // TODO Auto-generated method stub if (counter < desc.length -1) counter++; imgView.setImageResource(imgs[counter]); tvDesc.setText(desc[counter]); }catch(Exception e) { Toast.makeText(ImageGallery.this, e.toString(), Toast.LENGTH_SHORT).show(); } } }); Button btnPrev = (Button)findViewById(R.id.btnPre); btnPrev.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub try{ // TODO Auto-generated method stub if (counter > 0) counter--; imgView.setImageResource(imgs[counter]); tvDesc.setText(desc[counter]); }catch(Exception e) { Toast.makeText(ImageGallery.this, e.toString(), Toast.LENGTH_SHORT).show(); } }}); } } <?xml version="1.0" encoding="utf-8"?> <AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:id="@+id/ImageView01" android:layout_x="70dip" android:layout_width="200px" android:layout_height="200px" android:layout_y="90dip" > </ImageView> <TextView android:id="@+id/tvDesc" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" android:layout_x="90px" android:layout_y="300px" /> <Button android:layout_x="47dip" android:layout_height="wrap_content" android:text="Previous" android:layout_width="100px" android:id="@+id/btnPre" android:layout_y="341dip"> </Button> <Button android:layout_x="190dip" android:layout_height="wrap_content" android:text="Next" android:layout_width="100px" android:id="@+id/btnNext" android:layout_y="341dip"> </Button> </AbsoluteLayout>

    Read the article

  • Java Box Class: Unsolvable: aligning components to the left or right

    - by user323186
    I have been trying to left align buttons contained in a Box to the left, with no success. They align left alright, but for some reason dont shift all the way left as one would imagine. I attach the code below. Please try compiling it and see for yourself. Seems bizarre to me. Thanks, Eric import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class MainGUI extends Box implements ActionListener{ //Create GUI Components Box centerGUI=new Box(BoxLayout.X_AXIS); Box bottomGUI=new Box(BoxLayout.X_AXIS); //centerGUI subcomponents JTextArea left=new JTextArea(), right=new JTextArea(); JScrollPane leftScrollPane = new JScrollPane(left), rightScrollPane = new JScrollPane(right); //bottomGUI subcomponents JButton encrypt=new JButton("Encrypt"), decrypt=new JButton("Decrypt"), close=new JButton("Close"), info=new JButton("Info"); //Create Menubar components JMenuBar menubar=new JMenuBar(); JMenu fileMenu=new JMenu("File"); JMenuItem open=new JMenuItem("Open"), save=new JMenuItem("Save"), exit=new JMenuItem("Exit"); int returnVal =0; public MainGUI(){ super(BoxLayout.Y_AXIS); initCenterGUI(); initBottomGUI(); initFileMenu(); add(centerGUI); add(bottomGUI); addActionListeners(); } private void addActionListeners() { open.addActionListener(this); save.addActionListener(this); exit.addActionListener(this); encrypt.addActionListener(this); decrypt.addActionListener(this); close.addActionListener(this); info.addActionListener(this); } private void initFileMenu() { fileMenu.add(open); fileMenu.add(save); fileMenu.add(exit); menubar.add(fileMenu); } public void initCenterGUI(){ centerGUI.add(leftScrollPane); centerGUI.add(rightScrollPane); } public void initBottomGUI(){ bottomGUI.setAlignmentX(LEFT_ALIGNMENT); //setBorder(BorderFactory.createLineBorder(Color.BLACK)); bottomGUI.add(encrypt); bottomGUI.add(decrypt); bottomGUI.add(close); bottomGUI.add(info); } @Override public void actionPerformed(ActionEvent arg0) { // find source of the action Object source=arg0.getSource(); //if action is of such a type do the corresponding action if(source==close){ kill(); } else if(source==open){ //CHOOSE FILE File file1 =chooseFile(); String input1=readToString(file1); System.out.println(input1); left.setText(input1); } else if(source==decrypt){ //decrypt everything in Right Panel and output in left panel decrypt(); } else if(source==encrypt){ //encrypt everything in left panel and output in right panel encrypt(); } else if(source==info){ //show contents of info file in right panel doInfo(); } else { System.out.println("Error"); //throw new UnimplementedActionException(); } } private void doInfo() { // TODO Auto-generated method stub } private void encrypt() { // TODO Auto-generated method stub } private void decrypt() { // TODO Auto-generated method stub } private String readToString(File file) { FileReader fr = null; try { fr = new FileReader(file); } catch (FileNotFoundException e1) { e1.printStackTrace(); } BufferedReader br=new BufferedReader(fr); String line = null; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } String input=""; while(line!=null){ input=input+"\n"+line; try { line=br.readLine(); } catch (IOException e) { e.printStackTrace(); } } return input; } private File chooseFile() { //Create a file chooser final JFileChooser fc = new JFileChooser(); returnVal = fc.showOpenDialog(fc); return fc.getSelectedFile(); } private void kill() { System.exit(0); } public static void main(String[] args) { // TODO Auto-generated method stub MainGUI test=new MainGUI(); JFrame f=new JFrame("Tester"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setJMenuBar(test.menubar); f.setPreferredSize(new Dimension(600,400)); //f.setUndecorated(true); f.add(test); f.pack(); f.setVisible(true); } }

    Read the article

  • Android: Playing sound when button clicked?

    - by gazeebo
    Hi all, I'm trying to play a sound file when a button is clicked but keeps getting an error. The error is "The method create(Context, int) in the type MediaPlayer is not applicable for the arguments (new View.OnClickListener(){}, int)" Here's my code: @Override public void onClick(View v) { // TODO Auto-generated method stub Button zero = (Button)this.findViewById(R.id.btnZero); zero.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub mp = MediaPlayer.create(this, R.raw.mamacita_zero); } }); } Any help or tips would be appreciated. Thnx!

    Read the article

  • Unit testing class in a web service in .net

    - by Dan Bailiff
    After some digging here, I took the advice in this thread: http://stackoverflow.com/questions/371961/how-to-unit-test-c-web-service-with-visual-studio-2008 I've created a separate class and my web service class is just a wrapper for that one. The problem is that when I try to create a unit test project in VS2008, it insists on creating a unit test that acts like I'm testing the web service calls instead of the class I specified. I can't get to the class I'm trying to test. I have a web service "subscription_api.asmx". The code behind is "subscription_api.cs" which contains the web method wrapper calls to the real code at "subscription.cs". I would expect to be able to do the following: [TestMethod()] public void GetSystemStatusTest() { subscription sub = new subscription(); XmlNode node = sub.GetSystemStatusTest(); Assert.IsNotNull(node); } But instead I get this mess which is autogenerated from VS'08: /// <summary> ///A test for GetSystemStatus ///</summary> // TODO: Ensure that the UrlToTest attribute specifies a URL to an ASP.NET page (for example, // http://.../Default.aspx). This is necessary for the unit test to be executed on the web server, // whether you are testing a page, web service, or a WCF service. [TestMethod()] [HostType("ASP.NET")] [AspNetDevelopmentServerHost("C:\\CVSROOT\\rnr\\pro\\product\\wms\\ss\\subscription_api", "/subscription_api")] [UrlToTest("http://localhost/subscription_api")] public void GetSystemStatusTest() { subscription_Accessor target = new subscription_Accessor(); // TODO: Initialize to an appropriate value XmlNode expected = null; // TODO: Initialize to an appropriate value XmlNode actual; actual = target.GetSystemStatus(); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); } Additionally, there is a "subscription_api.accessor" in the Test References folder. When I try this: [TestMethod()] public void GetSystemStatusTest2() { subscription_Accessor sub = new subscription_Accessor(); XmlNode node = sub.GetSystemStatus(); Assert.IsNotNull(node); } I get an error: Test method subscription_api.Test.subscriptionTest.GetSystemStatusTest2 threw exception: System.TypeInitializationException: The type initializer for 'subscription_Accessor' threw an exception. ---> System.ArgumentNullException: Value cannot be null. I'm really new to unit testing and feel lost. How can I create a unit test just for my subscription class in "subscription.cs" without testing the web service? Am I limited to testing within the same project (I hope not)? Do I have to put the target class in its own project outside of the web service project?

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >