Search Results

Search found 2978 results on 120 pages for 'ex parrot'.

Page 14/120 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • Java: CSV file read & write.

    - by battousai622
    Im reading in 2 csv file: store_inventory & new_acquisitions... I want to be able to compare the store_inventory csv file with new_acquisitions. 1) If the item names match just update the quantity in store_inventory. 2) If new_acquisitions has a new item that does not exist in store_inventory, then add it to the store_inventory. Heres what i have so far but its not very good. I added comments where i need to add taks 1) & 2). Any advice or code would be great, thanks. File new_acq = new File("/src/test/new_acquisitions.csv"); Scanner acq_scan = null; try { acq_scan = new Scanner(new_acq); } catch (FileNotFoundException ex) { Logger.getLogger(mainpage.class.getName()).log(Level.SEVERE, null, ex); } String itemName; int quantity; Double cost; Double price; File store_inv = new File("/src/test/store_inventory.csv"); Scanner invscan = null; try { invscan = new Scanner(store_inv); } catch (FileNotFoundException ex) { Logger.getLogger(mainpage.class.getName()).log(Level.SEVERE, null, ex); } String itemNameInv; int quantityInv; Double costInv; Double priceInv; while (acq_scan.hasNext()) { String line = acq_scan.nextLine(); if (line.charAt(0) == '#') { continue; } String[] split = line.split(","); itemName = split[0]; quantity = Integer.parseInt(split[1]); cost = Double.parseDouble(split[2]); price = Double.parseDouble(split[3]); while(invscan.hasNext()) { String line2 = invscan.nextLine(); if (line2.charAt(0) == '#') { continue; } String[] split2 = line2.split(","); itemNameInv = split2[0]; quantityInv = Integer.parseInt(split2[1]); costInv = Double.parseDouble(split2[2]); priceInv = Double.parseDouble(split2[3]); if(itemName == itemNameInv) { //update quantity } } //add new entry into csv file } Thanks again for any help. =]

    Read the article

  • Is there a reason Image.FromFile throws an OutOfMemoryException for an invalid image format?

    - by Arc
    I am writing code that catches this OutOfMemoryException and throws a new, more intuitive exception: /// ... /// <exception cref="FormatException">The file does not have a valid image format.</exception> public static Image OpenImage( string filename ) { try { return Image.FromFile( filename, ); } catch( OutOfMemoryException ex ) { throw new FormatException( "The file does not have a valid image format.", ex ); } } Is this code acceptable to its user, or is OutOfMemoryException intentionally being thrown for a particular reason?

    Read the article

  • [NEWVERSION]algorithm || method to write prog[UNSOLVED] [closed]

    - by fatai
    I am one of the computer science student. Everyone solve problem with a different or same method, ( but actually I dont know whether they use method or I dont know whether there are such common method to approach problem.) if there are common method, What is it ? If there are different method, which method are you using ? All teacher give us problem which in simple form sometimes, but they donot introduce any approach or method(s) so that we cannot make a decision to choose the method then apply that one to problem , afterward find solution then write code.No help from teacher , push us to find method to solve homework. Ex: my friend is using no method , he says "I start to construct algorithm while I try to write prog." I have found one method when I failed the course, More accurately, my method: When I counter problem in language , I will get more paper and then ; first, input/ output step ; my prog will take this / these there argument(s) and return namely X , ex : in c, input length is not known and at same type , so I must use pointer desired output is in form of package , so use structure second, execution part ; in that step , I am writing all step which are goes to final output ex : in python ; 1.) [ + , [- , 4 , [ * , 1 , 2 ]], 5] 2.) [ + , [- , 4 , 2 ],5 ] 3.) [ + , 2 , 5] 4.) 7 ==> return 7 third, I will write test code ex : in c++ input : append 3 4 5 6 vector_x remove 0 1 desired output vector_x holds : 5 6 now, my other question is ; What is/are other method(s) which have/has been; used to construct class :::: for c++ , python, java used to communicate classes / computers used for solving embedded system problem ::::: for c by other user? Some programmer uses generalized method without considering prog-language(java , perl .. ), what is this method ? Why I wonder , because I learn if you dont costruct algorithm on paper, you may achieve your goal. Like no money no lunch , I can say no algorithm no prog therefore , feel free when you write your own method , a way which is introduced by someone else but you are using and you find it is so efficient

    Read the article

  • android zxing intentintegrator

    - by cristi _b
    I've written the following code that works fine if you decide to scan a QR code (using zxing) and store it in private storage but in case you decide to cancel scanning, it crashes and the file previously stored content disappears. I think it might be a design error, not sure why. Below is relevant code ... /** * menu generation */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } /** * menu handling */ @Override public boolean onOptionsItemSelected(MenuItem item) { Context context = getApplicationContext(); Toast toast = Toast.makeText(context, "", Toast.LENGTH_LONG); toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0); switch (item.getItemId()) { case R.id.qrScan: IntentIntegrator integrator = new IntentIntegrator(this); integrator.initiateScan(); return true; case R.id.qrReset: File dir = getFilesDir(); File file = new File(dir, qrCodeFile); boolean deleted = file.delete(); return true; case R.id.appClose: this.finish(); return true; default: return super.onOptionsItemSelected(item); } } ... public void onActivityResult(int requestCode, int resultCode, Intent intent) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); Context context = getApplicationContext(); Toast toast = Toast.makeText(context, "", Toast.LENGTH_SHORT); if (scanResult != null) { FileOutputStream fos = null; CharSequence text = scanResult.getContents(); try { fos = openFileOutput(qrCodeFile, Context.MODE_PRIVATE); try { fos.write(text.toString().getBytes()); fos.close(); toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0); toast.setText("Code saved"); toast.show(); } catch (IOException ex) { toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0); toast.setText("Invalid code"); toast.show(); Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex); } } catch (FileNotFoundException ex) { toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0); toast.setText("Error while saving"); toast.show(); Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex); } } else { toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0); toast.setText("Invalid code"); toast.show(); } }

    Read the article

  • pass Multilple paramets in struts action with same parameter name

    - by raju
    Hi I would like to pass Multiple parameters for single param in action tag. Ex: abc Answers.jsp I have getters and setters for hint (String) variable in my action. Currently i can be able to get parameter value for hint variable as abc if i send one. I would like to send multiple parameters for same variable(hint) ex: abc, xyz how can achieve the above. Thanks in advance Raju

    Read the article

  • WCF Troubleshooting from ASP.NET Client -- Help!

    - by Kobojunkie
    I am trying to call a method in my service that is as below, from an ASP.NET application. public bool ValidateUser(string username, string password) { try { // String CurrentLoggedInWindowsUserName = WindowsIdentity.GetCurrent().Name; // //primary identity of the call // String CurrentServiceSecurityContextPrimaryIdentityName = // ServiceSecurityContext.Current.PrimaryIdentity.Name; // } catch (Exception ex) { FaultExceptionFactory fct = new FaultExceptionFactory(); throw new FaultException<CustomFaultException>(fct.CreateFaultException(ex)); } return false; } The Config for the client end of my service is as below <binding name="WSHttpBinding_IMembershipService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="false" allowCookies="false"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" /> <security mode="Message"> <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" /> <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" /> </security> </binding> Problem I keep having is when I call it; I get the following exception message. Server Error in '/' Application. The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ServiceModel.CommunicationObjectFaultedException: The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state. Stack Trace: [CommunicationObjectFaultedException: The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.] System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +7596735 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +275 System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout) +0 System.ServiceModel.ClientBase`1.System.ServiceModel.ICommunicationObject. Close(TimeSpan timeout) +142 System.ServiceModel.ClientBase`1.Close() +38 System.ServiceModel.ClientBase`1.System.IDisposable.Dispose() +4 Controls.Membership.accountLogin.ValidateUserCredentials(String UserName, String Password) in C:\ Petition.WebClient\Controls\ Membership\accountLogin.ascx.cs:49 Controls.Membership.accountLogin.Login1_Authenticate(Object sender, AuthenticateEventArgs e) in C:\ WebClient\ Controls\Membership \accountLogin.ascx.cs:55 I am not entirely sure why I keep getting this. Just in case, here is how I call my service from the client private bool ValidateUserCredentials(string UserName, string Password) { bool boolReturnValue = false; using(Members.MembershipServiceClient client = new Controls.Members.MembershipServiceClient()) { try { boolReturnValue = client.ValidateUser(UserName, Password); } catch (FaultException<CustomFaultException> ex) { throw ex; } } return boolReturnValue; } Anyone have any idea what I need to do in this case?

    Read the article

  • Need help with Java Producer Consumer Problem, NullPointerException

    - by absk
    This is my code: package test; import java.util.logging.Level; import java.util.logging.Logger; class Data{ int ar[]=new int[50]; int ptr; Data() { for(int i=0;i<50;i++) ar[i]=0; ptr=0; } public int produce() { if(this.ptr<50) { this.ar[this.ptr]=1; this.ptr++; return this.ptr; } else return -1; } public int consume() { if(this.ptr>0) { this.ar[this.ptr]=0; this.ptr--; return this.ptr; } else return -1; } } class Prod implements Runnable{ private Main m; Prod(Main mm) { m=mm; } public void run() { int r = m.d.produce(); if (r != -1) { System.out.println("Produced, total elements: " + r); } else { try { wait(); } catch (InterruptedException ex) { Logger.getLogger(Prod.class.getName()).log(Level.SEVERE, null, ex); } } } } class Cons implements Runnable{ private Main m; Cons(Main mm) { m=mm; } public void run() { int r=m.d.consume(); if(r!=-1) System.out.println("Consumed, total elements: " + r); else { try { wait(); } catch (InterruptedException ex) { Logger.getLogger(Prod.class.getName()).log(Level.SEVERE, null, ex); } } notify(); } } public class Main{ Data d; public static void main(String s[]) throws InterruptedException{ Main m = new Main(); Prod p = new Prod(m); Cons c = new Cons(m); new Thread(p).start(); new Thread(c).start(); } } It is giving following errors: Exception in thread "Thread-0" Exception in thread "Thread-1" java.lang.NullPointerException at test.Cons.run(Main.java:84) at java.lang.Thread.run(Thread.java:619) java.lang.NullPointerException at test.Prod.run(Main.java:58) at java.lang.Thread.run(Thread.java:619) I am new to Java. Any help will be appreciated.

    Read the article

  • Validating against a Schema with JAXB

    - by fwgx
    I've been looking for solutions to this problem for far too long considering how easy it sounds so I've come for some help. I have an XML Schema which I have used with xjc to create my JAXB binding. This works fine when the XML is well formed. Unfortunately it also doesn't complain when the XML is not well formed. I cannot figure out how to do proper full validation against the schema when I try to unmarshall an XML file. I have managed to use a ValidationEventCollector to handle events, which works for XML parsing errors such as mismatched tags but doesn't raise any events when there is a tag that is required but is completely absent. From what I have seen validation can be done againsta schema, but you must know the path to the schema in order to pass it into the setSchema() method. The problem I have is that the path to the schema is stored in the XML header and I can't knwo at run time where the schema is going to be. Which is why it's stored in the XML file: <?xml version="1.0" encoding="utf-8"?> <DDSSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="/a/big/long/path/to/a/schema/file/DDSSettings.xsd"> <Field1>1</Field1> <Field2>-1</Field2> ...etc Every example I see uses setValidating(true), which is now deprecated, so throws an exception. This is the Java code I have so far, which seems to only do XML validation, not schema validation: try { JAXBContext jc = new JAXBContext() { private final JAXBContext jaxbContext = JAXBContext.newInstance("blah"); @Override public Unmarshaller createUnmarshaller() throws JAXBException { Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); ValidationEventCollector vec = new ValidationEventCollector() { @Override public boolean handleEvent(ValidationEvent event) throws RuntimeException { ValidationEventLocator vel = event.getLocator(); if (event.getSeverity() == event.ERROR || event.getSeverity() == event.FATAL_ERROR) { String error = "XML Validation Exception: " + event.getMessage() + " at row: " + vel.getLineNumber() + " column: " + vel.getColumnNumber(); System.out.println(error); } m_unmarshallingOk = false; return false; } }; unmarshaller.setEventHandler(vec); return unmarshaller; } @Override public Marshaller createMarshaller() throws JAXBException { throw new UnsupportedOperationException("Not supported yet."); } @Override @SuppressWarnings("deprecation") public Validator createValidator() throws JAXBException { throw new UnsupportedOperationException("Not supported yet."); } }; Unmarshaller unmarshaller = jc.createUnmarshaller(); m_ddsSettings = (com.ultra.DDSSettings)unmarshaller.unmarshal(new File(xmlfileName)); } catch (UnmarshalException ex) { Logger.getLogger(UniversalDomainParticipant.class.getName()).log( Level.SEVERE, null, ex); } catch (JAXBException ex) { Logger.getLogger(UniversalDomainParticipant.class.getName()).log( Level.SEVERE, null, ex); } So what is the proper way to do this validation? I was expecting there to be a validate() method on the JAXB generated classes, but I guess that would be too simple for Java.

    Read the article

  • Java - Runtime.getRuntime().exec() what's going on?

    - by kunkanwan
    Hi, I have problem with Runtime.exec() in Java My code: String lol = "/home/pc/example.txt"; String[] b = {"touch", lol}; try { Runtime.getRuntime().exec(b); } catch(Exception ex) { doSomething(ex); } It's working good but when I trying changle variable "lol" files doesn't create in hard disk for instance: String lol = x.getPath(); where getPath() returns String What should I do ? Thanks for your reply :)

    Read the article

  • Datagridview error

    - by Simon
    I have two datagridviews. So for the second one, i just copy-pasted the code from the first and changed where the difference was. But i get an error at the secod data grid when i want to view the result of my sql code. Translated in english the error show something like that there was no value given to at least one required parameter. Please help! private void button1_Click(object sender, EventArgs e) { string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=save.mdb"; try { database = new OleDbConnection(connectionString); database.Open(); date = DateTime.Now.ToShortDateString(); string queryString = "SELECT zivila.naziv,(obroki_save.skupaj_kalorij/zivila.kalorij)*100 as Kolicina_v_gramih " + "FROM (users LEFT JOIN obroki_save ON obroki_save.ID_uporabnika=users.ID)" + " LEFT JOIN zivila ON zivila.ID=obroki_save.ID_zivila " + " WHERE users.ID= " + a.ToString(); loadDataGrid(queryString); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } public void loadDataGrid(string sqlQueryString) { OleDbCommand SQLQuery = new OleDbCommand(); DataTable data = null; dataGridView1.DataSource = null; SQLQuery.Connection = null; OleDbDataAdapter dataAdapter = null; dataGridView1.Columns.Clear(); // <-- clear columns SQLQuery.CommandText = sqlQueryString; SQLQuery.Connection = database; data = new DataTable(); dataAdapter = new OleDbDataAdapter(SQLQuery); dataAdapter.Fill(data); dataGridView1.DataSource = data; dataGridView1.AllowUserToAddRows = false; dataGridView1.ReadOnly = true; dataGridView1.Columns[0].Visible = true; } private void Form8_Load(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=save.mdb"; try { database = new OleDbConnection(connectionString); database.Open(); date = DateTime.Now.ToShortDateString(); string queryString = "SELECT skupaj_kalorij " + "FROM obroki_save " + " WHERE users.ID= " + a.ToString(); loadDataGrid2(queryString); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } public void loadDataGrid2(string sqlQueryString) { OleDbCommand SQLQuery = new OleDbCommand(); DataTable data = null; dataGridView2.DataSource = null; SQLQuery.Connection = null; OleDbDataAdapter dataAdapter = null; dataGridView2.Columns.Clear(); // <-- clear columns SQLQuery.CommandText = sqlQueryString; SQLQuery.Connection = database; data = new DataTable(); dataAdapter = new OleDbDataAdapter(SQLQuery); dataAdapter.Fill(data); dataGridView2.DataSource = data; dataGridView2.AllowUserToAddRows = false; dataGridView2.ReadOnly = true; dataGridView2.Columns[0].Visible = true; }

    Read the article

  • Regex Help matching quotes

    - by Farhan
    Hi Guys, I havin a reg ex problemm i would like to have a reg ex that will match the '\nGO at the end of my file(see below.) I have got the following so far: ^\'*GO but its match the quote sysbol? EOF: WHERE (dbo.Property.Archived <> 1) ' GO

    Read the article

  • Running Network Application on port Server side give me error how can i solve it?

    - by Phsika
    if i run Server App. Exception occurs: on Dinle.Start() System.Net.SocketException - Only one usage of each socket address (protocol/network address/port) is normally permitted How can i solve this error? Server.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; namespace Server { public partial class Server : Form { Thread kanal; public Server() { InitializeComponent(); try { kanal = new Thread(new ThreadStart(Dinle)); kanal.Start(); kanal.Priority = ThreadPriority.Normal; this.Text = "Kanla Çalisti"; } catch (Exception ex) { this.Text = "kanal çalismadi"; MessageBox.Show("hata:" + ex.ToString()); kanal.Abort(); throw; } } private void Server_Load(object sender, EventArgs e) { Dinle(); } private void btn_Listen_Click(object sender, EventArgs e) { Dinle(); } void Dinle() { // IPAddress localAddr = IPAddress.Parse("localhost"); // TcpListener server = new TcpListener(port); // server = new TcpListener(localAddr, port); //TcpListener Dinle = new TcpListener(localAddr,51124); TcpListener Dinle = new TcpListener(51124); try { while (true) { Dinle.Start(); Exception is occured. Socket Baglanti = Dinle.AcceptSocket(); if (!Baglanti.Connected) { MessageBox.Show("Baglanti Yok"); } else { TcpClient tcpClient = Dinle.AcceptTcpClient(); if (tcpClient.ReceiveBufferSize 0) { byte[] Dizi = new byte[250000]; Baglanti.Receive(Dizi, Dizi.Length, 0); string Yol; saveFileDialog1.Title = "Dosyayi kaydet"; saveFileDialog1.ShowDialog(); Yol = saveFileDialog1.FileName; FileStream Dosya = new FileStream(Yol, FileMode.Create); Dosya.Write(Dizi, 0, Dizi.Length - 20); Dosya.Close(); listBox1.Items.Add("dosya indirildi"); listBox1.Items.Add("Dosya Boyutu=" + Dizi.Length.ToString()); listBox1.Items.Add("Indirilme Tarihi=" + DateTime.Now); listBox1.Items.Add("--------------------------------"); } } } } catch (Exception ex) { MessageBox.Show("hata:" + ex.ToString()); } } } }

    Read the article

  • EF4. Add a object with relationship causes full table select

    - by Fujiy
    Ex 1: "autor.ComentariosWorkItens.Add(comentarioWorkItem);" autor.ComentariosWorkItens makes EF4 load all ComentariosWorkItens. Ex 2: comentarioWorkItem.Usuario = autor; Fixup make EF load all ComentariosWorkItens too: private void FixupUsuario(Usuario previousValue) { if (previousValue != null && previousValue.ComentariosWorkItens.Contains(this)) { previousValue.ComentariosWorkItens.Remove(this); } if (Usuario != null) { if (!Usuario.ComentariosWorkItens.Contains(this)) { Usuario.ComentariosWorkItens.Add(this); } } } How can I prevent this?

    Read the article

  • Why is this simple file upload not working? JSF

    - by Nitesh Panchal
    Hello, Why is this code not working? I always get size() = 0, whenever i upload file. xhtml file :- <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title>Abc</title> </h:head> <h:body> <center> <form method="post" enctype="multipart/form-data" id="form" action="/upload/uploadFile"> <input type="file"/> <br/> <input type="Submit" value="upload"/> </form> </center> </h:body> </html> This is my servlet :- package servlets; import java.io.IOException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; @WebServlet(name="uploadFile", urlPatterns={"/uploadFile"}) public class uploadFile extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, FileUploadException { System.out.println("executed!"); List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); System.out.println(items.size()); for (FileItem item : items) { if (!item.isFormField()) { System.out.println("Name: " + item.getName()); System.out.println("Size: " + item.getSize()); System.out.println("Type: " + item.getContentType()); } } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (FileUploadException ex) { ex.printStackTrace(); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (FileUploadException ex) { ex.printStackTrace(); } } @Override public String getServletInfo() { return "Short description"; } }

    Read the article

  • Vaadin: Downloaded file has whole path as file name

    - by javydreamercsw
    I have a download action implemented on my Vaadin application but for some reason the downloaded file has the original file's full path as the file name. Any idea? You can see the code on this post. Edit: Here's the important part of the code: package com.bluecubs.xinco.core.server.vaadin; import com.bluecubs.xinco.core.server.XincoConfigSingletonServer; import com.vaadin.Application; import com.vaadin.terminal.DownloadStream; import com.vaadin.terminal.FileResource; import java.io.*; import java.net.URLEncoder; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.CRC32; import java.util.zip.CheckedInputStream; /** * * @author Javier A. Ortiz Bultrón<[email protected]> */ public class FileDownloadResource extends FileResource { private final String fileName; private File download; private File newFile; public FileDownloadResource(File sourceFile, String fileName, Application application) { super(sourceFile, application); this.fileName = fileName; } protected void cleanup() { if (newFile != null && newFile.exists()) { newFile.delete(); } if (download != null && download.exists() && download.listFiles().length == 0) { download.delete(); } } @Override public DownloadStream getStream() { try { //Copy file to directory for downloading InputStream in = new CheckedInputStream(new FileInputStream(getSourceFile()), new CRC32()); download = new File(XincoConfigSingletonServer.getInstance().FileRepositoryPath + System.getProperty("file.separator") + UUID.randomUUID().toString()); newFile = new File(download.getAbsolutePath() + System.getProperty("file.separator") + fileName); download.mkdirs(); OutputStream out = new FileOutputStream(newFile); newFile.deleteOnExit(); download.deleteOnExit(); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); final DownloadStream ds = new DownloadStream( new FileInputStream(newFile), getMIMEType(), fileName); ds.setParameter("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8")); ds.setCacheTime(getCacheTime()); return ds; } catch (final FileNotFoundException ex) { Logger.getLogger(FileDownloadResource.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (IOException ex) { Logger.getLogger(FileDownloadResource.class.getName()).log(Level.SEVERE, null, ex); return null; } } } I already debugged and verified that fileName only contains the file's name not the whole path.

    Read the article

  • jQuery, get table cell at specific index

    - by Jarek Waliszko
    Hello, I know that I can get first or last table cell (ex for last row) using jquery expression like below: first cell: $('#table tr:last td:first') or last cell: $('#table tr:last td:last') Can I get cell at specific index, for example index 2, using similliar expression: ex: $('#table tr:last td:[2]')... Regards.

    Read the article

  • How to change fileupload name

    - by Domnic
    im using following code to upload protected void UploadButton_Click(object sender, EventArgs e) { if(FileUploadControl.HasFile) { try { string filename = Path.GetFileName(FileUploadControl.FileName); FileUploadControl.SaveAs(Server.MapPath("~/") + filename); StatusLabel.Text = "Upload status: File uploaded!"; } catch(Exception ex) { StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message; } } } i want to cahnge upload file name...i have to assign file name for every uploaded file how?

    Read the article

  • Passing arguments to a C program

    - by Radhika
    Hi All, I was writing a C program where I use 6 variables a,b,c,d,e,f a,b,c are constant values which I should pass as an argument(command line) d,e,f are going to be size of arrays(which are a part of a structure) typedef struct { blah blah } ex; ex ex0[d]; I am very confused about how to pass all these as argument. Right now I have hard coded these values,which apparently I should not be doing.

    Read the article

  • Probelm with String.split() in java

    - by Matt
    What I am trying to do is read a .java file, and pick out all of the identifiers and store them in a list. My problem is with the .split() method. If you run this code the way it is, you will get ArrayOutOfBounds, but if you change the delimiter from "." to anything else, the code works. But I need to lines parsed by "." so is there another way I could accomplish this? import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.*; public class MyHash { private static String[] reserved = new String[100]; private static List list = new LinkedList(); private static List list2 = new LinkedList(); public static void main (String args[]){ Hashtable hashtable = new Hashtable(997); makeReserved(); readFile(); String line; ListIterator itr = list.listIterator(); int listIndex = 0; while (listIndex < list.size()) { if (itr.hasNext()){ line = itr.next().toString(); //PROBLEM IS HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! String[] words = line.split("."); //CHANGE THIS AND IT WILL WORK System.out.println(words[0]); //TESTING TO SEE IF IT WORKED } listIndex++; } } public static void readFile() { String text; String[] words; BufferedReader in = null; try { in = new BufferedReader(new FileReader("MyHash.java")); //NAME OF INPUT FILE } catch (FileNotFoundException ex) { Logger.getLogger(MyHash.class.getName()).log(Level.SEVERE, null, ex); } try { while ((text = in.readLine()) != null){ text = text.trim(); words = text.split("\\s+"); for (int i = 0; i < words.length; i++){ list.add(words[i]); } for (int j = 0; j < reserved.length; j++){ if (list.contains(reserved[j])){ list.remove(reserved[j]); } } } } catch (IOException ex) { Logger.getLogger(MyHash.class.getName()).log(Level.SEVERE, null, ex); } try { in.close(); } catch (IOException ex) { Logger.getLogger(MyHash.class.getName()).log(Level.SEVERE, null, ex); } } public static int keyIt (int x) { int key = x % 997; return key; } public static int horner (String word){ int length = word.length(); char[] letters = new char[length]; for (int i = 0; i < length; i++){ letters[i]=word.charAt(i); } char[] alphabet = new char[26]; String abc = "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < 26; i++){ alphabet[i]=abc.charAt(i); } int[] numbers = new int[length]; int place = 0; for (int i = 0; i < length; i++){ for (int j = 0; j < 26; j++){ if (alphabet[j]==letters[i]){ numbers[place]=j+1; place++; } } } int hornered = numbers[0] * 32; for (int i = 1; i < numbers.length; i++){ hornered += numbers[i]; if (i == numbers.length -1){ return hornered; } hornered = hornered % 997; hornered *= 32; } return hornered; } public static String[] makeReserved (){ reserved[0] = "abstract"; reserved[1] = "assert"; reserved[2] = "boolean"; reserved[3] = "break"; reserved[4] = "byte"; reserved[5] = "case"; reserved[6] = "catch"; reserved[7] = "char"; reserved[8] = "class"; reserved[9] = "const"; reserved[10] = "continue"; reserved[11] = "default"; reserved[12] = "do"; reserved[13] = "double"; reserved[14] = "else"; reserved[15] = "enum"; reserved[16] = "extends"; reserved[17] = "false"; reserved[18] = "final"; reserved[19] = "finally"; reserved[20] = "float"; reserved[21] = "for"; reserved[22] = "goto"; reserved[23] = "if"; reserved[24] = "implements"; reserved[25] = "import"; reserved[26] = "instanceof"; reserved[27] = "int"; reserved[28] = "interface"; reserved[29] = "long"; reserved[30] = "native"; reserved[31] = "new"; reserved[32] = "null"; reserved[33] = "package"; reserved[34] = "private"; reserved[35] = "protected"; reserved[36] = "public"; reserved[37] = "return"; reserved[38] = "short"; reserved[39] = "static"; reserved[40] = "strictfp"; reserved[41] = "super"; reserved[42] = "switch"; reserved[43] = "synchronize"; reserved[44] = "this"; reserved[45] = "throw"; reserved[46] = "throws"; reserved[47] = "trasient"; reserved[48] = "true"; reserved[49] = "try"; reserved[50] = "void"; reserved[51] = "volatile"; reserved[52] = "while"; reserved[53] = "="; reserved[54] = "=="; reserved[55] = "!="; reserved[56] = "+"; reserved[57] = "-"; reserved[58] = "*"; reserved[59] = "/"; reserved[60] = "{"; reserved[61] = "}"; return reserved; } }

    Read the article

  • How to encrypt and save a binary stream after serialization and read it back?

    - by Anindya Chatterjee
    I am having some problems in using CryptoStream when I want to encrypt a binary stream after binary serialization and save it to a file. I am getting the following exception System.ArgumentException : Stream was not readable. Can anybody please show me how to encrypt a binary stream and save it to a file and deserialize it back correctly? The code is as follows: class Program { public static void Main(string[] args) { var b = new B {Name = "BB"}; WriteFile<B>(@"C:\test.bin", b, true); var bb = ReadFile<B>(@"C:\test.bin", true); Console.WriteLine(b.Name == bb.Name); Console.ReadLine(); } public static T ReadFile<T>(string file, bool decrypt) { T bObj = default(T); var _binaryFormatter = new BinaryFormatter(); Stream buffer = null; using (var stream = new FileStream(file, FileMode.OpenOrCreate)) { if(decrypt) { const string strEncrypt = "*#4$%^.++q~!cfr0(_!#$@$!&#&#*&@(7cy9rn8r265&$@&*E^184t44tq2cr9o3r6329"; byte[] dv = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF}; CryptoStream cs; DESCryptoServiceProvider des = null; var byKey = Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8)); using (des = new DESCryptoServiceProvider()) { cs = new CryptoStream(stream, des.CreateEncryptor(byKey, dv), CryptoStreamMode.Read); } buffer = cs; } else buffer = stream; try { bObj = (T) _binaryFormatter.Deserialize(buffer); } catch(SerializationException ex) { Console.WriteLine(ex.Message); } } return bObj; } public static void WriteFile<T>(string file, T bObj, bool encrypt) { var _binaryFormatter = new BinaryFormatter(); Stream buffer; using (var stream = new FileStream(file, FileMode.Create)) { try { if(encrypt) { const string strEncrypt = "*#4$%^.++q~!cfr0(_!#$@$!&#&#*&@(7cy9rn8r265&$@&*E^184t44tq2cr9o3r6329"; byte[] dv = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF}; CryptoStream cs; DESCryptoServiceProvider des = null; var byKey = Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8)); using (des = new DESCryptoServiceProvider()) { cs = new CryptoStream(stream, des.CreateEncryptor(byKey, dv), CryptoStreamMode.Write); buffer = cs; } } else buffer = stream; _binaryFormatter.Serialize(buffer, bObj); buffer.Flush(); } catch(SerializationException ex) { Console.WriteLine(ex.Message); } } } } [Serializable] public class B { public string Name {get; set;} } It throws the serialization exception as follows The input stream is not a valid binary format. The starting contents (in bytes) are: 3F-17-2E-20-80-56-A3-2A-46-63-22-C4-49-56-22-B4-DA ...

    Read the article

  • Return in catch block?

    - by lowlyintern
    Is is wrong to have a return statement in a catch block? What are the alternatives? i.e: public bool SomeFunction() { try { //somecode return true; } catch(Exception ex) { MessageBox.Show(ex.message); return false; } }

    Read the article

  • Problem while adding a new value to a hashtable when it is enumerated

    - by karthik
    `hi I am doing a simple synchronous socket programming,in which i employed twothreads one for accepting the client and put the socket object into a collection,other thread will loop through the collection and send message to each client through the socket object. the problem is 1.i connect to clients to the server and start send messages 2.now i want to connect a new client,while doing this i cant update the collection and add a new client to my hashtable.it raises an exception "collection modified .Enumeration operation may not execute" how to add a NEW value without having problems in a hashtable. private void Listen() { try { //lblStatus.Text = "Server Started Listening"; while (true) { Socket ReceiveSock = ServerSock.Accept(); //keys.Clear(); ConnectedClients = new ListViewItem(); ConnectedClients.Text = ReceiveSock.RemoteEndPoint.ToString(); ConnectedClients.SubItems.Add("Connected"); ConnectedList.Items.Add(ConnectedClients); ClientTable.Add(ReceiveSock.RemoteEndPoint.ToString(), ReceiveSock); //foreach (System.Collections.DictionaryEntry de in ClientTable) //{ // keys.Add(de.Key.ToString()); //} //ClientTab.Add( //keys.Add( } //lblStatus.Text = "Client Connected Successfully."; } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btn_receive_Click(object sender, EventArgs e) { Thread receiveThread = new Thread(new ThreadStart(Receive)); receiveThread.IsBackground = true; receiveThread.Start(); } private void Receive() { while (true) { //lblMsg.Text = ""; byte[] Byt = new byte[2048]; //ReceiveSock.Receive(Byt); lblMsg.Text = Encoding.ASCII.GetString(Byt); } } private void btn_Send_Click(object sender, EventArgs e) { Thread SendThread = new Thread(new ThreadStart(SendMsg)); SendThread.IsBackground = true; SendThread.Start(); } private void btnlist_Click(object sender, EventArgs e) { //Thread ListThread = new Thread(new ThreadStart(Configure)); //ListThread.IsBackground = true; //ListThread.Start(); } private void SendMsg() { while (true) { try { foreach (object SockObj in ClientTable.Keys) { byte[] Tosend = new byte[2048]; Socket s = (Socket)ClientTable[SockObj]; Tosend = Encoding.ASCII.GetBytes("FirstValue&" + GenerateRandom.Next(6, 10).ToString()); s.Send(Tosend); //ReceiveSock.Send(Tosend); Thread.Sleep(300); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } }

    Read the article

  • SQLAlchemy: a better way for update with declarative?

    - by hadrien
    I am a SQLAlchemy noob. Let's say I have an user table in declarative mode: class User(Base): __tablename__ = 'user' id = Column(u'id', Integer(), primary_key=True) name = Column(u'name', String(50)) When I know user's id without object loaded into session, I update such user like this: ex = update(User.__table__).where(User.id==123).values(name=u"Bob Marley") Session.execute(ex) I dislike using User.__table__, should I stop worrying with that? Is there a better way to do this? Thanx!

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >