w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
MATLAB: Nested functions and structs
EDIT: Updated based on the error mentioned in the comments. You can convert them by A = struct('one', [A.one], 'two', [A.two]); In general: D = [fieldnames(A), cellfun(@(x) [A.(x)], fieldnames(A), 'Uni', false)].'; A = struct(D{:}); OLD ANSWER: You can convert them by A.one = [A.one]; A.two = [A.two]; In general for theField = fieldnames(A)' F = theField{1}; A.(F) = [A.(F)]; end

Categories : Matlab

Unpacking nested C structs in Python
You Struct format does not match with C structure. (final H should be 6H) struct.unpack(6h, ..) does return 6 fields. (not one with 6 elements) So your code should looks like .. s = struct.Struct('= B B H H 6h 6h 6h 6H') fields = s.unpack(packet_data) seq, _type, flags, upTimestamp = fields[:4] x = fields[4:10] y = fields[10:16] z = fields[16:22] lowTimestamp = fields[22:]

Categories : Python

What's the effect of __attribute__ ((__packed__)) on nested structs?
No, bar will not be tightly packed. It must be explicitly marked as __attribute__ ((__packed__)) if it is to be packed. Consider the following example: #include <stdio.h> struct { struct { char c; int i; } bar; char c; int i; } foo1; struct __attribute__ ((__packed__)) { struct { char c; int i; } bar; char c; int i; } foo2; struct { struct __attribute__ ((__packed__)) { char c; int i; } bar; char c; int i; } foo3; struct __attribute__ ((__packed__)) { struct __attribute__ ((__packed__)) { char c; int i; } bar; char c; int i; } foo4; int main() { printf("sizeof(foo1): %d ", (int)sizeof(foo1)); printf("sizeof(foo2): %d ", (int

Categories : C++

Deserialize deep-nested arrays
It seems there's no built-in way of de-/serializing deep-nested json into anything other than JObject/JArray. So I use strings instead. I suppose one could write a converter to handle everything, however not needed in my case. public class NestedArrayConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value.GetType() == typeof(List<string>)) { var list = (List<string>)value; writer.WriteStartArray(); foreach (var str in list) writer.WriteRawValue(str); writer.WriteEndArray(); } else { writer.WriteValue(value); } } public override object ReadJson(JsonReader reader,

Categories : C#

Jackson - Deserialize nested JSON
I see couple of problems in your code. First thing is that you don't have report attribute in your Response class, which is required as per the json structure you have shown. Secondly you need to provide the getters and setters in your bean classes as those will be used by the jackson for marhsalling and unmarshalling of json/object.

Categories : Java

RestSharp deserialize deeply nested XML document
XML is case-sensitive in the deserialization process. To quickly get around this you can try XML = XML.Replace("COUPON", "Coupon"); etc for each of your element names. If you're going to be processing many different xml files then it will be worth finding something that will do that nicely for you. nb, you could also change the name of your property in Template from Coupon to COUPON

Categories : C#

JSON Deserialization Despair (unable to deserialize nested types)
I haven't done what you are doing before, but judging by the documentation, I'd assume the following would work: List<Type> types = new List<Type>(); types.Add(typeof(Person)); types.Add(typeof(Language)); types.Add(typeof(Secretary)); DataContractJsonSerializer dc = new DataContractJsonSerializer(typeof(PeopleObject), types); PeopleObject p = (PeopleObject)dc.ReadObject(response); You basically need to tell the Serializer all the types it may encounter while serializing/deserializing your object.

