w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Generic scala function whose input is a function of variable arity
There is a pattern called Magnet Pattern, created by the Spray team. It does exectly what you want

Categories : Scala

Possible to compile-time check constructor parameters for generic factory function?
Not really, since you're using reflection which is a runtime technology... The only way the compiler would become aware of the inability to create your instance would be to run your code... At least until the CAAS shows up. One option might be to approach this differently: force a new() constraint on your generic type in the method (makes sure that all types have a parameterless constructor) and then maybe map the constructor parameters as properties instead on your types? Maybe not ideal if you want immutability but reflection can write to private types etc. anyway... This is pretty much the kind of scenario that the ArgumentException class was built for... Throw it if stuff doesn't work as expected.

Categories : C#

How to create a function in oracle in which i don't know the count of input parameters
There are 2 option The first one You need 2 parameters: 1. table name for your avg calculation 2. either xmltype or varchar2 or clob which contains the list of fields 3. id of the row in your table Next step you create dynamic sql which extracts and inserts values from the table sequentialy either in a temporary table or a collection and calculates ordinal AVG. The second one: Just one parameter - table of number (collection I meant) which you populate by yourself and calculate avg on it. If you like a stupid solution create 50 overloaded functions with number of parameters from 1 to 50 in a package.

Categories : SQL

How do I declare the constructor for a generic class with a generic base class with parameters?
This is fundamentally impossible. The problem is that you are not allowed to derive a generic class from a type parameter, which you are trying to do with class TException<P> : P If you actually try to compile your code, you'll see this error: Cannot derive from 'P' because it is a type parameter The other error you are seeing (about the Object() base) is an artifact. Note that the reason you can't derive a generic class from a type parameter is that this must be guaranteed to work at compile time, but there is no language support for constraining the type so that it is a non-sealed class.

Categories : C#

How can i make a generic function of two functions with a generic type specifier to a parameter
public class BinarySearchComparers<T> : IComparer<KeyValuePair<int, T>> // Declares a generic type { public int Compare(KeyValuePair<int, T> x, KeyValuePair<int, T> y) { return x.Key.CompareTo(y.Key); } } Is it what you want? Update Given Chris Sinclair understanding of your question, the solution might be: public class BinarySearchComparers<U, T> : IComparer<KeyValuePair<U, T>> // Declares a generic type where U : IComparable<U> // Restricts the type U to implémentations of IComparable<U> (necessary to call CompareTo) { public int Compare(KeyValuePair<U, T> x, KeyValuePair<U, T> y) { return x.Key.CompareTo(y.Key); } }

Categories : C#

Can I pass a generic into a non-generic function once I've checked its type?
The fact that you check the dynamic type of the variable doesn't change its static type, and that what it's used to check the call. If you want to do that, you need a cast. You can use a checked cast to do it in one go: Enumerable ex = x as Enumerable; if (ex != null && !EnumerableContainsEnumerable(ex, b)) return false; The as operator checks whether the cast is possible: if it is it will return the casted object; if it is not, it will return null.

Categories : C#

