Search Results

Search found 502 results on 21 pages for 'primitive'.

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

  • Can't combine "LINQ Join" with other tables

    - by FullmetalBoy
    The main problem is that I recieve the following message: "base {System.SystemException} = {"Unable to create a constant value of type 'BokButik1.Models.Book-Author'. Only primitive types ('such as Int32, String, and Guid') are supported in this context."}" based on this LinQ code: IBookRepository myIBookRepository = new BookRepository(); var allBooks = myIBookRepository.HamtaAllaBocker(); IBok_ForfattareRepository myIBok_ForfattareRepository = new Bok_ForfattareRepository(); var Book-Authors = myIBok_ForfattareRepository.HamtaAllaBok_ForfattareNummer(); var q = from booknn in allBooks join Book-Authornn in Book-Authors on booknn.BookID equals Book-Authornn.BookID select new { booknn.title, Book-AuthorID }; How shall I solve this problem to get a class instance that contain with property title and Book-AuthorID? // Fullmetalboy I also have tried making some dummy by using "allbooks" relation with Code Samples from the address http://www.hookedonlinq.com/JoinOperator.ashx. Unfortunately, still same problem. I also have taken account to Int32 due to entity framework http://msdn.microsoft.com/en-us/library/bb896317.aspx. Unfortunatley, still same problem. Using database with 3 tables and one of them is a many to many relationship. This database is used in relation with entity framework Book-Author Book-Author (int) BookID (int) Forfattare (int) Book BookID (int) title (string) etc etc etc

    Read the article

  • Using JAXB to customise the generation of java enums

    - by belltower
    I'm using an external bindings file when using jaxb against an XML schema. I'm mostly using the bindings file to map from the XML schema primitives to my own types. This is a snippet of the bindings file <jxb:bindings version="1.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ai="http://java.sun.com/xml/ns/jaxb/xjc" extensionBindingPrefixes="ai"> <jxb:bindings schemaLocation="xsdurl" node="xs:schema"> <jxb:globalBindings> <jxb:javaType name="com.companyname.StringType" xmlType="xs:string" parseMethod="parse" printMethod="print" hasNsContext="true"> </jxb:javaType> </jxb:globalBindings> </jxb:bindings> </jxb:bindings> So whenever a xs:string is encountered, the com.companyname.StringType the methods print / parse are called for marshalling/unmarshalling etc. Now if JAXB encounters an xs:enumeration it will generate a java enum. For example: <xs:simpleType name="Address"> <xs:restriction base="xs:string"> <xs:enumeration value="ADDR"/> <xs:enumeration value="PBOX"/> </xs:restriction> </xs:simpleType> public enum Address { ADDR, PBOX, public String value() { return name(); } public static Address fromValue(String v) { return valueOf(v); } } Does anyone know if it is possible to customise the creation of an enum like it is for a primitive? I would like to be able to: Add a standard member variable / other methods to every enum generated by jaxb. Specify the static method used to create the enum.

    Read the article

  • What is the proper way to use a Logger in a Serializable Java class?

    - by Tim Visher
    I have the following (doctored) class in a system I'm working on and Findbugs is generating a SE_BAD_FIELD warning and I'm trying to understand why it would say that before I fix it in the way that I thought I would. The reason I'm confused is because the description would seem to indicate that I had used no other non-serializable instance fields in the class but bar.model.Foo is also not serializable and used in the exact same way (as far as I can tell) but Findbugs generates no warning for it. import bar.model.Foo; import java.io.File; import java.io.Serializable; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Demo implements Serializable { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final File file; private final List<Foo> originalFoos; private Integer count; private int primitive = 0; public Demo() { for (Foo foo : originalFoos) { this.logger.debug(...); } } ... } My initial blush at a solution is to get a logger reference from the factory right as I use it: public DispositionFile() { Logger logger = LoggerFactory.getLogger(this.getClass()); for (Foo foo : originalFoos) { this.logger.debug(...); } } That doesn't seem particularly efficient, though. Thoughts?

    Read the article

  • Entity Framework and WCf

    - by Nihilist
    Hi I am little confused on designing WCf services with EF. When using WCf and EF, where do we draw this line on what properties to return and what not to with the entity. Here is my scenario I have User. Here are the relations. User [1 to many] Address, User [ 1 to many] Email, User [ 1 to many] Phone So now on the webform, on page1 I can edit user information. say I can edit few properties on the user entity and can also edit address, phone, email entities[ like add / delete and update any] On page2, i can only update user properties and nothing related to navigation properties [ address, email, phone]. So when I return the User Entity [ OR DTO] should i be returning the navigation properties too? Or should the client make multiple calls to get navigation properites. Also, how does it go with Save? Like should the client make multiple calls to save user and related entites or just one call to save the graph? Lets say, if I just have a Save(User user) [ where user has all the related entities too] both page1 and page2 will call save and pass me the user. but one page1 i will need a lot more information. but on page2 i just need the user primitive properties. So my question is, where do we draw this line, how do we design theses services ? Is the WCF operation designed on the page and the fields it has ? I am hoping i explained my problem well enough.

    Read the article

  • C# struct with object as data member

    - by source-energy
    As we know, in C# structs are passed by value, not by reference. So if I have a struct with the following data members: private struct MessageBox { // data members private DateTime dm_DateTimeStamp; // a struct type private TimeSpan dm_TimeSpanInterval; // also a struct private ulong dm_MessageID; // System.Int64 type, struct private String dm_strMessage; // an object (hence a reference is stored here) // more methods, properties, etc ... } So when a MessageBox is passed as a parameter, a COPY is made on the stack, right? What does that mean in terms of how the data members are copied? The first two are struct types, so copies should be made of DateTime and TimeSpan. The third type is a primitive, so it's also copied. But what about the dm_strMessage, which is a reference to an object? When it's copied, another reference to the same String is created, right? The object itself resides in the heap, and is NOT copied (there is only one instance of it on the heap.) So now we have to references to the same object of type String. If the two references are accessed from different threads, it's conceivable that the String object could be corrupted by being modified from two different directions simultaneously. The MSDN documentation says that System.String is thread safe. Does that mean that the String class has a built-in mechanism to prevent an object being corrupted in exactly the type of situation described here? I'm trying to figure out if my MessageBox struct has any potential flaws / pitfalls being a structure vs. a class. Thanks for any input. Source.Energy.

    Read the article

  • MACRO compilation PROBLEM

    - by wildfly
    i was given a primitive task to find out (and to put in cl) how many nums in an array are bigger than the following ones, (meaning if (arr[i] arr[i+1]) count++;) but i've problems as it has to be a macro. i am getting errors from TASM. can someone give me a pointer? SortA macro a, l LOCAL noes irp reg, <si,di,bx> push reg endm xor bx,bx xor si,si rept l-1 ;;also tried rept 3 : wont' compile mov bl,a[si] inc si cmp bl,arr[si] jb noes inc di noes: add di,0 endm mov cx,di irp reg2, <bx,di,si> pop reg2 endm endm dseg segment arr db 10,9,8,7 len = 4 dseg ends sseg segment stack dw 100 dup (?) sseg ends cseg segment assume ds:dseg, ss:sseg, cs:cseg start: mov ax, dseg mov ds,ax sortA arr,len cseg ends end start errors: Assembling file: sorta.asm **Error** sorta.asm(51) REPT(4) Expecting pointer type **Error** sorta.asm(51) REPT(6) Symbol already different kind: NOES **Error** sorta.asm(51) REPT(10) Expecting pointer type **Error** sorta.asm(51) REPT(12) Symbol already different kind: NOES **Error** sorta.asm(51) REPT(16) Expecting pointer type **Error** sorta.asm(51) REPT(18) Symbol already different kind: NOES Error messages: 6

    Read the article

  • C# wrapper for objects

    - by Haggai
    I'm looking for a way to create a generic wrapper for any object. The wrapper object will behave just like the class it wraps, but will be able to have more properties, variable, methods etc., for e.g. object counting, caching etc. Say the wrapper class be called Wrapper, and the class to be wrapped be called Square and has the constructor Square(double edge_len) and the properties/methods EdgeLength and Area, I would like to use it as follows: Wrapper<Square> mySquare = new Wrapper<Square>(2.5); /* or */ new Square(2.5); Console.Write("Edge {0} -> Area {1}", mySquare.EdgeLength, mySquare.Area); Obviously I can create such a wrapper class for each class I want to wrap, but I'm looking for a general solution, i.e. Wrapper<T> which can handle both primitive and compound types (although in my current situation I would be happy with just wrapping my own classes). Suggestions? Thanks.

    Read the article

  • OrderBy Linq.Expression as parameter = (Of Func(Of T,IComparable)) to perform LinqToEntity is not working

    - by NicoJuicy
    I'd like to get this working: Call: (Count & Page are used for pagination, so Count = 20 and Page = 1 for example, for the first 20 values). Sorting should be by name LeverancierService.GetLeveranciers(Function(el) el.Name, Count, Page) Equivalent in c#: LeverancierService.GetLeveranciers(el= el.Name, Count, Page) Method that gives an error (parameters shown above): Public Overridable Function GetAllPaged(orderby As Expression(Of Func(Of T, IComparable)), ByVal Count As Integer, ByVal Page As Integer) As IEnumerable(Of T) Return dbset.OrderBy(orderby).Skip((Page - 1) * Count).Take(Count).ToList() End Function Already tried changing it to this, but it gives the same error: Public Overridable Function GetAllPaged(Of TOrderBy)(orderby As Expression(Of Func(Of T, TOrderBy)), ByVal Count As Integer, ByVal Page As Integer) As IEnumerable(Of T) Return dbset.OrderBy(orderby).Skip((Page - 1) * Count).Take(Count).ToList() End Function Error: Unable to cast the type 'System.String' to type 'System.IComparable'. LINQ to Entities only supports casting Entity Data Model primitive types. Any idea how to do this? Extra info: I'm in a DDD-layered application, so the parameter should stay the same as the called method is an overridden interface (eg. if i change this, i have to do this for 200 times or so, because it's in VB.Net and not in C# (= 1 change) ) I know there is a way to change the expression to a string and then use DLinq (= Dynamic Linq), but that's not how it should be.

    Read the article

  • deleting object with template for int and object

    - by Yokhen
    Alright so Say I have a class with all its definition, bla bla bla... template <class DT> class Foo{ private: DT* _data; //other stuff; public: Foo(DT* data){ _data = data } virtual ~Foo(){ delete _data } //other methods }; And then I have in the main method: int main(){ int number = 12; Foo<anyRandomClass>* noPrimitiveDataObject = new Foo<anyRandomClass>(new anyRandomClass()); Foo<int>* intObject = new Foo<int>(number); delete noPrimitiveDataObject; //Everything goes just fine. delete intObject; //It messes up here, I think because primitive data types such as int are allocated in a different way. return 0; } My question is: What could I do to have both delete statements in the main method work just fine? P.S.: Although I have not actually compiled/tested this specific code, I have reviewed it extensively (as well as indented. You're welcome.), so if you find a mistake, please be nice. Thank you.

    Read the article

  • Avoid an "out of memory error" in Java(eclipse), when using large data structure?

    - by gnomed
    OK, so I am writing a program that unfortunately needs to use a huge data structure to complete its work, but it is failing with a "out of memory error" during its initialization. While I understand entirely what that means and why it is a problem, I am having trouble overcoming it, since my program needs to use this large structure and I don't know any other way to store it. The program first indexes a large corpus of text files that I provide. This works fine. Then it uses this index to initialize a large 2D array. This array will have nXn entries, where "n" is the number of unique words in the corpus of text. For the relatively small chunk I am testing it on(about 60 files) it needs to make approximately 30,000x30,000 entries. this will probably be bigger once I run it on my full intended corpus too. It consistently fails every time, after it indexes, while it is initializing the data structure(to be worked on later). Things I have done include: revamp my code to use a primitive "int[]" instead of a "TreeMap" eliminate redundant structures, etc... Also, I have run eclipse with "eclipse -vmargs -Xmx2g" to max out my allocated memory I am fairly confident this is not going to be a simple line of code solution, but is most likely going to require a very new approach. I am looking for what that approach is, any ideas? Thanks, B.

    Read the article

  • OpenGL fast texture drawing with vertex buffer objects. Is this the way to do it?

    - by Matthew Mitchell
    Hello. I am making a 2D game with OpenGL. I would like to speed up my texture drawing by using VBOs. Currently I am using the immediate mode. I am generating my own coordinates when I rotate and scale a texture. I also have the functionality of rounding the corners of a texture, using the polygon primitive to draw those. I was thinking, would it be fastest to make a VBO with vertices for the sides of the texture with no offset included so I can then use glViewport, glScale (Or glTranslate? What is the difference and most suitable here?) and glRotate to move the drawing position for my texture. Then I can use the same VBO with no changes to draw the texture each time. I could only change the VBO when I need to add coordinates for the rounded corners. Is that the best way to do this? What things should I look out for while doing it? Is it really fastest to use GL_TRIANGLES instead of GL_QUADS in modern graphics cards? Thank you for any answer.

    Read the article

  • Java: which configuration framework to use?

    - by Laimoncijus
    Hi, I need to decide which configuration framework to use. At the moment I am thinking between using properties files and XML files. My configuration needs to have some primitive grouping, e.g. in XML format would be something like: <configuration> <group name="abc"> <param1>value1</param1> <param2>value2</param2> </group> <group name="def"> <param3>value3</param3> <param4>value4</param4> </group> </configuration> or a properties file (something similar to log4j.properties): group.abc.param1 = value1 group.abc.param2 = value2 group.def.param3 = value3 group.def.param4 = value4 I need bi-directional (read and write) configuration library/framework. Nice feature would be - that I could read out somehow different configuration groups as different objects, so I could later pass them to different places, e.g. - reading everything what belongs to group "abc" as one object and "def" as another. If that is not possible I can always split single configuration object into smaller ones myself in the application initialization part of course. Which framework would best fit for me?

    Read the article

  • How to create a generic method in C# that's all applicable to many types - ints, strings, doubles et

    - by satyajit
    Let's I have a method to remove duplicates in an integer Array public int[] RemoveDuplicates(int[] elems) { HashSet<int> uniques = new HashSet<int>(); foreach (int item in elems) uniques.Add(item); elems = new int[uniques.Count]; int cnt = 0; foreach (var item in uniques) elems[cnt++] = item; return elems; } How can I make this generic such that now it accepts a string array and remove duplicates in it? How about a double array? I know I am probably mixing things here in between primitive and value types. For your reference the following code won't compile public List<T> RemoveDuplicates(List<T> elems) { HashSet<T> uniques = new HashSet<T>(); foreach (var item in elems) uniques.Add(item); elems = new List<T>(); int cnt = 0; foreach (var item in uniques) elems[cnt++] = item; return elems; } The reason is that all generic types should be closed at run time. Thanks for you comments

    Read the article

  • Understanding C++ pointers (when they point to a pointer)

    - by Stephano
    I think I understand references and pointers pretty well. Here is what I (think I) know: int i = 5; //i is a primitive type, the value is 5, i do not know the address. int *ptr; //a pointer to an int. i have no way if knowing the value yet. ptr = &i; //now i have an address for the value of i (called ptr) *ptr = 10; //go get the value stored at ptr and change it to 10 Please feel free to comment or correct these statements. Now I'm trying to make the jump to arrays of pointers. Here is what I do not know: char **char_ptrs = new char *[50]; Node **node_ptrs = new Node *[50]; My understanding is that I have 2 arrays of pointers, one set of pointers to chars and one to nodes. So if I wanted to set the values, I would do something like this: char_ptrs[0] = new char[20]; node_ptrs[0] = new Node; Now I have a pointer, in the 0 position of my array, in each respective array. Again, feel free to comment here if I'm confused. So, what does the ** operator do? Likewise, what is putting a single * next to the instantiation doing (*[50])? (what is that called exactly, instantiation?)

    Read the article

  • Callers block until getFoo() has a value ready?

    - by Sean Owen
    I have a Java Thread which exposes a property which other threads want to access: class MyThread extends Thread { private Foo foo; ... Foo getFoo() { return foo; } ... public void run() { ... foo = makeTheFoo(); ... } } The problem is that it takes some short time from the time this runs until foo is available. Callers may call getFoo() before this and get a null. I'd rather they simply block, wait, and get the value once initialization has occurred. (foo is never changed afterwards.) It will be a matter of milliseconds until it's ready, so I'm comfortable with this approach. Now, I can make this happen with wait() and notifyAll() and there's a 95% chance I'll do it right. But I'm wondering how you all would do it; is there a primitive in java.util.concurrent that would do this, that I've missed? Or, how would you structure it? Yes, make foo volatile. Yes, synchronize on an internal lock Object and put the check in a while loop until it's not null. Am I missing anything?

    Read the article

  • Most awkward/misleading method in Java Base API ?

    - by JG
    I was recently trying to convert a string literal into a boolean, when the method "boolean Boolean.getBoolean(String name)" popped out of the auto-complete window. There was also another method ("boolean Boolean.parseBoolean(String s)") appearing right after, which lead me to search to find out what were the differences between these two, as they both seemed to do the same. It turns out that what Boolean.getBoolean(String name) really does is to check if there exists a System property (!) of the given name and if its value is true. I think this is very misleading, as I'm definitely not expecting that a method of Boolean is actually making a call to System.getProperty, and just by looking at the method signature, it sure looks (at least to me) like it should be used to parse a String as a boolean. Sure, the javadoc states it clearly, but I still think the method has a misleading name and is not in the right place. Other primitive type wrappers, such as Integer also have a similar method. Also, it doesn't seem to be a very useful method to belong in the base API, as I think it's not very common to have something like -Darg=true. Maybe it's a good question for a Java position interview: "What is the output of Boolean.getBoolean("true")?". I believe a more appropriate place for those methods would be in the System class, e.g., getPropertyAsBoolean; but again, I still think it's unnecessary to have these methods in the base API. It'd make sense to have these in something like the Properties class, where it's very common to do this kind of type conversions. What do you think of all this ? Also, if there's another "awkward" method that you're aware of, please post it. N.B. I know I can use Boolean.valueOf or Boolean.parseBoolean to convert a string literal into a boolean, but I'm just looking to discuss the API design.

    Read the article

  • Using static variables for Strings

    - by Vivart
    below content is taken from Best practice: Writing efficient code but i didn't understand why private static String x = "example"; faster than private static final String x ="example"; Can anybody explain this. Using static variables for Strings When you define static fields (also called class fields) of type String, you can increase application speed by using static variables (not final) instead of constants (final). The opposite is true for primitive data types, such as int. For example, you might create a String object as follows: private static final String x = "example"; For this static constant (denoted by the final keyword), each time that you use the constant, a temporary String instance is created. The compiler eliminates "x" and replaces it with the string "example" in the bytecode, so that the BlackBerry® Java® Virtual Machine performs a hash table lookup each time that you reference "x". In contrast, for a static variable (no final keyword), the String is created once. The BlackBerry JVM performs the hash table lookup only when it initializes "x", so access is faster. private static String x = "example"; You can use public constants (that is, final fields), but you must mark variables as private.

    Read the article

  • Java: over-typed structures?

    - by HH
    Term over-type structure = a data structure that accepts different types, can be primitive or user-defined. I think ruby supports many types in structures such as tables. I tried a table with types 'String', 'char' and 'File' in Java but errs. How can I have over-typed structure in Java? How to show types in declaration? What about in initilization? Suppose a structure: INDEX VAR FILETYPE //0 -> file FILE //1 -> lineMap SizeSequence //2 -> type char //3 -> binary boolean //4 -> name String //5 -> path String Code import java.io.*; import java.util.*; public class Object { public static void print(char a) { System.out.println(a); } public static void print(String s) { System.out.println(s); } public static void main(String[] args) { Object[] d = new Object[6]; d[0] = new File("."); d[2] = 'T'; d[4] = "."; print(d[2]); print(d[4]); } } Errors Object.java:18: incompatible types found : java.io.File required: Object d[0] = new File("."); ^ Object.java:19: incompatible types found : char required: Object d[2] = 'T'; ^

    Read the article

  • Nesting arbitrary objects in Java

    - by user1502381
    I am having trouble solving a particular problem in Java (which I did not find by search). I do not know how to create a nested lists of objects - with a different type of object/primitive type at the end. For example: *Note: only an example. I am actually doing this below with something other than Employee, but it serves as simple example. I have an array of an object Employee. It contains information on the Employee. public class Employee { int age int salary int yearsWorking public Employee () { // constructor... } // Accessors } What I need to do is organize the Employees by quantiles/percentiles. I have done so by the following: import org.apache.commons.math.stat.descriptive.rank.Percentile; public class EmployeeSort { public void main(String args[]) { Percentile p = new Percentile(); Employee[] employeeArray = new Employee(100); // filled employeeArray double[] ageArray new double[100]; // filled ageArray with ages from employeeArray int q = 25; // Percentile cutoff for (int i = 1; i*q < 100; i++) { // assign percentile cutoff to some array to contain the values } } } Now, the problem I have is that I need to organize the Employees first by the percentiles of age, then percentiles of yearsWorking, and finally by percentiles of salary. My Java knowledge is inadequate right now to solve this problem, but the project I was handed was in Java. I am primarily a python guy, so this problem would have been a lot easier in that language. No such luck.

    Read the article

  • Keeping track of dependency revisions

    - by Samaursa
    I have a project with several dependencies that are in various repositories. Each time I commit changes to my project, I make sure I write the revision numbers of all the dependent repositories so that in the event I ever have to come back to this revision (let's call it 5), I can immediately know which revisions of the dependent repositories revision 5 is guaranteed to work with, update the dependencies to the specified revisions, compile and run the project. So for example if I have: Dep1 @ Revisions 10 Dep2 @ Revisions 20 Dep3 @ Revisions 10 Proj @ Revisions 35 And let's say that when Proj was on revision 17, the Dep1 revision was 5, Dep2 revision was 13 and Dep3 revision was 3. So in my SVN logs, I recorded something like this: !! Works with Dep1 Rev 5, Dep2 Rev 13, Dep3 Rev 3 To me this seems primitive and makes me believe that there is a better way to do it. Now in one of my other questions, Ivy Dependency Manager has been recommended. I have not looked at it in detail yet (seems complicated and yet another thing I must learn). To me it seems like the log of SVN (and Mercurial etc.) could have been split into Log and Dependencies (if any) where the latter could be switched off if there were no dependencies (unless of course I am unaware of an easier/better solution). This would allow for a cleaner log that maybe even warned at each new commit to check the previously defined dependencies again and make sure they have not changed. So, I was wondering how everyone manages this situations and if you have any tips, techniques, programs, suggestions that you can offer. Thank you.

    Read the article

  • WPF Single Selection Across Multiple ItemsControls

    - by gregsdennis
    Part of my app has a month-view calendar interface, but I'm having trouble with item selection. The interface is set up so that each of the days in the view contains a ListBox of items, much like the month view in Outlook. The problem I'm experiencing is that I need to maintain a single item selection across all of the ListBoxes. Below is a sample window that should adequately describe my situation. I need to maintain a single selection between both ListBoxes. <Window x:Class="StackOverflow.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <ListBox ItemsSource="{Binding Numbers}" SelectedItem="{Binding SelectedObject"/> <ListBox Grid.Column="1" ItemsSource="{Binding Dates}" SelectedItem="{Binding SelectedObject"/> </Grid> </Window> In this primitive example, I would expect that when the SelectedObject property of my view model gets set to an item that's not in one ListBox, the selection would be removed in that ListBox, but that doesn't happen. I understand that I can simply name each ListBox, and hook into the SelectionChanged event. I'd prefer to not have to do that with an entire month-view calendar. There has to be a better way. In a previous iteration of the app, I was able to create a SelectionManager static class with an attached property that was used to maintain selection. However, I can't use this now as the classes I'm using for my items are not DependencyObjects, and I'd really prefer not to have to create DependencyObject wrapper classes as this will considerably complicate my architecture. Thanks.

    Read the article

  • C++ Dynamic Allocation Mismatch: Is this problematic?

    - by acanaday
    I have been assigned to work on some legacy C++ code in MFC. One of the things I am finding all over the place are allocations like the following: struct Point { float x,y,z; }; ... void someFunc( void ) { int numPoints = ...; Point* pArray = (Point*)new BYTE[ numPoints * sizeof(Point) ]; ... //do some stuff with points ... delete [] pArray; } I realize that this code is atrociously wrong on so many levels (C-style cast, using new like malloc, confusing, etc). I also realize that if Point had defined a constructor it would not be called and weird things would happen at delete [] if a destructor had been defined. Question: I am in the process of fixing these occurrences wherever they appear as a matter of course. However, I have never seen anything like this before and it has got me wondering. Does this code have the potential to cause memory leaks/corruption as it stands currently (no constructor/destructor, but with pointer type mismatch) or is it safe as long as the array just contains structs/primitive types?

    Read the article

  • "Invalid assignment" error from == operator

    - by Tom
    I was trying to write a simple method: boolean validate(MyObject o) { // propertyA && propertyB are not primitive types. return o.getPropertyA() == null && o.getPropertyB() == null; } And got a strange error on the == null part: Syntax error on token ==. Invalid assignment operator. Maybe my Java is rusty after a season in PLSQL. So I tried a simpler example: Integer i = 4; i == null; // compile error: Syntax error on token ==. Invalid assignment operator. Integer i2 = 4; if (i == null); //No problem How can this be? I'm using jdk160_05. To clarify: I'm not trying to assign anything, just do an && operation between two boolean values. I don't want to do this: if (o.propertyA() == null && o.propertyB() == null) { return true; } else { return false; }

    Read the article

  • Question on passing a pointer to a structure in C to a function?

    - by worlds-apart89
    Below, I wrote a primitive singly linked list in C. Function "addEditNode" MUST receive a pointer by value, which, I am guessing, means we can edit the data of the pointer but can not point it to something else. If I allocate memory using malloc in "addEditNode", when the function returns, can I see the contents of first-next ? Second question is do I have to free first-next or is it only first that I should free? I am running into segmentation faults on Linux. #include <stdio.h> #include <stdlib.h> typedef struct list_node list_node_t; struct list_node { int value; list_node_t *next; }; void addEditNode(list_node_t *node) { node->value = 10; node->next = (list_node_t*) malloc(sizeof(list_node_t)); node->next->value = 1; node->next->next = NULL; } int main() { list_node_t *first = (list_node_t*) malloc(sizeof(list_node_t)); first->value = 1; first->next = NULL; addEditNode(first); free(first); return 0; }

    Read the article

  • Trouble accessing fields of a serialized object in Java

    - by typoknig
    I have instantized a class that implements Serializable and I am trying to stream that object like this: try{ Socket socket = new Socket("localhost", 8000); ObjectOutputStream toServer = new ObjectOutputStream(socket.getOutputStream()); toServer.writeObject(myObject); } catch (IOException ex) { System.err.println(ex); } All good so far right? Then I am trying to read the fields of that object like this: //This is an inner class class HandleClient implements Runnable{ private ObjectInputStream fromClient; private Socket socket; // This socket was established earlier try { fromClient = new ObjectInputStream(socket.getInputStream()); GetField inputObjectFields = fromClient.readFields(); double myFristVariable = inputObjectFields.get("myFirstVariable", 0); int mySecondVariable = inputObjectFields.get("mySecondVariable", 0); //do stuff } catch (IOException ex) { System.err.println(ex); } catch (ClassNotFoundException ex) { System.err.println(ex); } finally { try { fromClient.close(); } catch (Exception ex) { ex.printStackTrace(); } } } But I always get the error: java.io.NotActiveException: not in call to readObject This is my first time streaming objects instead of primitive data types, what am I doing wrong? BONUS When I do get this working correctly, is the ENTIRE CLASS passed with the serialized object (i.e. will I have access to the methods of the object's class)? My reading suggests that the entire class is passed with the object, but I have been unable to use the objects methods thus far. How exactly do I call on the object's methods? In addition to my code above I also experimented with the readObject method, but I was probably using it wrong too because I couldn't get it to work. Please enlighten me.

    Read the article

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