Categories : C#

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type with complex and nested objects
According to your JSON data, the objects that you need to map to have to look like this (unless you have your own JsonDeserializer of course): public class Banner { public string LocationCodeString { get; set; } public int LocationCodeInt { get; set; } public string MediaUrl { get; set; } } public class CampaignWithChosenProposal { public List<Banner> Banners { get; set; } public string Code { get; set; } public string CustomerInstruction { get; set; } public string InfoLink { get; set; } public string LobbySubTitle { get; set; } public string LobbyTitle { get; set; } public string MoreText { get; set; } public int NumOfColumns { get; set; } public int NumOfRows { get; set; } public string OriginString { get; set; } public int

Categories : C#

Proper way of dealing with array of structs: all in one place vs splitting vs arrays within structs
What I would suggest is to have a class containing a double with three static members for the things that don't change. struct myStruct{ static std::array<double,10> p1; static std::array<double,10> p2; static std::array<bool,10> p3; double w; } This way you save the space and still have easy access to the three other variables, IMO it is better to keep the class instead of just using an array of doubles because it preserves the association in between the variables and also gives you an opportunity to modify the class later on. Classes don't really cause as much overhead as you think especially with modern compilers. You may also want to make the static variables const if they will never change

Categories : C++

struct unable to define new type and structs within structs
This function: Room createRoom(char *name, float width, float length, float height); Should be declared and defined like so: struct Room createRoom(char *name, float width, float length, float height); ^^^^^^ On this line: h.rooms[1] = &createRoom("lounge", 20, 20, 9); you are taking the address of a temporary which you are not allowed to do. You could potentially use a temporary variable like so: h.rooms[0] = &hall; struct Room hall2 = createRoom("lounge", 20, 20, 9); h.rooms[1] = &hall2 ; although that is not a pretty solution, you may want to consider having createRoom dynamically allocate a Room and return a Room*. You are also assigning string literals to name and address which could come back to bit you later on, you may also want to consider dynamically alloc

Categories : C

Sorting an array of structs by particular members of said structs?
You can use std::sort with lambdas, like this: myStruct pointOfInterest = ...; // Set the point of interest sort(mMyClassVector.begin(), mMyClassVector.end(), [&](const myStruct & lhs, const myStruct & rhs) -> bool { double distanceLhs = computeDistance(pointOfInterest, lhs); double distanceRhs = computeDistance(pointOfInterest, rhs); return distanceLhs < distanceRhs; });

Categories : C++

Marshal C++ to C# structs with unions of structs
A precious ressource about translation can be found here IMO, reading it worth every single page :) About FooBarZ, you are looking for [FieldOffset(NBR)], which is the way to translate union. Look at the translation in pinvoke of the STRRET struct for an example on how to use it.

Categories : C#

Nested structs/Using a struct in another struct
You can't initialize(in fact those are assignments here) the members inside a class/struct declaration. Remove all the initializations which you're doing. Except that the nested struct should work fine. Change the code to the following: struct pokeDex { struct pokemonTemplate { std::string pokemonName; std::string pokemonMoves[3]; int pokemonLevel; int baseATK; int baseDEF; int baseSPATK; int baseSPDEF; int baseSPEED; }; pokemonTemplate Bulbasaur; pokemonTemplate Pikachu; }; And write your own constructor to initialize them or some setters methods to do the work.

Categories : C++

