w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to resolve the correct type from the container (static type vs runtime type)?
You'll need to do some sort of runtime resolution of the type. E.g. using the dynamic keyword: IBase a = new A(); Console.WriteLine(Resolve((dynamic)a)); A b = new A(); Console.WriteLine(Resolve((dynamic)b)); Or using reflection: int ResolveDynamic(IBase a) { MethodInfo method = typeof(IContainer).GetMethod("Resolve"); var handlerType = typeof(IHandler<>).MakeGenericType(a.GetType()); var enumerableType = typeof(IEnumerable<>).MakeGenericType(handlerType); MethodInfo generic = method.MakeGenericMethod(enumerableType); var result = (IEnumerable<object>)generic.Invoke(_container, null); return result.Count(); }

Categories : C#

Static nested class as generic type bound doesn't work
First, you don't have to static-import the class. Just qualify the reference to your inner classes: public abstract class AbstractContainer<ElementType extends AbstractContainer.AbstractElement> { and public class ConcreteContainer extends AbstractContainer<ConcreteContainer.ConcreteElement> When compiling with Java 1.6, I don't see your compiler error. But I do see it when compiling with 1.7. As it happens, fully-qualifying AbstractElement when declaring ConcreteElement seems to satisfy the compiiler: public class ConcreteContainer extends AbstractContainer<ConcreteContainer.ConcreteElement> { // fully qualify here public static class ConcreteElement extends AbstractContainer.AbstractElement { }

Categories : Java

ClientRequest, how to serialize POJO's to json data correctly? could not find writer for content-type application/json type:
Problem solved, unfortunately I haven't included all necessary 3rd party libraries to the projects build path. Finally I added the following jars: jackson-core-asl-1.6.3.jar jackson-jaxrs-1.6.3.jar jackson-mapper-asl-1.6.3.jar jackson-xc-1.6.3.jar resteasy-jackson-provider-2.2.1.GA.jar This example brings the strength of Maven to the front. With Maven there is only one entry necessary to fulfill these dependencies. <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jackson-provider</artifactId> <version>2.2.1.GA</version> </dependency>

Categories : Java

Output of static base type and dynamic derived type
Have a look at Can virtual functions have default parameters?: A virtual function call (10.3) uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object. An overriding function in a derived class does not acquire default arguments from the function it overrides. Therefore, bptr->display(); calls the derived version of display, but uses the argument from base, the static type of the pointer bptr. This is because the default value of an argument has to be determined at compile time while dynamic binding is deferred to the runtime. Using different default arguments in the base and derived versions of the same virtual is almost guaranteed to cause trouble. Problems are likely to arise whe

Categories : C++

Processing Java Error: The nested type (Node) cannot hide an enclosing type
Check if your tab or sketch name is the same as program's inner class name. Change the name of your tab/sketch and you'll be fine. Rename your sketch (foo.pde) which is also the name of the tab to something other than the class name. The main sketch in processing cannot have a nested class with the same name, other sketches (other tabs) can have classes that are the same name as the tab.

Categories : Java

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#

Custom Json.NET serializer settings per type
Based on your comment above, following is an example of per-controller configuration: [MyControllerConfig] public class ValuesController : ApiController [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class MyControllerConfigAttribute : Attribute, IControllerConfiguration { public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor) { //remove the existing Json formatter as this is the global formatter and changing any setting on it //would effect other controllers too. controllerSettings.Formatters.Remove(controllerSettings.Formatters.JsonFormatter); JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter(); formatter.SerializerSettings.

Categories : C#

ASP.MVC 3 AJAX JSON won't serialize to Rectangle or Custom Type
Your jquery ajax code is missing the contentType parameter: var cropArea = { X: 50, Y: 50, Width: 200, Height: 200 }; var cropArea = { X: 50, Y: 50, Width: 200, Height: 200 }; var destSize = { Width: 200, Height: 200 }; $.ajax({ url: "image/CropImage", type: "POST", data: JSON.stringify({ id: image.id, cropArea: cropArea, size: destSize }), dataType: "json", contentType: 'application/json; charset=utf-8' }); I have quickly tested that using a dummy method in my home controller and some dummy classes: [HttpPost] public ActionResult ResizeImage(int id, Rectangle cropArea, Size size) { // Crop Code here return Json(true); } public class Rectangle { public int X { get; set; } public int Y { get; set; } public int Width { get; set; } public int H

Categories : Asp Net Mvc

Generic Class with Static Nested Class of the Same Type
You could declare the type of stctype as <? extends T>. private final Class<? extends T> stcType; This will ensure that the stctype is able to handle T or any subclass of T. In order to get rid of the compiler error, you can now safely cast the helper.crtObject().getClass(); to Class<? extends T> as follows: stcClass = (Class<? extends T>) helper.crtObject().getClass();

Categories : Java

Static constructor cannot have return type but static method must have return type in C#
Static constructor cannot have return type(int,string etc) Correct. But a (static) constructor does not need to return anything. but static method must have return type in C#. Wrong. A static method can very well be a void method. How does c# compiler distinguish ... static class StaticClass { public static StaticClass(){} //right : Wrong. 'public' is not allowed. public static int StaticClass(){} //wrong : Indeed wrong. Member cannot have same name as class public static int StaticMethod(){} //right }

Categories : C#

JSON Schema: represent constraint to encode object type in string type
I agree, either you choose the object or string type. I have looked into the JSON Schema documentation and I could not find anything to express the constraint as clear as needed. Hence, a short discussions of the two approaches there are to my mind. Type String JSON Schema defines seven primitive types, including object. A string is simply defined as a JSON string. The RFC 4627 defines a JSON string as follows A string is a sequence of zero or more Unicode characters This would apply to your case, even though the content of the string has to be restricted. The question is how to communicate the restriction. I would use a description to reference to another subschema. You can even define a pattern for the string an encode the subschema as regular expression. This, however,

Categories : Javascript

How to deserialize JSON with fixed type header and variant type body in C#?
Is it feasible to solve this problem by using an interface instead of object, and making use of the "specify known types" version of the DataContractJsonSerializer ( http://msdn.microsoft.com/en-us/library/bb908209.aspx ) ? It would look something like var serializer = new DataContractJsonSerializer(typeof(IMySerializable), new [] { typeof(ConcreteSerializable1), typeof(ConcreteSerializable2) }); Basically, DataContractSerializer needs context on what you expect it might serialize/deserialize, it can't infer types from the content of the JSON. If you don't want to do that you may want to consider a third party library that will give you m

Categories : C#

Actionscript check custom object defined type (not actual type)
I think you're misunderstanding the way all of those examples in your question work. They don't check the type that is associated with a variable - they check the type of the instance assigned to that variable. Here is a good example of why your examples don't make sense: var prop:DisplayObject = new MovieClip(); trace(prop is MovieClip); // true If this worked the way you thought it does, you would actually get false here. All you're doing when you create a variable and give it a type is telling the compiler what type of instances it expects to see assigned to that property, and to throw an error if something that is not an instance of the expected type is assigned to it. I don't think there is a way to determine what type a variable expects. Moreover, I think if you see a need to

Categories : Actionscript

Could not determine JSON object type for type System.Char
If you are getting multiple randoms in sequence may need to change your code to generate better randoms but this will work for creating a JArray var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var random = new Random ( ); var result = JArray.FromObject ( Enumerable.Repeat ( chars , 1 ) .Select ( s => s [ random.Next ( s.Length ) ] ) .ToArray ( ) );

Categories : C#

cds library: michael_deque causes crash when pushing back derived type of custom type (only in release mode)
It was indeed a compiler bug. More specifically, it was a bug associated with Visual Studio 2012's atomic implementation. Some template specializations of the std::atomic class modify the stack frame pointer (ebp) without backing it up on and popping it form the stack before/after the modification. The libcds library uses one of these specializations, and the resulting incorrect frame pointer sometimes causes illegal memory access (the undefined behavior seems to prevent catastrophic failure in debug mode) when running outside the scope of a function. The fix in this special case was to make libcds use a different atomics library then the standard one provided by Visual Studio. The library decides which implementation to use in cxx11_atomic.h: #if defined(CDS_USE_BOOST_ATOMIC) # err

Categories : C++

Serialize complex type as simple type JSON
import this namespace System.Web.Script.Serialization; string SerializeObject() { var objs = new List<Test>() var objSerialized = new JavaScriptSerializer(); return objSerialized .Serialize(objs); } I use as example a List but you will use your object instead.

Categories : C#

Json.NET how to override serialization for a type that defines a custom JsonConverter via an attribute?
You need to use custom contract resolver. Default contract resolver uses converters from settings only if converter is not specified for the type. class CustomContractResolver : DefaultContractResolver { protected override JsonConverter ResolveContractConverter (Type objectType) { if (typeof(Foo).IsAssignableFrom(objectType)) return null; // pretend converter is not specified return base.ResolveContractConverter(objectType); } } Usage: JsonConvert.DeserializeObject<Foo>("{}", new JsonSerializerSettings { ContractResolver = new CustomContractResolver(), Converters = new[] { new CustomConverter() }, });

Categories : C#

Calling a constructor on custom view model changes output type to JSON
It seems that this is some weird behavior of the serializer. Add a default empty constructor to your model along with the other constructor: public MyViewModel() { } public MyViewModel(Product product) { } But personally I would use a view model. A real one. Not some hybrid to which you are passing your domain model. Just have a simple POCO as view model. And a mapping layer that will map from the domain model.

Categories : C#

How to define a lengthy type as a custom type?
To derive a class from List<string>, use the following syntax: public class LString : List<string> { } It is not possible to further derive the class from an array. So you'll have to be happy with: LString[] myvar = new LString[5]; Edit: Based on feedback, you're better off doing something like this to encompass your list: public class LString { private List<string>[] _lists = new List<string>[5]; public void Add(int index, string value) { if (index < 0 || index > 4) throw new ArgumentOutOfRangeException("index"); _lists[index].Add(value); } }

Categories : C#

Enum type reference or primitive (with example) - shallow/deep copy
There's nothing special about enums here. You'll see the exact same behaviour if you use strings or any type, basically. Your two Test objects are entirely separate. When you write: t2.enumValue = TestEnum.THREE; you're changing the value of the enumValue field within the second object to be a reference to the object referred to by TestEnum.THREE. The two enumValue fields (one via t1 and one via t2) are entirely separate. Changing one field doesn't change another. Now, if instead you made your enum mutable (which I would strongly discourage) and changed your code to something like this: t2.enumValue.someMutableField = "a different value"; ... then that would be visible via t1.enumValue, because they both refer to the same object. It's really important to differentiate between cha

Categories : Java

Cannot access none static methods from static method, Android: getResources() from the type ContextWrapper
In Java static method can not access any non-static method or variable. One of the basic rules of working with static methods is that you can’t access a nonstatic method or field from a static method because the static method doesn’t have an instance of the class to use to reference instance methods or fields. for more information Document here is good example how to access them

Categories : Java

Nested and recursive JSON input handling
Read this acticle: http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/ My opinion, you should do the service in this case, something like this: # app/services/recursive_update.rb class RecursiveUpdate def initalize(source) @source = source end def update(params) # your code here end def create_term(term_params, parent=nil) #.... end def permitted_params #.... end def save @source.save end end in the controller: updater = RecurciveUpdate.new @model updater.update params update.save

Categories : Ruby On Rails

Cannot make a static reference to the non-static method getSystemService(String) from the type
getSystemService is a non static method of the Context class, so in order to access it you need an object from the class Context.Typically you call it from inside an Activty where this is also an object of Context . In order to fix you could pass a Context to your method isNetworkConnected

Categories : Android

Cannot make a static reference to the non-static method getFilter() from the type JobsListAdapter
Just what it says. Either you need to make the method static or create an instance of the class and access the method that way. Something like JobsListAdapter myClass = new JobsListAdapter(); // enter your params for the constructor myClass.getFilter().filter(s.toString().toLowerCase()); or change the method signature to include the static modifier which may or may not be what you want. public static Filter getFilter() { if(filter == null) filter = new MangaNameFilter(); return filter; } Just a couple links that may be helpful When to make my method static Understanding instance and class members

Categories : Android

Cannot make a static reference to the non-static method invalidate() from the type View MainActivity.java
View is a class. invalidate() is an instance method. You need to call it on an instance. However, you need to perform UI modifications on the UI thread. I would make your Activity class implement a Callback interface with a method like public interface Callback { void onModifiedTextView(String value); } Your class then implements it as public void onModifiedTextView(final String title) { runOnUiThread(new Runnable() { public void run() { textView.setText(title); textView.invalidate(); // not even necessary } }); } Then pass that to DownloadWebPageTask. In other words, create a constructor that accepts a Callback instance public DownloadWebPageTask(Callback callback) { this.callback = callback; } private Callback callback;

Categories : Java

Mongo/DataNucleus/JPA with embedded type query gives: Cannot find type of (part of) ... since symbol has no type; implicit variable?
FINE: Compilation of filter to be evaluated completely in-datastore was impossible : Invoke expression is not supported by this mapper so it is not currently implemented to convert JPQL "collField.contains(val)" (the equivalent of what you typed in for your query) into a MongoDB query, hence cant evaluate it in the datastore. Since you know what it needs converting into, you can easily enough get the code for the DataNucleus MongoDB plugin and find class QueryToMongoDBMapper and contribute support for that particular query.

Categories : Mongodb

Haskell Recursive Type
Part 1: data Elem = El String | Node String String Resp type Resp = [Elem] Part 2: Well... kinda. The unsatisfying answer is: You shouldn't want to because doing so is less type safe. The more direct answer is Elem needs it's own constructor but Resp is easily defined as a type synonym as above. However, I would recommend newtype Resp = Resp { getElems :: [Elem] } so that you can't mix up some random list of Elems with a Resp. This also gives you the function getElems so you don't have to do as much pattern matching on a single constructor. The newtype basically let's Haskell know that it should get rid of the overhead of the constructor during runtime so there's no extra indirection which is nice.

Categories : Haskell

how does Cpython implement its type Objects, i.e. type's type is always type?
The code that defines PyType_Type.ob_type = &PyType_Type involves a couple of indirections. It all starts in the function _Py_ReadyTypes() when it calls PyType_Ready(&PyType_Type). Before the function is called, the members tp_base and ob_type are both NULL. The function first sets type->tp_base to &PyBaseObject_Type (which is object in Python space) and then sets type->ob_type = PyBaseObject_Type.ob_type. The code uses Py_TYPE() which is just a macro for ob->ob_type. Since the type of object is type the code sets the type of type to type. Now you have: >>> type.__bases__ (<class 'object'>,) >>> type(object) <class 'type'> >>> type(type(object)) <class 'type'> The definition makes type an instance of object plus itself a

Categories : Python

Type 'MyClass' cannot inherit from a type that is not marked with DataContractAttribute or SerializableAttribute. Consider marking the base type
One approach would be to override it: public new byte[] SomeByteArray { get; set; } and then you could ignore it with the IgnoreDataMember attribute.

Categories : C#

the content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8'
You need to use the WebServiceHostFactory, instead of the regular ServiceHostFactory in your code. That will configure the endpoint with the appropriate binding (webHttpBinding) and behavior (webHttp) to honor the [WebInvoke] attribute. <serviceHostingEnvironment > <serviceActivations> <add factory="System.ServiceModel.Activation.WebServiceHostFactory" relativeAddress="./wsccc1/wscccService.svc" service="service.wservice"/> </serviceActivations> </serviceHostingEnvironment>

Categories : Json

Wordpress custom post type capabilities, admin can't edit post type
thats a strange problem. it should work. the following will work for you (note i just copied paste my code so some of my code creeped in) add_action('init', 'register_custom_event_type'); function register_custom_event_type() { register_post_type('event', array( 'labels' => array( 'name' => _x('Event', 'Event'), 'singular_name' => _x('Event Custom Post', 'domain'), 'add_new' => _x('Add New', 'domain'), 'add_new_item' => _x('Add New Event Custom Post', 'domain'), 'edit' => _x('Edit', 'domain'), 'edit_item' => _x('Edit Event Custom Post', 'domain'), 'new_item' => _x('New Event Custom Post', 'domain'), 'view' => _x('View Event Custom Post', 'domain'), 'view_item' => _x('View Event Custom Post', 'dom

Categories : Wordpress

Entity Framework 5 table-per-type update, change sub type but keep same base type
I don't have a good answer, but I can think of four "solutions" that are really workarounds: Don't use DBMS-computed values for your primary keys (if you already use natural keys, it's fine). Use DBMS-computed surrogate keys. Follow something like the state pattern. Do some evil voodoo with the object state manager. Update: There seems to be a popular consensus that trying isn't even worth it; most people thus simply use stored procedures instead to work around the problem. Changing Inherited Types in Entity Framework Entity Framework: Inheritance, change object type Changing the type of an (Entity Framework) entity that is part of an inheritance hierarchy Changing the type of an entity that is part of an inheritance hierarchy Using natural keys First, remember that the objects tr

Categories : Entity Framework

Template specialization for recursive type
Did you try it? Note that you can't make the class not exist, however you can make it not inherit from singleton, in order to break the chain. template <class T> class stats<singleton<stats<T> > > {};

Categories : C++

Recursive type constraints in CodeDom
For the reasons unknown, Add method doesn't use type parameter name then it's passed as a Type type, but it will generate them from a string. Apparently difference is in the CodeTypeReference class constructor (which is ultimate item type in Constraints collection). So codeTypeParameter.Constraints.Add(constraint.ToString()); should give you an expected result.

Categories : C#

WordPress custom post type archive-.php not working
It looks like in your URL example you're attempting to get to the actual template file name itself. But if you've defined the slug to be event you should be able to simply visit localhost/websitename/wordpress/event

Categories : PHP

json database get image setting data for json using while loop carousel type jquery json
Look for a jquery carousel plugin. http://vandelaydesign.com/blog/tools/jquery-carousel-plugins/ http://www.webdesigntunes.com/freebies/30-amazing-free-jquery-slider-and-carousel-plugins-of-2013/ Edit: does this help? $data = array(); $x = 0; while ($test = mysql_fetch_array($query)) { $data[$x]['content'] = "<div class='slide_inner'><a class='photo_link' href='#'><img class='photo' src='{$test['image']}' alt='Bike'></a><a class='caption' href='#'>Sample Carousel Pic Goes Here And The Best Part is that...</a></div>"; $data[$x]['content_button'] = "<div class='thumb'><img src='{$test['thumb']}' alt='bike is nice'></div><p>Agile Carousel Place Holder</p>"; $x++; } echo json_encode($data);

Categories : PHP

Scala classOf on class with recursive type parameter
How about simply classOf[Order[_]]? (BTW, your Java declarations are using raw types — most likely, you'll need to declare things like class Order<O extends Order<O, I>, I extends Item<O, I>> and class Item<O extends Order<O, I>, I extends Item<O, I>>.)

Categories : Java

Annotated recursive data types with different type of annotation in AST
So you've got this big old term annotated with ranges everywhere. You destruct it, which gives you a range annotation named pos and a subterm (still annotated with ranges all over the place) named exp. You throw out pos and replace it with a type annotation, which is laudable, but then have the audacity to claim that exp is annotated with types. But that's clearly not true -- you would have to traverse the entire subterm and rip out all the old annotations for it to be! The error says this, too, but its language is dry and boring.

Categories : Haskell

A recursive template type for a container / typename forwarding
You need to tell the compiler that Inner is a templated class: template<typename T, template<typename> class Inner> struct container { T value; Inner<container> holder; };

Categories : C++

Scala type mismatch: default.type (with underlying type A1 => B1)
Strange, as soon as I renamed default variable, everything compiled fine: scala> def composeHandlingFuture[T](fut: Future[T], x: T): Future[T] = | fut recover { case e: Exception => x } composeHandlingFuture: [T](fut: scala.concurrent.Future[T], x: T)scala.concurrent.Future[T]

Categories : Scala



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