Generic method without parameters
The compiler infers the type of T from the concrete type used on the LHS of the assignment. From this link: If the type parameter does not appear in the types of the method arguments, then the compiler cannot infer the type arguments by examining the types of the actual method arguments. If the type parameter appears in the method's return type, then the compiler takes a look at the context in which the return value is used. If the method call appears as the righthand side operand of an assignment, then the compiler tries to infer the method's type arguments from the static type of the lefthand side operand of the assignment. The example code in the link is similar to the one in your question: public final class Utilities { ... public static <T> HashSet&

Categories : Java

CodeType get generic parameters
I think the answer here is pretty definitive. This isn't supported by DTE or DTE2 and is unlikely to be supported in the future. The only way currently is to use Roslyn, which is not acceptable for those of us that don't want to use pre-release software. I also haven't looked into what kinds of dependencies that will entail (do users of my component need to install Roslyn?). You could use a regular expression to get the types from the FullName string. But, for those of us in the real world who need the token (T) to concrete type (System.String) mapping, this is not an option.

Categories : C#

Overriding methods containing generic parameters
Let me start with example: List<DoesStuff> a = new LinkedList<DoesStuff>; LinkedList<DoesStuff> b = new LinkedList<DoesMoreStuff>; //doesn't work. In the second example if it was legal, you would be able to add DoesStuff objects into list of DoesMoreStuff. The trick is in your DoesMoreStuff you have type Paramter E which is not used and you've already explicitly set type parameter and have these methods: public void MethodA(ArrayList<DoesMoreStuff.ElementA> moreElements) {} public void MethodB(ArrayList<DoesMoreStuff.ElementA> moreElements) {} you can't overide them like this as described in the example above @Override public void MethodA(ArrayList<E> moreElements) {} // as described in the example above Now coming to the third class: p

Categories : Java

Dynamic length of generic parameters
EDIT: This answer addresses the original question rather than the motivation behind it. In terms of passing work to a BackgroundWorker etc, using a lambda expression makes perfect sense. Now I've just wondered if there is a way to write this method without forcing a fixed size of parameters. Nope, I'm afraid not. What you're looking for is higher order types, I think1 - but they don't exist in .NET (which is why there are so many "generic arity overloads" for Func<>, Tuple<>, Action<> etc). 1 I don't know much about these things myself, to be honest. Joe Duffy has a blog post which blows my mind somewhat, but which may be useful.

Categories : C#

Generic Generator parameters in Hibernate cannot be set
You're using javax.persistence.Parameter instead of using org.hibernate.annotations.Parameter. Importing all classes from a package is generally considered as a bad practice. Only import the classes that you need.

Categories : Hibernate

Generic methods with delegate parameters
You might be confusing the return type with the proxy type. If you specify your argument as Func<T>, then T needs to be the return type of the function, not the proxy type. However, you also need to specify the proxy type, in order to get the proper service endpoint and channel factory. Thus, you actually need two type parameters: one for the proxy and one for the return type. I'm also assuming that the function delegate needs to take the initialized proxy as parameter; otherwise, this wrapper method would be pointless. public static TResult ExecuteAndReturn<TProxy, TResult>( Func<TProxy, TResult> delegateToExecute) { string endpointUri = ServiceEndpoints.GetServiceEndpoint(typeof(TProxy)); TResult valueToReturn; using (ChannelFactory<TProxy> fact

Categories : C#

Contravariance on constrained generic type parameters
Answer to initial question You're currently trying to convert a single element of type TDerived to a sequence of type Base. I wouldn't expect your Cast call to work either, as TDerived doesn't implement IEnumerable - I suspect you've actually got that to work in a different situation instead. I suspect you actually meant: void Test3<TDerived>(IEnumerable<TDerived> derived) where TDerived : Base { IEnumerable<Base> b = derived; } That compiles with no problems. Answer to edited question Okay, now we've got the real problem between two type parameters, the issue is that the compiler doesn't know that they're reference types - which is required for generic variance. You can fix that with a class constraint on TDerived: void Test3<TDerived, TBase>(IEnumerabl

Categories : C#

Generic Key Pool Factory setting parameters
You would be using constructor args. Here's an example lifted from Spring docs: <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg><ref bean="anotherExampleBean"/></constructor-arg> <constructor-arg><ref bean="yetAnotherBean"/></constructor-arg> <constructor-arg type="int"><value>1</value></constructor-arg> </bean>

Categories : Java

Casting Exceptions Using Generic Type Parameters: Right way to do it?
You are trying to recover runtime type information, so yes you'll need Class.cast or similar. As it stands your code can throw a ClassCastException at the caller of getException because you are catching and storing all Exceptions. You may find it better to remove the generics and have the caller use instanceof or similar.

Categories : Java

How do you call a generic method with out parameters by reflection?
You've passed parameters that will find M<T>(IEnumerable<int>, ref int). You need to find M(IEnumerable<T>, ref T) (the distinction between ref and out exists only in the C# language; reflection only has ref). I'm not sure how to pass that; you may need to loop through all methods to find it. On an unrelated note, you need to pass more BindingFlags: BindingFlags.Public | BindingFlags.Static

Categories : C#

resolving generic parameters in dependent classes
I can't get compiling instruction new ConcurrentHashMap<ProxyWeakReference<K>,V>();! Why you don't use full generics for ProxyWeakReference instead of a messy mix? You can resolve all errors and write a "correct" code. public class ProxyWeakReference<K> extends WeakReference<K>{ public ProxyWeakReference(K o, ReferenceQueue<K> q) { super(o,q); } } public class SafeQueueMap<K,V>{ ConcurrentMap<WeakReference<K>,V> d=new ConcurrentHashMap<WeakReference<K>, V>(); ReferenceQueue<K> refQueue=new ReferenceQueue<K>(); public void put(K k ,V v){ WeakReference<K> r=new ProxyWeakReference<K>(k,refQueue); d.put((ProxyWeakReference<K>) r,v); } } or you can u

Categories : Java

Generic way to set particular parameters of a polymorphic member variable
you want to use A's public interface to set derived class parameters: you can define a public function In A, which have a Base* parameter: class A { public: void setter(const Base *p); { m = p; } }; if you want to set Drived1 you can define a object of Derived1, can pass it to setter; I think you want to pass value using A's public function, you must know the type of pointer of Base*,so you can pass value by the constructor of Derived1 or Derived2!

Categories : C++

Polymorphic Type Parameters in Generic Collections
your question is very similar to mine: the answer is that you can't do that cast because thoose are diferent types create by a template class and they do not inherit. what you can do is: f(bL.Cast<A>());

Categories : C#

Using DynamicMethod to invoke a method with generic parameters?
I haven't used DynamicMethod myself like this, but I suspect you just need to MakeGenericMethod on this EnumerableOrderBy just like you're already doing for GetDefaultKeySelectorForProperty. At the moment you're trying to call the generic method without specifying any type arguments. So something like: MethodInfo EnumerableOrderBy = typeof(Enumerable).GetMethods() .Single(m => m.Name == "OrderBy" && m.GetParameters().Count() == 3) .MakeGenericMethod(typeof(T), propertyToSortOn.PropertyType); (MakeGenericMethod uses a parameter array, so you don't need to explicitly construct the Type[] to pass in.) (If you need to work with Entity Framework, I've have thought you'd be looking at Queryable rather than Enumerable and building expression trees instead of delegates, but

Categories : C#

Forcing Java generic parameters to be of the same type
You can force the parameters to be of the same type by doing the following: // the first class, A<K>: class A<K> { void f(K x) {} } // the second class, defining the method with generic type parameters class Test { <T> void foo(A<T> a, T x) { a.f(x); // now it works! } } // a third class, that uses the above two: class Main { public static void main(final String... args) { final Test test = new Test(); final A<String> a = new A<>(); test.foo(a, "bar"); } } What this does is: the method foo defines a generic type parameter T and uses it to enforce that the K type parameter of the class A must match the type of x, the second parameter of foo. You could even impose restrictions on <T> if you wish and if it makes sense f

Categories : Java

How to make a list of objects with generic type parameters
It's usually best to create an interface. I have interfaces on most of my generic classes, to use them without knowing the generic argument. interface IFoo { object UntypedBlah(object arg); } class Foo<T> : IFoo { object UntypedBlah(object arg) { return Blah((T)arg); } T Blah(T arg) { //... } } List<IFoo> foos = new List<IFoo>(); foos.Add(new Foo<int>()); foos.Add(new Foo<string>()); You could also make it covariant. (The interface would have a covariant generic argument. It depends on the members you need on the interface if this makes sense or not.) Instead of having "untyped" members, you could give them the same name and implement them explicitly. But sometimes you get into troubles when having complex interface and class hier

Categories : C#

Why C++14 Generic lambdas require auto in parameters specification?
The problem is that you are also allowed to leave out the parameter's name. If the compiler sees (a,b) and a and b are also valid types, what should that mean? (a /*dummy_a*/, b /*dummy_b*/) or (auto a, auto b)? With having to type auto explicitly, it is no longer ambiguous.

Categories : C++

Can you enforce the same constraint on multiple generic type parameters?
No, that is not supported. The C# language spec states Each type-parameter-constraint-clause consists of the token where, followed by the name of a type parameter, followed by a colon and the list of constraints for that type parameter. The key here is a, indicating that the grammer requires where <TypeParam> : <Constraint1>,<Constraint2>, etc.. .

Categories : C#

How two abstract the number of parameters of a function with type parameters in Scala?
You could use tupled method on function: new Wrapper(multiplyFunction.tupled). If you want to make this transparent to the wrapper class's user you could use duck typing: object Wrapper { def apply[I, O](e: { def tupled: I => O }) = new Wrapper(e.tupled) def apply[I, O](e: I => O) = new Wrapper(e) } scala> Wrapper( (a: Int) => a ) res0: Wrapper[Int,Int] = Wrapper@29d03e78 scala> Wrapper( (a: Int, b: Int) => a * b ) res1: Wrapper[(Int, Int),Int] = Wrapper@581cdfc2 You'll get some overhead due to reflection.

Categories : Scala

Determine if class is a subclass of a type with multiple generic parameters
You're looking for GetGenericTypeDefinition: typeof(BobGeneric).GetGenericTypeDefinition().IsSubclassOf(typeof(MyGenericClass<,>)).Dump(); You can imagine that method as "stripping away" all generic type arguments, just leaving the raw definition with its formal generic parameters. If it does not work directly on BobGeneric, you may have to navigate upwards in the type hierarchy till you find MyGenericClass<...,...> (or any type for which IsGenericType returns true).

Categories : C#

Function with a variable number of parameters without any explicit parameters
If you want to maintain some semblance of platform independence, you need at least one parameter and use the va_arg macros. If you know the low level details of the architecture and calling convention, then you can pull the arguments directly out of the registers and/or stack (depending on where the various parameters end up).

Categories : C++

R: wrapper function(fun, parameters) that calls fun with "unrolled" parameters
I think, you are looking for do.call for the construction of function calls. The function constructs the call and evaluates it immediately( You can also use call to construct the call and evaluates it later using eval for example). do.call takes the arguments from an object of mode "list" containing all the arguments of function to be evaluated. For example: do.call("mean", list(x=1:4,na.rm=TRUE)) is equivalent to : mean(x=1:4,na.rm=TRUE)

Categories : R

Conditional methods of Scala generic classess with restrictions for type parameters
In this case you can only use an implicit parameter, as the type gets determined before the method call. trait Col[T] extends Traversable[T] { def sum(implicit num: Numeric[T]) :T = ??? } If the method you are calling would be parameterized, you could use context bounds, which are just syntactic sugar for the implicit parameter bound to the type parameter: def foo[A](implicit ev: Something[A]) = ??? is equivalent to def foo[A : Something] = ???

Categories : Scala

Generic method named Max that takes 2 parameters and returns greater of 2 reference types
That's because the compiler does not know that the open type T has a property called Salary. You can either add a constraint to T that it needs to be a derived class of Employee or you need to call the Maximum function with the salaries instead of the employee instances. public static T Maximum<T>(T emp1, T emp2) where T: Employee { if (emp1.Salary >= emp2.Salary) { return emp1; } else { return emp2; } } Just to elaborate on the question, a generic function only constraining on reference type like static T Maximum<T>(T obj1, T obj2) where T : class { if (obj1 > obj2) { return obj1; } return obj2; } does not work as the > operator is not defined on T. Your best chance is to check if the input objects

Categories : C#

Use the parameters of a function that takes any number of parameters, in C
The second version does NOT accept a variable number of parameters, it accepts a fixed (but unspecified) sequence of parameters. In effect, it declares the function, but does not prototype the function. So calls to the function will not be checked for valid types. It's common for the compiler to look at the first call to the function and check other calls against the types found in the first call. This is why, if you omit #include <stdio.h>, the first call to printf will be acceptable, but any calls to printf with different types will generate an error. Eg. int main() { printf("hello"); //<--- accepted, compiler may assume `int printf(char *);` printf("%s", "world"); //<--- error, type mismatch } To have a function accept a variable number, it must have at l

Categories : C

How does wrapping a function pointer and function object work in generic code?
C++11 offers an std::function template. You don't have to mess with function pointers. You can pass those by reference, copy them, move them and they can even be used to store lambdas: std::function<void()> func = []() { std::cout << "Hi" << std::endl; };

Categories : C++

Solved: Scala: How to write a generic check function that evaluates any function that returns boolean?
If your input functions only have 2 arguments, like your two examples, you can write a semi generic function take takes all functions with two arguments of any type: def eval[A,B](func: (A,B) => Boolean, arg1: A, arg2: B) = { func(arg1, arg2) } def checkLength(str: String, length: Int) : Boolean = { str.length == length } eval(checkLength, "ham", 4) res0: Boolean = false But if you want to support functions with more arguments, you would have to write one eval function for three arguments, four arguments, etc Maybe there is a better way that can handle all cases?

Categories : Function

Specializing class for generic function returning pointer to function
I believe this will work if you specialize it as: template<typename FpResultType, typename FpArg1, typename Arg1, typename Arg2> A<ResultType (*(Arg1, Arg2))(FpArg1)> {...}; I tested with the following code, which compiles successfully (using Clang): template<typename T> class A; template<typename FnRetT, typename FnArgT, typename Arg1, typename Arg2> class A<FnRetT (*(Arg1, Arg2))(FnArgT)> { public: typedef FnRetT fn_ret_t; }; float foo(float a) { return a; } float (*getfn(int arg1, int arg2))(float) { return foo; } int main(int argc, const char * argv[]) { typedef A<decltype(getfn)>::fn_ret_t ret_ty; return 0; } Note that the syntax used to match the function type matches the declaration of getfn.

Categories : C++

when javascript function alter html input text ,I want the input text trigger a event like calling other JS function
You can call it yourself. var counter = 0; function AlterText(){ counter=counter +1; document.getElementById('txtbox1').value = counter; AlertMe.call(document.getElementById('txtbox1')); } function AlertMe(){ alert("Done!.."); }

Categories : Javascript

generic form validation based on the input name or id
See the jQuery Validation docs: http://jqueryvalidation.org/Validator.element You can set up your rules for the form, since jQuery validation only validates forms, then validate individual elements when you need to: Example from the docs: var validator = $( "form" ).validate({/*your rules*/}); validator.element( "#email" );

Categories : Jquery

Generic xsd validation and xml for input and output pairing
When you define your XML at a very high level of abstraction, by making it very generic instead of specific to your task, it becomes difficult (and sometimes impossible) to make it enforce constraints that apply at a lower level of abstraction. The constraints at the lower level of abstraction can be enforced only if the system knows about the details at that level of abstraction, and the vocabulary can be defined at a high level of abstraction only by glossing over those lower-level details. This is not unique to XML; any system that allows you to choose your own level of abstraction will exhibit the same phenomenon. I do not believe there is a generic solution to this class of problem.

Categories : Java

Generic Type x Generic Parameter: Building a "very generic" structure
Well, first of all, you're overcomplicating this. All you really need to do is: public void add(final Tree<? extends T> subTree) { Theres no need to parameterize add(). But anyways, I'll address your original attempt: You want SubTree extends Tree<Leaf>, because even if Leaf extends T you can't guarantee that SubTree extends Tree<T> with SubTree<Leaf> matches. E.g. if your class hierarchy is: public class Base { } public class A extends Base { } public class B extends Base { } If Leaf is A and SubTree is Tree<B> then add (final SubTree<Leaf>) does not match Tree<B>. So conceptually you actually want this: public <Leaf extends T, SubTree extends Tree<Leaf>> void add(final SubTree<Leaf> subTree) { Of course that is not va

Categories : Java

DurandalJs: A generic solution to put focus to the first input element on the composed view
Enclose your view's html inside a root section or div. add data-bind="focusFirstEditable: true" to this root element. Create a custom binding handler by that name and put your logic to look for the first element that is editable and set the focus in the init of your custom bindingHandler. Add your custom binding handler to composition.addHandler(yourCustomBindingHandler). This will create a lazy binding that will happen after your compose is complete and it is centralized. whichever view you want this to happen, just add it to the root element.

Categories : Javascript

How to send two generic parameters in Messenger.Default.Send
Please take a look at the Tuple Class page on MSDN. A Tuple is a generic holder of data... You can use it like this: Tuple<int, TransportOrder> data = new Tuple<int, TransportOrder>(toTempId, to); They are very useful 'containers' and can take up to 8 input parameters. You can then access the values at the other end, like this: int toTempId = data.Item1; TransportOrder to = data.Item2;

Categories : C#



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