C++ For loops through Vectors of Structs (containing more vectors of structs)
Your struct does not contain a vector, it just has a typedef: typedef vector<pAccount> Accounts; If you want Accounts to be a data member, remove the typedef. vector<pAccount> Accounts; Furthermore, you should seriously consider not using the same name for the items in both levels of the nested loop: for (auto& user : users) { for (auto& account : user.Accounts) { Also, note that you do not need to use typedef to declare a struct. In typedef struct Foo {};, the typedef is ignored. It just adds clutter to the code. Finally, at a glance there seems to be no reason for the usage of pointers in your code. It would be greatly simplified if you stored values instead.

Categories : C++

Struts 1.1 nested and in combination
Use <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> and the code will look like <c:choose> <c:when test="${element.method1 == true}"> <c:choose> <c:when test="${element.method2 == true}"> <span style="color:green;"><c:out value="${element.prop1}/></span> </c:when> <c:otherwise> <span style="color:red;"><c:out value="${element.prop1}/></span> </c:otherwise> </c:choose> </c:when> <c:otherwise> <span style="color:black;"><c:out value="${element.prop1}/></span> </c:otherwise> </c:choose>

Categories : Java

Calloc(), Structs & C
The rule is very simple. You can and should free precisely that which you allocated. That is, you must only pass pointers to free() which you received as the return value of malloc/calloc/realloc etc.*, or a null pointer. Nothing else may be passed to free(). So, you can free tne entire array, or nothing at all. (Note also that "freeing a single element from the middle" would be utterly pointless, because you would have no way of iterating over such a "holy" array sensibly.) If you want to deallocate some memory, allocate a new range, copy the desired elements over and free the original array. *) Some quasi-standard functions may indirectly return dynamically allocated memory which you must fre; check the documentation. Some examples are strdup, GNU's scanf, and GCC's abi::__cxa_demangl

Categories : C

iOS: why can't you have objects in structs?
If you look at the Transitioning to ARC Release Notes, it says: You cannot use object pointers in C structures. Rather than using a struct, you can create an Objective-C class to manage the data instead. If you watch WWDC 2011 video Introducing Automatic Reference Counting, it touches on the point why this is the case on the slide titled Rule #2/4: No Object Pointers in C Structs (slide #21), namely that: Compiler must know when references come and go Pointers must be zero initialized Release when reference goes away C structs don't satisfy that critiera, which is why they advise using objects instead. You could use __unsafe_unretained in conjunction with C structs, but that is, as the name makes obvious, unsafe, and defeats many of the benefits of ARC.

Categories : IOS

Vector of structs c++
You must turn this: vector<Info> dataBase; into this: vector<Info*> dataBase; as you want to push_back a pointer, and vector is declared to take objects.

Categories : C++

Confusion about structs
You need curly braces to intitialize: tPage pagenumber = {0}; or make your own constructor: struct sPage { U16 _; sPage(U16 val) : _(val) { } };

Categories : C++

Structs and classes advice
This depends more on the purpose of your type than on the size. If you want to pass data around and want a copy for each call you should use a struct. But if you need to have your data stored at a central location and many other parts of your code should work on the same data, then you need a class. A class is passed by reference and does not duplicate any data. If you copy data around, as structs do, you can end up with an inconsistent state.

Categories : C#

Objective-C array of structs
Unfortunately, Objective C with Automatic Reference Counting (ARC) enabled does not allow for objects inside C structs. Objc also only allows objects inside NSArrays (the loose equivalent of vectors). The first step of the solution is to create a class instead of a struct: // Foo.h #import <Foundation/Foundation.h> @interface Foo : NSObject @property (nonatomic, strong) NSString *title; @property (nonatomic, strong) NSArray *books; // no need to keep the number of items in an NSArray as a separate variable, // NSArray does that for you. - (id)initWithTitle:(NSString *)title books:(NSArray *)books; @end // Foo.m #import "Foo.h" @implementation Foo @synthesize title; @synthesize books; - (id)initWithTitle:(NSString *)title books:(NSArray *)books { if (self = [super init]) {

Categories : Objective C

Struct in C, functions with structs
This code is totally wrong: for (k = 0 ; k < lines_got; k ++) { temp_country_name[k] = tolower (ptr_player[k].player_country); k++; } You're incrementing k twice -- in the loop header and in the body. The target of the assignment is a single character in the temp_country_name string, but the parameter to tolower() is an entire string. Aren't you getting a warning from the compiler saying that the parameter to tolower() is the wrong type (it expects a char, you're giving it a char*)? You're already iterating over lines in the outer loop using i. This loop should just iterate over characters. Try this: for (k = 0 ; ptr_player[i].player_country[k]; k ++) { temp_country_name[k] = tolower (ptr_player[i].player_country[k]); } ptr_player

Categories : C

How to create immutable structs in C++?
The reason for this is that in C++ after a variable has been created (either a local or field variable) it cannot be "replaced" with another instance, only its state can be altered. So in this line index = MyIndex(1); not a new MyIndex instance is created (with its constructor), but rather the existing index variable is supposed to be altered with its copy assignment operator. The missing operator = function is the copy assignment operator of the MyIndex type, which it lacks, because it doesn't get automatically generated if the type has a const field. The reason why it is not generated is that it simply can't be sensibly implemented. A copy assignment operator would be implemented like this (which doesn't work here): MyIndex& operator=(const MyIndex& other) { if(this != &

Categories : C++

JNA: how to deal with unkown structs?
If you don't know the content of the struct, then it is referred to as "opaque". For opaque struct *, you can use com.sun.jna.Pointer to represent the structure address.

Categories : Java

Use lambda/linq on structs
CODE.Status would never work, as is it presented in question, cause Status is a type inside your class and, not it's member. You can think about something like: public partial class CODE { public struct Status { public static readonly long Registered = 5; //STATIC public static readonly long Active = 6; //STATIC } } In this way you can access those fields, but it's not clear to me if this completely answers your question. If it's not, please clarify.

Categories : C#

is move constructor necessary on (POD) structs?
Yes, it will work without the need of specifying the move constructor; in your example, it is possible that the compiler optimizes the move operation by initializing lala instead of test; check the assembler output about that.

Categories : C++

Unions used like Classes/Structs
Is this a new feature of C++, or something specific to MSVC? No, as BoBtFish said, the 2003 C++ standard section 9.5 Unions paragraph 1 says: [...] A union can have member functions (including constructors and destructors), but not virtual (10.3) functions. A union shall not have base classes. A union shall not be used as a base class. An object of a class with a non-trivial constructor (12.1), a non-trivial copy constructor (12.8), a non-trivial destructor (12.4), or a non-trivial copy assignment operator (13.5.3, 12.8) cannot be a member of a union, nor can an array of such objects. If a union contains a static data member, or a member of reference type, the program is ill-formed. unions do come under section 9 Classes and the grammar for class-key is as follows: class-key:

Categories : C++

Structs - expression must be a modifiable value
You can't use that syntax to initialize an array outside of the arrays definition. You have to fill in all values manually. Fortunately there are standard C++ functions to do that for use, like std::fill: std::fill(std::begin(element.bWpId), std::end(element.bWpId), '0'); element.bWpId[9] = '1'; You can of course make a constructor for the sWaypoint_t structure, and initialize the array in that: typedef struct sWaypoint_s { CHAR_t bWpId[10]; CHAR_t bWpDescr[25]; UINT16_t wCoA; sUtmCoordinate_t Coordinate; sWaypoint_s() : bWpId{'0','0','0','0','0','0','0','0','0','1'} {} } sWaypoint_t; The problem with this is that it requires a C++11 capable compiler.

Categories : C++

C++ vector of structs with pointers
Your solution doesn't work because of test_struct destructor and the fact you're trying to store your structs in a vector. When test_struct tmp is pushed to the vector, a copy of test_struct is created. Then tmp is destroyed with calling delete[] array and the copy in vector <test_struct> data ends up with a dangling pointer. You probably need to rethink your architecture, or at least add a copy constructor for the test_struct that will copy the whole array

Categories : C++

Mix c++ with objective-c pointers, structs
Your problem is that in the Objective-C case, the player structure isn't a local variable - it has assumedly been declared as a property. When you assign a value using self.player, you are essentially calling the property setter method [self setPlayer:{0}] which doesn't make any sense. Looking at how you're using the code, I'm assuming player is actually declared as a pointer to a MyPlayer struct, so you would need to allocate memory for it. If you use calloc for that you can create the structure and initialise it to zero at the same time. Something like this: self.player = calloc(1, sizeof(MyPlayer)); This allocates the memory, sets the contents to zero, and calls the property setter to assign that memory to the player property. If I've got that wrong, it would help if you showed ho

Categories : C++

Can structs be cast to a different size in the following way?
The second parameter to _tcscpy_s is the number of elements but you're feeding it the number of bytes. According to the documentation: The debug versions of these functions first fill the buffer with 0xFE. This will result in a buffer overflow if sizeof(TCHAR) != 1.

Categories : C

Passing Structs in Ctypes
To handle aggregate returns larger than 8 bytes, both MinGW and Microsoft's compiler implicitly pass a pointer to local memory in the caller. It looks like your version of gcc defaults to popping this pointer in the callee. However, ctypes/libffi was built with Visual Studio and expects Microsoft's convention, which handles this in the caller. That's why it complains about missing 4 bytes. If you're using gcc 4.6+, there's a function attribute to enable Microsoft's convention: callee_pop_aggregate_return (number) On 32-bit i?86-- targets, you can control by those attribute for aggregate return in memory, if the caller is responsible to pop the hidden pointer together with the rest of the arguments - number equal to zero -, or if the callee is responsible to pop hidden pointer - n

Categories : Python

Why can't I pass up an array of structs from C++ to C#
You are missing a level of indirection. Your native code returns a double pointer. But the managed code only performs a single pointer de-reference. Add in that second layer of indirection and you'll be fine. Instead of Marshal.PtrToStructure(arrayValue, typeof(DeviceEndPoint) you need Marshal.PtrToStructure(Marshal.ReadIntPtr(arrayValue), typeof(DeviceEndPoint) And instead of arrayValue = new IntPtr(arrayValue.ToInt32() + deviceEndPointSize); you need arrayValue = new IntPtr(arrayValue.ToInt64() + Marshal.SizeOf(IntPtr)); To be honest though, this is a pretty complex interface. If I was faced with creating an interop layer, I would use C++/CLI.

Categories : Misc

Brace initialization of structs
From section 8.5.1 Aggregates of the c++11 standard (draft n3337): 1 An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3). 2 When an aggregate is initialized by an initializer list, as specified in 8.5.4, the elements of the initializer list are taken as initializers for the members of the aggregate, in increasing subscript or member order... And from section 8.5.4 List-initialization: List-initialization can be used as the initializer in a variable definition (8.5) as the initializer in a new expression (5.3.4) This means NaryNode is an

Categories : C++

Expand array of structs using realloc
The new allocated size should be based on the size of the elements of the array, and not based on the size of the pointer to the beginning of the array. Also you want to resize it relative to the current length: container->inner = realloc(container->inner, sizeof(*container->inner) * (container->length + 50));

Categories : C

1 struct with 2 different definitions (or dynamic structs)
No, this won't work. First of all, all the definitions of the structure must be the same, otherwise you get the infamous Undefined Behaviour. Second, look at the memory layout. What should be the offset to bar from the beginning of the structure? The first and the third definitions don't agree on this (the fields are most likely to be located consecutively). Maybe you can try a union? struct theStruct { int fd; unsigned int flags; struct config config; int foo; // in both systems union { int bar; // only in System A int foobar; // only in system B }; }; If you choose this, you should use only bar on System A and only foobar on System B. If the two systems are incompatible, and the actual type needed for bar is

Categories : C

syntax error C2061 using structs
order! typedef struct { char * cModel; } model; typedef struct { char *cMake; model *testModel; } make; your compiler doesn't know model when you use it, because it's defined later in the code.

Categories : C

Cython Memoryviews -- From Array of Structs?
Actually, just building a structured numpy array and then a memoryview works just fine. cdef np.ndarray hi2u = np.ndarray((MAXPOWER,),dtype=[('lucky','i4'),('unlucky','a10')]) cdef oh_hi [:] hi2me = hi2u The performance of this seems quite good and this saves a later copy if you need the data back in python. As per usual, the numpy version is pretty good. =p

Categories : Python

C++ macro to generate const structs
Yes, you can do it with Boost.Preprocessor. #define CONST_STRUCT(name, members) struct name { name(GENERATE_CTOR_PARAMS(members)) : GENERATE_CTOR_INITIALISERS(members) {} GENERATE_MEMBERS(members) } #define PARAM_TYPE(param) BOOST_PP_TUPLE_ELEM(2, 0, param) #define PARAM_NAME(param) BOOST_PP_TUPLE_ELEM(2, 1, param) #define GENERATE_CTOR_PARAMS(members) BOOST_PP_ENUM(BOOST_PP_SEQ_SIZE(members), GENERATE_CTOR_PARAM, members) #define GENERATE_CTOR_PARAM(z, idx, members) const PARAM_TYPE(BOOST_PP_SEQ_ELEM(idx, members)) & PARAM_NAME(BOOST_PP_SEQ_ELEM(idx, members)) #define GENERATE_CTOR_INITIALISERS(members) BOOST_PP_ENUM(BOOST_PP_SEQ_SIZE(members), GENERATE_CTOR_INITIALISER, members) #define GENERATE_CTOR_INITIALISER(z, idx, members) P

Categories : C++

Issue with template in structs struct in c++
T represents a type, such as int. Writing return T; will be the same as return int; when T is an int. Is return int; valid? You can call your function template as: dummy.myproc<int>();. You have to tell it what T is by writing <int>. If however the function took a T argument then the compiler would be able to deduce what T is by seeing the type of the argument. For example dummy.myproc(2.3) would resolve as T being a double because 2.3 is a double.

Categories : C++



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.