You need to use a type parameter to say that two 'unknown' types are the same. I thought that maybe you should change your method signature from: static <T> void sort(List<T> data, final Key<T, ?> key[], final int dir[]) to static <T,U> void sort(List<T> data, final Key<T,U> key[], final int...
javascript,arrays,types,type-conversion
Should be straight forward, just iterate and split on the colon var A = ['"age":"20"','"name":"John"','"email":"[email protected]"']; var O = {}; A.forEach(function(item) { var parts = item.split(':').map(function(x) { return x.trim().replace(/\"/g,'') }); O[parts[0]] = parts[1]; }); document.body.innerHTML = '<pre>' + JSON.stringify(O, null, 4) + '</pre>'; ...
This has nothing to do with the Add-Type cmdlet in particular; it applies to all PowerShell types: PS > (1).GetType().Name Int32 PS > [int].GetType().Name RuntimeType Things like (new-object MyTest) and 1 are instances of specific types. Calling .GetType() on them is returning the type of those instances. Things like [MyTest]...
javascript,types,ternary-operator
"0" is a string of length>0 which is true. Try 0 ? 8 : 10 and see. It will return 10. == does type conversion and hence when you do "0" == false it returns true. When you do 0 == "0" //true It also returns true as again type...
c#,generics,types,stream,buffer
return (TValue)buffer; // here's where I'm stuck Yes, you have just shifted the problem. From not having a Stream.Read<T>() to not having a Convert<T>(byte[]) in the std library. And you would have to call it like Read<int>() anyway so there isn't a direct advantage over BinaryReader.ReadInt32() Now when you want...
OK I seem to have figured it out myself now.... Firstly, I was using the wrong test in checking for GTYPE_TO_POINTER and GPOINTER_TO_GTYPE since they were the variables I wanted to define the compiler could not find them and the definition was never being made. Secondly, I was using undefined...
Use remove_reference: #include <string> #include <iostream> #include <type_traits> using namespace std; int main() { int const x = 50; int const& y = x; cout << std::is_const<std::remove_reference<decltype(x)>::type>::value << endl; // 1 cout << std::is_const<std::remove_reference<decltype(y)>::type>::value << endl; // 1 return 0; } See on coliru...
ok this will work: average :: Integral a => [a] -> a average ns = sum ns `div` (fromIntegral $ length ns) please note that div :: Integral a => a -> a -> a so you need Integral a instead of just Num a (which has no division) And...
I am not ready to give a nice list of best practises, but for starters if you want to keep stuff sanely organized, use explicit exports instead of just exporting everything, e.g: module Parser ( parseConfig ) where ... Explicit exports also allow you to reexport your imports, e.g. module...
algorithm,haskell,types,type-inference,type-systems
You cannot remove Ord since you are using functions like < and > and operating them on polymorphic type. See their type: λ> :t (<) (<) :: Ord a => a -> a -> Bool But if you instead limit your polymorphic code to operate only on Int or any...
The ScopedTypeVariables extension solves exactly your problem. The page also provides some alternative solutions (asTypeOf and undefined arguments).
java,eclipse,types,classpath,derby
As politely as I can, may I suggest that if you are uncomfortable with Java's CLASSPATH notion, then writing your own custom data types in Derby is likely to be a challenging project? In the specific case you describe here, one issue that will arise is that your custom Java...
indexing,types,integer,type-conversion,ada
type index is new Integer range 1..50; type table is new Array(index) of expression; You don't need (and can't have) the new keyword in the declaration of table. c: Character; get(c); s: String := " "; s(1) := c; The last two lines can be written as: S: String :=...
c,gcc,memory,types,compiler-optimization
In most cases, there won't be any memory usage difference because i will never be in memory. i will be stored in a CPU register, and you can't really use one register to store two variables. So i will take one register, uint8 or uint32 doesn't matter. In some rare...
First check out all the great answers here. type() simply returns the type of an object. Whereas, isinstance(): Returns true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. Example: class MyString(str): pass my_str = MyString() if type(my_str) ==...
The tai parameter is fixed to Double because of your datatype. Change it to data Method a = Ndiv Int | Size a for example, then your function should typecheck, although you'll need a stronger constraint than Num, as cieling requires RealFrac. The type will be function :: RealFrac a...
From the MSDN docs: A TypeInfo object represents the type definition itself, whereas a Type object represents a reference to the type definition. Getting a TypeInfo object forces the assembly that contains that type to load. In comparison, you can manipulate Type objects without necessarily requiring the runtime to load...
haskell,types,monoids,type-variables,foldable
I found that this typechecks: {-# LANGUAGE RankNTypes #-} module FoldableTA where import Control.Category import Prelude hiding (id, (.)) class FoldableTA fm where foldMapTA :: Category h => (forall b c . a b c -> h b c) -> fm a b d -> h b d foldrTA ::...
This can happen if you're using type declaration on numeric types. If you do something like this: type T int64 ... var value interface{} = T(1) and put it into your code, you'll get the exact same error. But if you don't check the kind, but the type, you'll see...
collections,types,drools,rules,declare
Since ArrayList is a generic collection, Gson is not able to correctly identify the type of the address object when processing the JSON string. The easiest way to accomplish what you are trying to do would be to use an array instead of a ArrayList: declare Person firstName : String...
This is a partial answer, written for Scala but applicable to other languages. A bug is something happening which was not expected. Thus, to solve bugs, the language should allow to let the user write any expectations and interact with them (proof, synthesis, etc.). There are several ways to address...
Java's generics don't actually change the underlying class or object, they just provide (mostly) compile-time semantics around them. By passing an ArrayList<Integer> into a method expecting an ArrayList (which can hold anything), you're bypassing the compiler's ability to provide you with that type safety. The Java Generics Tutorial explains this,...
types,mapping,logstash,kibana,grok
It's quite possible that Logstash is doing the right thing here (your configuration looks correct), but how Elasticsearch maps the fields is another matter. If a field in an Elasticsearch document at some point has been dynamically mapped as a string, subsequent documents added to the same index will also...
The float val is stored as 307.02999 or something like that intval just truncate the number, no rounding, hence 30702.
scala,generics,types,implicit-conversion
You've just told the compiler that types passed to your class as T and S should be equal - you just require an evidence of their equality, which can be used to infer actual T and S correctly when you pass actual types (but not inside generic class itself). It...
types,typescript,typescript1.4
You will need to do some type checking and casting to handle this scenario: (member: resources.IMember) => { return member.user.id == user.id; if (typeof (member.user) === 'number') { return member.user == user.id; } else { return (<ISimpleUser>member.user).id == user.id; } }).length > 0; Just because you know the possible types...
IQueryable q = ...; if (q.ElementType.GetProperty("PropertyName").PropertyType == typeof(int)) { // PropertyName is an integer property . . . } ...
[MyAttribute(new OtherType(TestEnum.EnumValue1))] That's not valid, you have to have a constant in attribute constructors. That matter aside, most of this is easy, if rather long-winded. You can call typeof(MyClass).CustomAttributes.Select(ca => ca.AttributeType) to get the types of attributes, typeof(MyClass).GetFields().Select(fi => fi.FieldType) to get the types of fields, and so on. Union...
mysql,sql,types,go,custom-type
You implement the Valuer interface for your StatusEnum type as operating on a *StatusEnum. Therefore when you pass one as a parameter to Exec it only makes sense as a pointer as only pointers to StatusEnum implement Value(), requiring a deference inline. You don't have a definition for the EmailList...
java,types,parametric-polymorphism,java-generics
public class LogBookRecord<Long, String> extends Pair<Long, String>{ ^ ^ | | generic type variable declaration (new type names) | generic type arguments That code is equivalent to public class LogBookRecord<T, R> extends Pair<T, R>{ You've simply shadowed the names Long and String with your own type variable names. Since T...
scala,generics,types,typeclass,type-parameter
You can provide an implicit function with the required type: implicit def SeqMonoid[T]: Monoid[Seq[T]] = new Monoid[Seq[T]] { override def op(a: Seq[T], b: Seq[T]): Seq[T] = a ++ b override def id: Seq[T] = Nil } ...
python,multidimensional-array,types
First of all, many unumpy objects are basically numpy arrays: >>>arr = unp.uarray([1, 2], [0.01, 0.002]) >>>arr [1.0+/-0.01 2.0+/-0.002] >>>type(arr) <type 'numpy.ndarray'> so you should not be surprised. By the way, ufloat is a function and not a type: >>>x = ufloat(0.20, 0.01) # x = 0.20+/-0.01 >>>print type(x) <class...
You can use std::iterator_traits::value_type: typedef typename std::iterator_traits<Iter>::value_type value_type; As for the function declaration and definition, in old-school C++03 style you could do the following: template<typename Iter> std::pair<typename std::iterator_traits<Iter>::value_type, typename std::iterator_traits<Iter>::value_type> summean(Iter first1, Iter last1) { typedef typename std::iterator_traits<Iter>::value_type value_type; value_type sum = std::accumulate(first1, last1,...
The reason why this has been done in the past is portability. C and C++ do not make specific guarantees of the size of int, long and short, while library designers often require it. A common solution is to define their own aliases for data types, and changing the definitions...
You should always pass an integer. HttpResponse('401 Client Error', status=401) As per the HTTP protocol: The Status-Code element is a 3-digit integer result code of the attempt to understand and satisfy the request. ...
The problem with your code is that you have a coherence violation in it, and, very likely, any attempts to fix it would lead to new coherence violations. Coherence rules in Rust are somewhat complex, however, they are based on one principle: you can implement "your" traits for arbitrary types...
c,pointers,types,pointer-arithmetic
Incrementing a pointer adds to the memory address the size of the thing the pointer points to. If d is of type int***, it is a pointer to int**. ++d will cause the pointer to move over sizeof(int**) bytes and sizeof(int**) is 4 because it is a pointer. So if...
This is F#'s embarrassing skeleton in the closet. Try this: > let mapPair f (x,y) = (f x, f y) val mapPair : f:('a -> 'b) -> x:'a * y:'a -> 'b * 'b Fully generic! Clearly, function application and tuples work. Now try this: > let makeList a b...
types,f#,typeerror,discriminated-union
Your error is caused by the fact, that each evaluation that execute in the FSI actually creates a dynamic assembly FSI_XXXX. So in fact, your function that you defined with ExprTree was maybe referring to FSI_0051.ExprTree whereas a function that you defined later and used ExprTree is now referring to...
c++,arrays,types,iterator,declaration
std::iterator is meant to be used as a base class. From 24.4.2/1: namespace std { template<class Category, class T, class Distance = ptrdiff_t, class Pointer = T*, class Reference = T&> struct iterator { typedef T value_type; typedef Distance difference_type; typedef Pointer pointer; typedef Reference reference; typedef Category iterator_category; };...
It happens because JwtSessionHandler expects lookupByUsername function with only one parameter, not lookupByUsernamePassword which has two.
types,julia-lang,type-parameter
It is currently not possible to restrict type parameters like this, though there has been discussion to allow the syntax that you tried up at the top. I believe that the solution that you came up with of checking the type parameter in an inner constructor is considered the best...
javascript,node.js,types,sequelize.js
Well, the error is pretty obvious. One of the arguments is not a string. The first one appears to be a number. Just convert it to a string first, e.g. via String: path.join(a, String(b)); ...
I suggest that this really isn't the way you should design your tables in the database. Since you're using a relational database, I recommend designing your tables like this: For your first table, have columns id fullName cell Then, create another table named items with columns id table_1_id item. When...
This is a complete example of a C program that passes a struct to Haskell then Haskell mutates the values of that struct. It has no outside dependencies. You should be able to copy the code and run it if you have GHC. Hopefully this will serve as a simple,...
class,haskell,opengl,types,uniform
Try adding -XFlexibleContexts and the constraint, literally, to your existing answer: {-# LANGUAGE FlexibleContexts #-} mvpUnif :: ( GL.UniformComponent a , Num a , Epsilon a , Floating a , AsUniform a , AsUniform (V4 (V4 a)) ) => (GLState a) -> ShaderProgram -> IO () Usually this is the...
as the return will wrap it into some monad, you can then get to the parts by deconstructing it directly inside a do block like this: do (b,c) <- solve x y ...
recursion,types,julia-lang,type-alias
Dose this work for what you are doing? typealias NestedTuple0{N,T} Tuple{Union(T,N),Union(T,N)} typealias NestedTuple{T} NestedTuple0{NestedTuple0{T},T} Note: I am only able to try this in 036, not 04 An exmple of use: function rnt(p) np = 0.95*p a=rand() <p ? rnt(np) : 1 b=rand() <p ? rnt(np) : 2 (a,b) end x=rnt(1.0)...
as far as i know, one solution would be to is to create another table of type B_products and use, a value from main product as foreign key, in table 2. So hence you can link both tables, instead of creating a table inside a table. I think this is...
You'll need a type parameter for the Collection element type, potentially a type parameter for the actual Collection type if you need it, and a type parameter for the values. class SubClass<E, K extends Collection<E>, V> implements Map<K, V> { ... } If you don't need the specific Collection type,...
If I understand your question correctly, you want this: x(10, "x"); to fail at compile time. Now consider doing this: Integer i = 10; String s = "x"; Object o1 = i; Object o2 = s; x(o1, o2); In this case they are both objects - the same type. I...
You could try union - as long as you make sure the types are identical in memory sizes: union convertor { int asInt; float asFloat; }; Then you can assign your int to asFloat (or the other way around if you want to). I use it a lot when I...
1 is a polymorphic value of type Num a => a. So in [1, [2, 3]], we have [2, 3] :: Num a => [a]; since all list elements must have the same type, we conclude that we must have 1 :: Num a => [a]. That's a bit weird...
You can use as to "cast" in Dart. import 'dart:html'; ... if((querySelector('#username') as InputElement).value!="") ...
Yes, you can use value classes: case class VertexId(val id: Long) extends AnyVal case class VertexLabel(val label: Long) extends AnyVal see http://docs.scala-lang.org/overviews/core/value-classes.html...
The Java Language Specification says that the wrapper objects for at least -128 to 127 are cached and reused by Integer.valueOf(), which is implicitly used by the autoboxing.
The following code is more efficient: unsigned char[word_size] = ...; int64_t num = 0; for ( int i = 0 ; i < sizeof(a) ; i++ ) num = (num << 8) | a[i]; This assumes big endian (highest order byte first) ordering of the bytes in the array. For...
The compiler sees the T2 and T identifiers and helpfully informs you that those types seem unrelated. That's absolutely correct, as they have no relation: there are no generic constraints that would assert any relations between them (I'm not saying that would be useful here though :) ). Whether this...
c#,sql-server,database,types,sqldatareader
Like the error says, you can cast to ushort: ID = (ushort) reader.GetInt16(2); ...
Don't you mean...? instance (GDefault a, GDefault b) => GDefault (a :+: b) where ... -- ^ ^ ...
The reason for the error is that decode does not always succeed. Its type is decode :: Data a => ByteString -> Maybe a Correspondingly, (decode <$>) :: Data a => IO ByteString -> IO (Maybe a) -- desired type, IO Temperatures, won't unify The type error message gives you...
Your type CT32 is a Discriminated union with one case identifier CT32 of float. It's not an alias to float type so you couldn't just cast it to float. To extract the value from it you can use pattern matching (this is the easiest way). type CT32 = CT32 of...
The right way in go to implement a stack is simply to use a slice. stack := []*HuffmanTree{} You can push to the stack using append, and pop by writing: v, stack := stack[len(stack)-1], stack[:len(stack)-1] You could encapsulate it into its own type if you prefer, but a slice is...
There are some scenarios in which Java can't handle the type inference all that well (when one thinks it should). This is one of those scenarios. If you explicitly pass the type to the new invocation, it will compile: Foo<String>.Bar fooBar2 = new Foo<String>().new Bar(); ...
From cppreference: An enumeration is a distinct type whose value is restricted to one of several explicitly named constants ("enumerators"). The values of the constants are values of an integral type known as the underlying type of the enumeration. So an example of an enumerated type is any type you...
java,sql-server,jdbc,types,data-type-conversion
You can call getBoolean directly and let it take care of all the casting/coverting: result.add(rs.getBoolean("columnName")); ...
mysql,types,data-type-conversion
Try this SELECT CONV( BINARY( '100101' ) , 2, 10 ) It will do the trick. I was inspired by Convert a binary to decimal using MySQL EDIT In fact you can make it even more simple by using just CONV SELECT CONV( '100101' , 2, 10 ) See http://dev.mysql.com/doc/refman/5.5/en/mathematical-functions.html#function_conv...
types,polymorphism,ocaml,record
Try type ('a,'b) item = { name:string; quantity:'a; price:'b };; As you can guess, you need to mention every type variable on the left-hand side. You did it for 'a, it's only natural to do it for 'b as well....
javascript,audio,types,web-audio
I think the issue here is that you're accessing file.length, while file is a Stream object which I don't think have a length property. So what you're doing is basically saying new Int16Array(undefined); and hence the type error. fs.createReadStream is documented here; https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options You can use the Stream object to...
Neo4j uses java primitive types, Strings or arrays of those for property values. There is no date type. So "2015-0104T10:33:44" is a String. Cypher provides couple of functions for type conversion like toFloat, toInt, ... that might help you here. Most folks store millis since epoch for date and time...
Try HINSTANCE hInstLibrary = LoadLibrary(L"DLL_tut.dll"); or HINSTANCE hInstLibrary = LoadLibrary(_TEXT("DLL_tut.dll")); The thing is that your project is probably compiled with UNICODE macro defined, which causes LoadLibrary to use LoadLibraryW version, which requires Unicode string as a parameter. ...
UILabel, UITextView ... are defined in the UIKit framework, therefore you have to #import <UIKit/UIKit.h> (which then implicitly imports Foundation). You can also use the more modern "module" syntax: @import UIKit; ...
I'd use an off the shelf generic linked list. I'm sure Spring has some, but if you don't want to take on all the dependencies that would entail you could use Chris Rolliston's simple linked list: https://code.google.com/p/ccr-exif/source/browse/blogstuff/CCR.SimpleLinkedList.pas?r=34 Then you just need to decide on the type of the payload. Use...
list,haskell,types,existential-type,heterogeneous
This will work for arbitrarily nested lists of strings with a few extension tricks: {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE OverloadedLists #-} import GHC.Exts import Data.String data MyStringListThingy = String String | List [MyStringListThingy] deriving (Eq, Show) instance IsString MyStringListThingy where fromString = String instance IsList...
You're reading in a String, but want to save it as Integer/Double. Try this: int num1 = Integer.valueOf(scan.nextLine()); Same goes for Double. Or as OldCurmudgeon mentioned: int num1 = scan.nextInt(); ...
Since you've grouped by the datatype of ?o, you know that all the ?o values in a group have the same datatype. You can just sample that to get one of those values, and then take the datatype of it: select (datatype(sample(?o)) as ?datatype) (count(?o) AS ?dTypeCount) where { ?s...
you have to move fac one in: mo08 f = \xx -> fac (if f (xx) then xx else xx * xx) or (if you like) move the xx to the left of the =: mo08 f xx = fac $ if f (xx) then xx else xx * xx...
Your main method located at the top of your class: public static void main(String[] args) { Is never closed, you should do something like this: public static void main(String[] args) { } Now your error should be resolved but without something inside your main method your code will probably not...
haskell,types,binding,dependent-type
The type you suggest can not be implemented, i.e. it is not inhabited: takeWhileVector :: (a -> Bool) -> Vector a n -> Vector a m Remember that the caller chooses the type variables a,n,m. This means that the caller can use your function as e.g. takeWhileVector :: (a ->...
arrays,stored-procedures,types,db2,row
You need to declare a temporary variable of the row type and assign array elements to it in a loop: CREATE OR REPLACE PROCEDURE TEST_ARRAY (IN P_ACCT_ARR ACCT_ARR) P1: BEGIN DECLARE i INTEGER; DECLARE v_acct acct; SET i = 1; WHILE i < CARDINALITY(p_acct_arr) DO SET v_acct = p_acct_arr[i]; CALL...
debugging,generics,types,compiler-errors
Imagine this scenario: public class Bob(){} public Class Tom(){} List list = new List(); list.Add(new Bob()); list.Add(new Tom()); Tom tom = (Tom)list[0]; //oops wrong index This will fail, but only at run time as a Bob isn't a Tom List<Bob> list = new List<Bob>(); list.Add(new Bob()); Tom tom = list[0];...
ios,objective-c,memory,types,casting
Your problem is that you're using a constant string. This is put straight into the programs memory so the reference is unexpectedly remaining valid despite the fact that it shouldn't. Use something less constant than a constant string and your program will brake like you think.
You can do : String type = scanner.next(); EmployeeType enumType = EmployeeType.valueOf(type); ...
The error message is wrong. The problem is that you are trying to multiply an Int and a CGFloat. Replace: innerY = innerY - CGFloat(gridHeight * row) with: innerY = innerY - gridHeight * CGFloat(row) The answer above is for the current version of your code. For the commented out...
The first argument of apply must be a matrix-like object (i.e., a matrix, array or data.frame). Otherwise you get this error: apply(1, 1, mean) #Error in apply(1, 1, mean) : dim(X) must have a positive length You are passing a list to apply, which can't work because you tell apply...
c#,memory-management,types,type-conversion,dllimport
It should be something like: IntPtr di; int result = afc_read_directory(client, @"C:\", out di); if (di == IntPtr.Zero) { throw new Exception(); } IntPtr di2 = di; while (true) { IntPtr ptr = Marshal.ReadIntPtr(di2); if (ptr == IntPtr.Zero) { break; } string str = Marshal.PtrToStringAnsi(ptr); if (str == string.Empty) {...
python,dictionary,pandas,types
You could use df.select_dtypes: In [58]: df = pd.DataFrame({'foo':[1,2,3], 'bar':['a','b','c'], 'baz':[1.2,3.4,5.6]}) In [59]: df.select_dtypes(exclude=[np.number]) Out[59]: bar 0 a 1 b 2 c The keys in col_dataType are of type numpy.dtype, not strings: In [67]: [type(item) for item in col_dataType.keys()] Out[67]: [numpy.dtype, numpy.dtype, numpy.dtype] So In [68]: col_dataType[np.dtype('O')] Out[68]: ['bar'] works,...
c#,generics,types,.net-4.0,value-type
The reason you get an error for GetSize(int) is that int is not a value. You need to use typeof like so: GetSize(typeof(int)), or if you have an instance then: GetSize(myInt.GetType()).
swift,types,init,lazy-initialization
I found two ways to get rid of this error. First, explicitly annotate the property with its type. I find this very strange because Swift is supposed to just infer this from the initialization. lazy var embeddedViewController: CustomViewController = CustomViewController() The second is just to remove the lazy keyword. var...
No, there's no need, the JavaDoc tool parses the Java code and gets the types from there. This article on the Oracle Java site may be useful: How to Write Doc Comments for the Javadoc Tool From the @param part of that article: The @param tag is followed by the...
types,module,encapsulation,coq
Yes. You can define your type inside a module and assign a module type to it: Module Type FOO. Variable t : Type. End FOO. Module Foo : FOO. Inductive typ := | T : typ. Definition t := typ. End Foo. (* This fails *) Check Foo.T. Another possibility...
c#,types,resharper,hierarchy,inspect
Not sure under what circumstances you're getting ReSharper to show types, but the rule of thumb is that the default search scope for Find Usages or Go To Derived Type, etc. is solution scope. So ReSharper will only show usages and derived types that are defined in the current solution....
The return type is a pointer to const pointer to int. Read the declaration from right to left, and it will make things much easier. My favourite tutorial for complicated pointer declarations: http://c-faq.com/decl/spiral.anderson.html Some (quite artificial) example: #include <iostream> int* const * foo(int x) { static int* const p =...