Search Results

Search found 1250 results on 50 pages for 'san'.

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

  • Updating CoreData xcdatamodel file troubles - attribute type change

    - by San
    I noticed several questions related to this topic go unanswered. Is this such a gray area that nobody really understands it? Here is my problem: I am a midway in the development of my app and the app has never been used ouside of my iphone simulator.One of the attributes in my core data structure requires a type change.Since my app has never been used outside of my iPhone Simulator, I first deleted the sqlite file. Doubling the effort of this step, I also went into iPhone Simulator menu and selected "Reset Content and Settings...". Than, I edited the xcdatamodel file and changed the type of my attribute. I saved the file and exited. Without any other changes, I compiled. I expected it to fail because of my type change. It did not! After this, I assigned a value with new type to my attribute and it fails to compile?! Is there something else that I need to do for the change to take an effect? I would really, really appreciate an answer to my question. Thank you!

    Read the article

  • How to use mock and verify methods of OCMock in objective-C ? Is there any good tutorial on OCMock i

    - by san
    My problem is I am getting an error: OCMckObject[NSNumberFormatter]: expected method was not invoked:setAllowsFloats:YES I have written following Code: (void) testReturnStringFromNumber { id mockFormatter = [OCMockObject mockForClass:[NSNumberFormatter class]]; StringNumber *testObject = [[StringNumber alloc] init]; [[mockFormatter expect] setAllowsFloats:YES]; [testObject returnStringFromNumber:80.23456]; [mockFormatter verify]; } @implementation StringNumber - (NSString *) returnStringFromNumber:(float)num { NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; [formatter setAllowsFloats:YES]; NSString *str= [formatter stringFromNumber:[NSNumber numberWithFloat:num]]; [formatter release]; return str; } @end

    Read the article

  • Many-to-Many Relationship mapping does not trigger the EventListener OnPostInsert or OnPostDelete Ev

    - by san
    I'm doing my auditing using the Events listeners that nHibernate provides. It works fine for all mappings apart from HasmanyToMany mapping. My Mappings are as such: Table("Order"); Id(x => x.Id, "OrderId"); Map(x => x.Name, "OrderName").Length(150).Not.Nullable(); Map(x => x.Description, "OrderDescription").Length(800).Not.Nullable(); Map(x => x.CreatedOn).Not.Nullable(); Map(x => x.CreatedBy).Length(70).Not.Nullable(); Map(x => x.UpdatedOn).Not.Nullable(); Map(x => x.UpdatedBy).Length(70).Not.Nullable(); HasManyToMany(x => x.Products) .Table("OrderProduct") .ParentKeyColumn("OrderId") .ChildKeyColumn("ProductId") .Cascade.None() .Inverse() .AsSet(); Table("Product"); Id(x => x.Id, "ProductId"); Map(x => x.ProductName).Length(150).Not.Nullable(); Map(x => x.ProductnDescription).Length(800).Not.Nullable(); Map(x => x.Amount).Not.Nullable(); Map(x => x.CreatedOn).Not.Nullable(); ; Map(x => x.CreatedBy).Length(70).Not.Nullable(); Map(x => x.UpdatedOn).Not.Nullable(); Map(x => x.UpdatedBy).Length(70).Not.Nullable(); HasManyToMany(x => x.Orders) .Table("OrderProduct") .ParentKeyColumn("ProductId") .ChildKeyColumn("OrderId") .Cascade.None() .AsSet(); Whenever I do an update of an order (Eg: Changed the Orderdescription and deleted one of the products associated with it) It works fine as in it updated the order table and deletes the row in the orderproduct table. the event listener that I have associated with it captures the update of the order table but does NOT capture the associated delete event when the orderproduct is deleted. This behaviour is observed only in case of a ManyTomany mapped relationships. Since I would also like audit the packageproduct deletion, its kind of an annoyance when the event listener aren't able to capture the delete event. Any information about it would be greatly appreciated.

    Read the article

  • Is it possible for parent window to notice if child window has been closed ???

    - by masato-san
    I have parent window (opener) and child (popup) ---------- -------------- | | | | | parent | -----> opens popup | child | | | | | ----------- -------------- Let's say, in parent page, I have js function hello() In order for child to call parent's hello() when the child window is closed and also pass an argument, I can do, window.close(); window.opener.hello(someArgument); This will close the window and also call parent's hello(); But what if I don't want to have the code window.opener.hello() in child page? I mean I want the code to be in parent page only One thing I can think of is: Somewhat parent knows when the child is closed (event listenr??? not sure in js) But in such case how to receive the argument? (i.e. some data back from the child)

    Read the article

  • QT: I've inherited from QTreeView. I've inherited from QStandardItem. How do i Style the items?

    - by San Jacinto
    My Google skills must be failing me today. I've inherited from QTreeView to create a TreeView that stores a QStandardItemModel instead of a QAbstractItemModel. I have also inherited from QStandardItem to create a class to store my data in an item as is necessary. I've successfully inserted my derived QStandardItem into my derived QTreeView's QStandardItemModel. Now the trouble is, I can't figure out how to style it. I know that QTreeView has a setStyleSheet(QString) member, but I can't seem to get it working. It may be as simple as I'm not styling the correct attribute. Any pointers would be appreciated. Thanks. For clarity, here are my class defs. class SurveyTreeItem : public QStandardItem { public: SurveyTreeItem(); SurveyTreeItem( const QString & text ); ~SurveyTreeItem(); }; class StandardItemModelTreeView : public QTreeView { public: StandardItemModelTreeView(QWidget* parent = 0); ~StandardItemModelTreeView(); QStandardItemModel* getStandardItemModel(); }; I've tried the following StyleSheets: StandardTreeView::Item { font: 87 12pt 'Arial Black'; } StandardTreeView::QStandardItem { font: 87 12pt 'Arial Black'; } QTreeView::QStandardItem { font: 87 12pt 'Arial Black'; } QTreeView::Item { font: 87 12pt 'Arial Black'; } QTreeView::SurveyTreeItem { font: 87 12pt 'Arial Black'; } StandardTreeView::SurveyTreeItem { font: 87 12pt 'Arial Black'; }

    Read the article

  • How do I add a header with data to a QTableWidget in Qt?

    - by San Jacinto
    Hi, I'm still learning Qt and I am indebted to the SO community for providing me with great, very timely answers to my Qt questions. Thank you. I'm quite confused on the idea of adding a header to a QTableWidget. What I'd like to do is have a table that contains information about team members. Each row for a member should contain his first and last name, each in its own cell, an email address in one cell, and office in the other cell. I'd to have a header above these columns to name them as appropriate. I'm trying to start off easy and get just the header to display "Last" (as in last name). Here is my code. int column = m_ui-teamTableWidget-columnCount(); m_ui-teamTableWidget-setColumnCount(column+1); QString* qq = new QString("Last"); m_ui-teamTableWidget-horizontalHeader()-model()-setHeaderData(0, Qt::Horizontal, QVariant(QVariant::String, &qq)); My table gets rendered corretly, but the header doesn't contain what I would expect. It contains 1 cell that contains the text "1". I am obviously doing something very silly here that is wrong, but i am lost. I keep pouring over the documentation, finding nothing. Here are the documentation links to the function calls I am making for the very last line. http://doc.trolltech.com/4.5/qtableview.html#horizontalHeader http://doc.trolltech.com/4.5/qabstractitemview.html#model http://doc.trolltech.com/4.5/qabstractitemmodel.html#setHeaderData Thanks for any and all help. Edit: HOW I SOLVED THE PROBLEM Using some help from the accepted answer, I came up with the following code: m_ui-teamTableWidget-setColumnCount(m_ui-teamTableWidget-columnCount()+1); QTableWidgetItem* qtwi = new QTableWidgetItem(QString("Last"),QTableWidgetItem::Type); m_ui-teamTableWidget-setHorizontalHeaderItem(0,qtwi);

    Read the article

  • JPA optimistic lock - setting @Version to entity class cause query to include VERSION as column

    - by masato-san
    I'm using JPA Toplink Essential, Netbean6.8, GlassFish v3 In my Entity class I added @Version annotation to enable optimistic locking at transaction commit however after I added the annotation, my query started including VERSION as column thus throwing SQL exception. None of this is mentioned in any tutorial I've seen so far. What could be wrong? Snippet public class MasatosanTest2 implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "id") private Integer id; @Column(name = "username") private String username; @Column(name = "note") private String note; //here adding Version @Version int version; query used: SELECT m FROM MasatosanTest2 m Internal Exception: com.microsoft.sqlserver.jdbc.SQLServerException Call: SELECT id, username, note, VERSION FROM MasatosanTest2

    Read the article

  • How to Canonicalize a Stax XML object.

    - by Enrique San Martín
    Hello, i want to Canonicalize a Stax object, the program it's doing it with DOM, but dom can't manage big XML documents (like 1GB), so STAX it's the solution. The Code that i have it's: File file=new File("big-1gb.xml"); org.apache.xml.security.Init.init(); DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = dfactory.newDocumentBuilder(); Document doc = documentBuilder.parse(file); Canonicalizer c14n = Canonicalizer.getInstance("http://www.w3.org/TR/2001/REC-xml-c14n-20010315"); outputBytes = c14n.canonicalizeSubtree(doc.getElementsByTagName("SomeTag").item(0)); The idea it's do the code below with Stax... Thx :)

    Read the article

  • ora-00939 error in reporting services, SSRS

    - by san
    Hi, I have an SSRS report , Oracle is my backend and am using this following query for dataset of my second parameter. select distinct X from v_stf_sec_user_staffing_center usc where usc.center_group_id in ( select distinct center_group_id from V_T_STAFFING_CENTER_GROUP scg where INSTR(','||REPLACE(:PI_REGION_LIST,' ')||',', ','||scg.group_abbreviation||',') 0) and usc.nt_user_name=:PI_NT_USER_NAME Here PI_REGION_LIST is a multivalued parameter of string type. and PI_NT_USER_NAME is a default string valued parameter this query works fine when i try to execute in manulally in the Data tab , also in the Oracle tool. But when i run the report in SSRS and select more than 3 values for the parameter PI_REGION_LIST the report throws an error on this dataset, ora-00939 error,too many arguments for function. I am not able to figure out the error here. Please help me with an idea. Thanks in advance, Suni.

    Read the article

  • JPA native query join returns object but dereference throws class cast exception

    - by masato-san
    I'm using JPQL Native query to join table and query result is stored in List<Object[]>. public String getJoinJpqlNativeQuery() { String final SQL_JOIN = "SELECT v1.bitbit, v1.numnum, v1.someTime, t1.username, t1.anotherNum FROM MasatosanTest t1 JOIN MasatoView v1 ON v1.username = t1.username;" System.out.println("get join jpql native query is being called ============================"); EntityManager em = null; List<Object[]> out = null; try { em = EmProvider.getDefaultManager(); Query query = em.createNativeQuery(SQL_JOIN); out = query.getResultList(); System.out.println("return object ==========>" + out); System.out.println(out.get(0)); String one = out.get(0).toString(); //LINE 77 where ClassCastException System.out.println(one); } catch(Exception e) { } finally { if(em != null) { em.close; } } } The problem is System.out.println("return object ==========>" + out); outputs: return object ==========> [[true, 0, 2010-12-21 15:32:53.0, masatosan, 0.020], [false, 0, 2010-12-21 15:32:53.0, koga, 0.213]] System.out.println(out.get(0)) outputs: [true, 0, 2010-12-21 15:32:53.0, masatosan, 0.020] So I assumed that I can assign return value of out.get(0) which should be String: String one = out.get(0).toString(); But I get weird ClassCastException. java.lang.ClassCastException: java.util.Vector cannot be cast to [Ljava.lang.Object; at local.test.jaxrs.MasatosanTestResource.getJoinJpqlNativeQuery (MasatosanTestResource.java:77) So what's really going on? Even Object[] foo = out.get(0); would throw an ClassCastException :(

    Read the article

  • How to set response header in JAX-RS so that user sees download popup for Excel?

    - by masato-san
    I wrote code that generate Excel file using REST JAX-RS and I confirmed that the generated Excel file is in GlassFish server directory. But my goal is when user click on the button (which generate Excel .xls), I want download popup to show up asking user whether to save or open the .xls file just like any other web services doing for downloading any type of files. According to my search, the step is: generate Excel .xls (DONE) write the excel to stream in JAX-RS file, set response header to something like, String fileName = "Blah_Report.xls"; response.setHeader("Content-Disposition", "attachment; filename=" + fileName); My question is I'm doing all of this in JAX-RS file and I don't have HttpServletResponse object available. According to the answer from Add Response Header to JAX-RS Webservice He says: You can inject a reference to the actual HttpServletResponse via the @Context annotation in your webservice and use addHeader() etc. to add your header. I can't really figure what exactly that means without sample code..

    Read the article

  • java: how to convert a file to utf8

    - by Enrique San Martín
    Hi, i have a file that have some non-utf8 caracters (like "ISO-8859-1"), and so i want to convert that file (or read) to UTF8 encoding, how i can do it? The code it's like this: File file = new File("some_file_with_non_utf8_characters.txt"); /* some code to convert the file to an utf8 file */ ... edit: Put an encoding example

    Read the article

  • How to change quicksort to output elements in descending order?

    - by masato-san
    Hi, I wrote a quicksort algorithm however, I would like to make a change somewhere so that this quicksort would output elements in descending order. I searched and found that I can change the comparison operator (<) in partition() to other way around (like below). //This is snippet from partition() function while($array[$l] < $pivot) { $l++; } while($array[$r] > $pivot) { $r--; } But it is not working.. If I quicksort the array below, $array = (3,9,5,7); should be: $array = (9,7,5,3) But actual output is: $array = (3,5,7,9) Below is my quicksort which trying to output elements in descending order. How should I make change to sort in descending order? If you need any clarification please let me know. Thanks! $array = (3,9,5,7); $app = new QuicksortDescending(); $app->quicksort($array, 0, count($array)); print_r($array); class QuicksortDescending { public function partitionDesc(&$array, $left, $right) { $l = $left; $r = $right; $pivot = $array[($right+$left)/2]; while($l <= $r) { while($array[$l] > $pivot) { $l++; } while($array[$r] < $pivot) { $r--; } if($l <= $r) {// if L and R haven't cross $this->swap($array, $l, $r); $l ++; $j --; } } return $l; } public function quicksortDesc(&$array, $left, $right) { $index = $this->partition($array, $left, $right); if($left < $index-1) { //if there is more than 1 element to sort on right subarray $this->quicksortDesc($array, $left, $index-1); } if($index < $right) { //if there is more than 1 element to sort on right subarray $this->quicksortDesc($array, $index, $right); } } }

    Read the article

  • Why download popup window in browser not showing up when using JAX-RS v.s. standard servlet?

    - by masato-san
    When I try using standard servlet approach, in my browser the popup window shows up asking me whether to open .xls file or save it. I tried the exactly same code via JAX-RS and the browser popup won't show up somehow. Has anyone encounter this mystery? Standard servlet that works: package local.test.servlet; import java.io.IOException; import java.net.URL; import java.net.URLDecoder; 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 local.test.jaxrs.ExcellaTestResource; import org.apache.poi.ss.usermodel.Workbook; import org.bbreak.excella.core.BookData; import org.bbreak.excella.core.exception.ExportException; import org.bbreak.excella.reports.exporter.ExcelExporter; import org.bbreak.excella.reports.exporter.ReportBookExporter; import org.bbreak.excella.reports.model.ConvertConfiguration; import org.bbreak.excella.reports.model.ReportBook; import org.bbreak.excella.reports.model.ReportSheet; import org.bbreak.excella.reports.processor.ReportProcessor; @WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"}) public class ExcelServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { //C:\Users\m-takayashiki\.netbeans\6.9\config\GF3\domain1 // ================== ?????? ======================= URL templateFileUrl = ExcellaTestResource.class.getResource("?????????.xls"); // /C:/Users/m-takayashiki/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/?????????.xls System.out.println(templateFileUrl.getPath()); String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8"); String outputFileDir = "MasatoExcelHorizontalOutput"; ReportProcessor reportProcessor = new ReportProcessor(); ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE); ReportSheet outputSheet = new ReportSheet("??????"); outputBook.addReportSheet(outputSheet); // ======================================================== // --------------- ?????? ------------------------- reportProcessor.addReportBookExporter(new OutputStreamExporter(response)); System.out.println("wtf???"); reportProcessor.process(outputBook); System.out.println("done!!"); } catch(Exception e) { System.out.println(e); } } //end doGet() @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }//end class class OutputStreamExporter extends ReportBookExporter { private HttpServletResponse response; public OutputStreamExporter(HttpServletResponse response) { this.response = response; } @Override public String getExtention() { return null; } @Override public String getFormatType() { return ExcelExporter.FORMAT_TYPE; } @Override public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException { System.out.println(book.getFirstVisibleTab()); System.out.println(book.getSheetName(0)); //TODO write to stream try { response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls"); book.write(response.getOutputStream()); response.getOutputStream().close(); System.out.println("booya!!"); } catch(Exception e) { System.out.println(e); } } }//end class JAX-RS way that won't display popup: package local.test.jaxrs; import java.net.URL; import java.net.URLDecoder; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.Path; import javax.ws.rs.GET; import javax.ws.rs.Produces; import org.apache.poi.ss.usermodel.Workbook; import org.bbreak.excella.core.BookData; import org.bbreak.excella.core.exception.ExportException; import org.bbreak.excella.reports.exporter.ExcelExporter; import org.bbreak.excella.reports.exporter.ReportBookExporter; import org.bbreak.excella.reports.model.ConvertConfiguration; import org.bbreak.excella.reports.model.ReportBook; import org.bbreak.excella.reports.model.ReportSheet; import org.bbreak.excella.reports.processor.ReportProcessor; @Path("excellaTest") public class ExcellaTestResource { @Context private UriInfo context; @Context private HttpServletResponse response; @Context private HttpServletRequest request; public ExcellaTestResource() { } @Path("horizontalProcess") @GET //@Produces("application/vnd.ms-excel") @Produces("application/vnd.ms-excel") public void getProcessHorizontally() { try { //C:\Users\m-takayashiki\.netbeans\6.9\config\GF3\domain1 // ================== ?????? ======================= URL templateFileUrl = this.getClass().getResource("?????????.xls"); // /C:/Users/m-takayashiki/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/?????????.xls System.out.println(templateFileUrl.getPath()); String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8"); String outputFileDir = "MasatoExcelHorizontalOutput"; ReportProcessor reportProcessor = new ReportProcessor(); ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE); ReportSheet outputSheet = new ReportSheet("??????"); outputBook.addReportSheet(outputSheet); // ======================================================== // --------------- ?????? ------------------------- reportProcessor.addReportBookExporter(new OutputStreamExporter(response)); System.out.println("wtf???"); reportProcessor.process(outputBook); System.out.println("done!!"); } catch(Exception e) { System.out.println(e); } //return response; return; } }//end class class OutputStreamExporter extends ReportBookExporter { private HttpServletResponse response; public OutputStreamExporter(HttpServletResponse response) { this.response = response; } @Override public String getExtention() { return null; } @Override public String getFormatType() { return ExcelExporter.FORMAT_TYPE; } @Override public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException { //TODO write to stream try { response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls"); book.write(response.getOutputStream()); response.getOutputStream().close(); System.out.println("booya!!"); } catch(Exception e) { System.out.println(e); } } }//end class

    Read the article

  • JAX-RS --- How to return JSON and HTTP Status code together?

    - by masato-san
    I'm writing REST web app (Netbean6.9, JAX-RS, Toplink-essential) and trying to return JSON and Http status code. I have code ready and working just to return JSON when HTTP GET Method is called from client. Code snippet @Path("get/id") @GET @Produces("application/json") public M_?? getMachineToUpdate(@PathParam("id") String id) { //some code to return JSON . . return myJson But I also want to return HTTP status code (500, 200, 204 etc) along with returning JSON. I tried using HttpServletResponse object, response.sendError("error message", 500); But this made browser to think it's real 500 so output web page was regular Http 500 error page. What I want to is just to return status code so that my Javascript on client side can handle some logic depending on what HTTP status code is returned. (maybe just to display the error code and message on html page.) Is it possible to do so? or should HTTP status code not be used for such thing?

    Read the article

  • How to remove characters from a string?

    - by masato-san
    Hi, Below is interview question so you cannot relay on the functions that predefined in libraries. Also my answer below set the element to null but there is another ways to solve the problem. Given string $string = "This is a pen", remove "is" so that return value is "Th a pen" (including whitespece). I've tried (shown below) but returned value is not correct. Thanks in advance! function remove_delimiter_from_string(&$string, $del) { for($i=0; $i<strlen($string); $i++) { for($j=0; $j<strlen($del); $j++) { if($string[$i] == $del[$j]) { $string[$i] = $string[$i+$j]; //this grabs delimiter :( } } } echo $string . "\n"; }

    Read the article

  • How to handle array element between int and Integer

    - by masato-san
    First, it is long post so if you need clarification please let me know. I'm new to Java and having difficulty deciding whether I should use int[] or Integer[]. I wrote a function that find odd_number from int[] array. public int[] find_odd(int[] arr) { int[] result = new int[arr.length]; for(int i=0; i<arr.length; i++) { if(arr[i] % 2 != 0) { //System.out.println(arr[i]); result[i] = arr[i]; } } return result; } Then, when I pass the int[] array consisting of some integer like below: int[] myArray = {-1, 0, 1, 2, 3}; int[] result = find_odd(myArray); The array "result" contains: 0, -1, 0, 1, 0, 3 Because in Java you have to define the size of array first, and empty int[] array element is 0 not null. So when I want to test the find_odd() function and expect the array to have odd numbers (which it does) only, it throws the error because the array also includes 0s representing "empty cell" as shown above. My test code: public void testFindOddPassValidIntArray() { int[] arr = {-2, -1, 0, 1, 3}; int[] result = findOddObj.find_odd(arr); //check if return array only contain odd number for(int i=0; i<result.length; i++) { if(result[i] != null) { assert is_odd(result[i]) : result[i]; } } } So, my question is should I use int[] array and add check for 0 element in my test like: if(result[i] != 0) { assert is_odd(result[i] : result[i] } But in this case, if find_odd() function is broken and returning 0 by miscalculation, I can't catch it because my test code would only assume that 0 is empty cell. OR should I use Integer[] array whose default is null? How do people deal with this kind of situation?

    Read the article

  • When should EntityManagerFactory instance be created/opened ?

    - by masato-san
    Ok, I read bunch of articles/examples how to write Entity Manager Factory in singleton. One of them easiest for me to understand a bit: http://javanotepad.blogspot.com/2007/05/jpa-entitymanagerfactory-in-web.html I learned that EntityManagerFactory (EMF) should only be created once preferably in application scope. And also make sure to close the EMF once it's used (?) So I wrote EMF helper class for business methods to use: public class EmProvider { private static final String DB_PU = "KogaAlphaPU"; public static final boolean DEBUG = true; private static final EmProvider singleton = new EmProvider(); private EntityManagerFactory emf; private EmProvider() {} public static EmProvider getInstance() { return singleton; } public EntityManagerFactory getEntityManagerFactory() { if(emf == null) { emf = Persistence.createEntityManagerFactory(DB_PU); } if(DEBUG) { System.out.println("factory created on: " + new Date()); } return emf; } public void closeEmf() { if(emf.isOpen() || emf != null) { emf.close(); } emf = null; if(DEBUG) { System.out.println("EMF closed at: " + new Date()); } } }//end class And my method using EmProvider: public String foo() { EntityManager em = null; List<Object[]> out = null; try { em = EmProvider.getInstance().getEntityManagerFactory().createEntityManager(); Query query = em.createNativeQuery(JPQL_JOIN); //just some random query out = query.getResultList(); } catch(Exception e) { //handle error.... } finally { if(em != null) { em.close(); //make sure to close EntityManager } } I made sure to close EntityManager (em) within method level as suggested. But when should EntityManagerFactory be closed then? And why EMF has to be singleton so bad??? I read about concurrency issues but as I am not experienced multi-thread-grammer, I can't really be clear on this idea.

    Read the article

  • Linux termios VTIME not working?

    - by San Jacinto
    We've been bashing our heads off of this one all morning. We've got some serial lines setup between an embedded linux device and an Ubuntu box. Our reads are getting screwed up because our code usually returns two (sometimes more, sometimes exactly one) message reads instead of one message read per actual message sent. Here is the code that opens the serial port. InterCharTime is set to 4. void COMBaseClass::OpenPort() { cerr<< "openning port"<< port <<"\n"; struct termios newtio; this->fd = -1; int fdTemp; fdTemp = open( port, O_RDWR | O_NOCTTY); if (fdTemp < 0) { portOpen = 0; cerr<<"problem openning "<< port <<". Retrying"<<endl; usleep(1000000); return; } newtio.c_cflag = BaudRate | CS8 | CLOCAL | CREAD ;//| StopBits; newtio.c_iflag = IGNPAR; newtio.c_oflag = 0; /* set input mode (non-canonical, no echo,...) */ newtio.c_lflag = 0; newtio.c_cc[VTIME] = InterCharTime; /* inter-character timer in .1 secs */ newtio.c_cc[VMIN] = readBufferSize; /* blocking read until 1 char received */ tcflush(fdTemp, TCIFLUSH); tcsetattr(fdTemp,TCSANOW,&newtio); this->fd = fdTemp; portOpen = 1; } The other end is configured similarly for communication, and has one small section of particular iterest: while (1) { sprintf(out, "\r\nHello world %lu", ++ulCount); puts(out); WritePort((BYTE *)out, strlen(out)+1); sleep(2); } //while Now, when I run a read thread on the receiving machine, "hello world" is usually broken up over a couple messages. Here is some sample output: 1: Hello 2: world 1 3: Hello 4: world 2 5: Hello 6: world 3 where number followed by a colon is one message recieved. Can you see any error we are making? Thank you. Edit: For clarity, please view section 3.2 of this resource href="http://www.faqs.org/docs/Linux-HOWTO/Serial-Programming-HOWTO.html. To my understanding, with a VTIME of a couple seconds (meaning vtime is set anywhere between 10 and 50, trial-and-error), and a VMIN of 1, there should be no reason that the message is broken up over two separate messages.

    Read the article

  • Function template accepting nothing less than a bidirectional iterator or a pointer

    - by san
    I need a function template that accepts two iterators that could be pointers. If the two arguments are random_access iterators I want the return type to be an object of std::iterator<random_access_iterator_tag, ...> type else a std::iterator<bidirectional_iterator_tag, ...> type. I also want the code to refuse compilation if the arguments are neither a bidirectional iterator, nor a pointer. I cannot have dependency on third party libraries e.g. Boost Could you help me with the signature of this function so that it accepts bidirectional iterators as well as pointers, but not say input_iterator, output_iterator, forward_iterators. One partial solution I can think of is the following template<class T> T foo( T iter1, T iter2) { const T tmp1 = reverse_iterator<T>(iter1); const T tmp2 = reverse_iterator<T>(iter2); // do something } The idea is that if it is not bidirectional the compiler will not let me construct a reverse_iterator from it.

    Read the article

  • How to find sum of node's value for given depth in binary tree?

    - by masato-san
    I've been scratching my head for several hours for this... problem: Binary Tree (0) depth 0 / \ 10 20 depth 1 / \ / \ 30 40 50 60 depth 2 I am trying to write a function that takes depth as argument and return the sum of values of nodes of the given depth. For instance, if I pass 2, it should return 180 (i.e. 30+40+50+60) I decided to use breath first search and when I find the node with desired depth, sum up the value, but I just can't figure out how to find out the way which node is in what depth. But with this approach I feel like going to totally wrong direction. function level_order($root, $targetDepth) { $q = new Queue(); $q->enqueue($root); while(!$q->isEmpty) { //how to determin the depth of the node??? $node = $q->dequeue(); if($currentDepth == $targetDepth) { $sum = $node->value; } if($node->left != null) { $q->enqueue($node->left); } if($node->right != null) { $q->enqueue($node->right); } //need to reset this somehow $currentDepth ++; } }

    Read the article

  • Refresh Service List of a paired Bluetooth device !

    - by sas-san
    Hi- Is there any possibility to refresh the service list of a paired device in a programm? At the moment, i have to go to the bluetooth options and select the device properties of the bluetooth device and have to refresh the service list manually. Is there any API that RIMM provides to do programmatically? thanks,

    Read the article

  • PHP the SELECT FROM WHERE col IN no working using array

    - by Sam Ram San
    I'm trying to pull some data from MySQL using an Array that was fetch from a first query. Everything's fine all the way to the implode after that, it's been a headache for me. Can someone help me? <?php $var = 'somedata'; include("config/conect.php"); $zip="SELECT * FROM table WHERE firstcol LIKE '%$var%' ORDER BY seconcol"; $results = $connetction->query($zip); while ($row = $results->fetch_array()){ $mycode[]=$row['zip']; } array_pop($mycode); $mycode = implode(', ',$mycode); //print_r ($mycode); echo '<br /><br /><br />'; $usr="SELECT * FROM reg_temp WHERE zip IN('".join("','", $mycode)."')"; $results = $asies->query($usr); while ($row = $results-> fetch_arra()) { $name = $row['name']; echo $name; } ?>

    Read the article

  • why the global variable value is not being set?

    - by masato-san
    I can't figure out why my global variable workRegionCode is not set properly. In function getWorkRegion(), after getting ajax callback, it attempt to set workRegionCode global variable. (inside of function setFirstIndexWorkRegionCode() ). The alert in setFirstIndexWorkRegionCode() outputs expected value like 401 or 123 etc. But then when getMachines() is called, the global variable workRegionCode is undefiend :( This js starts from window.onload() (please ignore those Japanese JSON key value and few Japanese variables. They are harmless) Code: var workRegionDropdown = document.getElementById("workRegionDropdown");; var machineDropdown = document.getElementById("machineDropdown"); //this is the global variable with problem..... var workRegionCode; //INIT window.onload = function() { getWorkRegions(); // alert("before: " + window.workRegionCode); getMachines(); // alert("after: " + window.workRegionCode); } function addWorkRegionToDropdown(jsonObject, dropdown) { for(var i=0, j=jsonObject.length; i<j; i++) { var option = document.createElement("option"); option.text = jsonObject[i].?????? + ":" + jsonObject[i].??????; option.value = jsonObject[i].??????; dropdown.options.add(option); } } function addMachineToDropdown(jsonObject, dropdown) { for(var i=0, j=jsonObject.length; i<j; i++) { var option = document.createElement("option"); option.text = jsonObject[i].???; option.value = jsonObject[i].???; dropdown.options.add(option); } } function getMachines() { //!!!!!!!!!!! workRegionCode is undefined.. why?!?!?! alert("inside of getMachines() ==> " + window.workRegionCode); var ajaxRequest = new XMLHttpRequest(); ajaxTimeout = setTimeout(function() {timeoutAjax(ajaxRequest, "showMessage")}, "5000"); ajaxRequest.onreadystatechange = function() { if(ajaxRequest.readyState == 4 ) { clearTimeout(ajaxTimeout); switch ( ajaxRequest.status ) { case 200: var jsonOut = JSON.parse(ajaxRequest.responseText); addMachineToDropdown(jsonOut.??, machineDropdown); break; default: document.getElementById("showMessage").innerHTML = ajaxRequest.responseText; } } } var aMonthAgo = new Date(); with(aMonthAgo) { setMonth(getMonth() - 1) } aMonthAgo = aMonthAgo.getYYYYMMDD(); var ??? = "29991231"; var url = "../resources/machine/list/" + window.workRegionCode + "/" + aMonthAgo + "/" + ???; ajaxRequest.open("GET", url, true); ajaxRequest.send(null) } function getWorkRegions() { var ajaxRequest = new XMLHttpRequest(); ajaxTimeout = setTimeout(function() {timeoutAjax(ajaxRequest, "showMessage")}, "5000"); ajaxRequest.onreadystatechange = function() { if(ajaxRequest.readyState == 4 ) { clearTimeout(ajaxTimeout); switch ( ajaxRequest.status ) { case 200: var jsonOut = JSON.parse(ajaxRequest.responseText); //set global variable workRegionCode setFirstIndexWorkRegionCode(jsonOut); addWorkRegionToDropdown(jsonOut.???, workRegionDropdown); default: document.getElementById("showMessage").innerHTML = ajaxRequest.responseText; } } } var url = "../resources/workshop/list"; ajaxRequest.open("GET", url, true); ajaxRequest.send(null) }//end getWorkRegions() function setFirstIndexWorkRegionCode(jsonString) { //here I set the value to work region code! window.workRegionCode = jsonString.???[0].??????; alert("??????: " + window.workRegionCode); }

    Read the article

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