w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
C Casting a variable of type double to a variable of type char when freeing memory
I have to agree with you - that code is a bit weird. There's no reason the author couldn't have used void ** just as easily. In addition, the if (*ptr != NULL) check is unnecessary, since free(NULL) is perfectly legal. The ; characters after the braces aren't necessary either. A simpler version might look like this: static void free_and_null(void **ptr) { free(*ptr); *ptr = NULL; } The reason this function exists at all is to make sure that freed pointers are set to NULL, which is helpful for detecting use-after-free bugs and avoiding double-free bugs entirely. Edit: As StarPilot suggests below, it's probably a good idea to check that ptr itself isn't NULL: static void free_and_null(void **ptr) { if (ptr) { free(*ptr); *ptr = NULL; } }

Categories : C

Use Converted string to class type for casting
//Use this Dictionary to pair the view types and their corresponding ColorEach to set accordingly Dictionary<Type,bool> colorEaches = new Dictionary<Type,bool>(); colorEaches[typeof(DevExpress.XtraCharts.BarDrawOptions)] = true; colorEaches[typeof(DevExpress.XtraCharts.StackedBarSeriesView)] = true; //..... bool value; Type viewType = sser.View.GetType(); if(colorEaches.TryGetValue(viewType,out value)){ //Suppose your `ColorEach` should be present in all the types added to the Dictionary viewType.GetProperty("ColorEach").SetValue(sser.View, value); }else { //your own code }

Categories : C#

Structural-type casting does not work with String?
Yes, the String is a Java class and doesn't have the mkString method without a little help. It is a limitation of running in the JVM and using it's native String class for speed and compatibility with Java code. The mkString is added to the String on demand, using an implicit conversion to the StringOps. When you cast the name into HasMkString the String->StringOps implicit conversion no longer apply and so you lose all the extra methods. The workaround would be either to replace def f (name: HasMkString) = name.mkString ("-") with def f (name: HasMkString) = if (name.isInstanceOf[String]) name.asInstanceOf[String].mkString ("-") else name.mkString ("-") or not to throw away the type information by explicitly casting to a structural type, e.g def f (name: HasMkString) = name.

Categories : Scala

Python value conversion to string representation of postgres procedure parameter including type casting
''' >>> py_to_pg([1,2,3]) "'{1,2,3}'::int[]" >>> py_to_pg('Jack Johnson') "'Jack Johnson'::text" >>> py_to_pg([decimal.Decimal(0.3),decimal.Decimal(0.3),decimal.Decimal(0.4)]) "'{0.3,0.3,0.4}'::numeric(5,4)[];" >>> py_to_pg(datetime.datetime(2013,7,7,13,0,0)) "'2013-07-07T13:00:00'::timestamp" >>> py_to_pg(float(0.5)) "0.5::numeric" >>> py_to_pg(5) "5::int" >>> py_to_pg(['a','b','c']) "'{a,b,c}'::text[]" >>> py_to_pg(None) "'NULL'" >>> py_to_pg(33.00) "'33.0000'::numeric(5,4)" >>> py_to_pg(True) "'T'" ''' def py_to_pg(pyval): # set precision to 4 decimals out getcontext().prec = 4 t2t = {int: "'%s'::int",

Categories : Python

How to pass a Range type value to a String Type variable
You don't need to conver the Range to a string, you need to use its address property, which is already a string Sub SelectRange() Dim Rng1 As Range Set Rng1 = Application.InputBox("select cell", Type:=8) MsgBox ("You selected " & Rng1.Address & "as the range") End Sub

Categories : String

How Generics allows strong type checking for Type Casting errors during Compile Time
JPA makes use of generics in TypedQuerys to ensure that the expected type is returned. If you ask for a Customer, the type system knows to treat the results of the query as Customer objects and not as a plain Object you have to cast yourself, and if you use the Criteria API, it can also verify that your query parameters refer to valid attributes of the Customer class.

Categories : Java

Convert String to Type, where Type is a variable
change Type propertyType = property.GetType(); to Type propertyType = property.PropertyType; Using GetType(), you get the type of property. And property is an instance of PropertyInfo.

Categories : C#

Does type erasure of Java Generics cause full type casting?
The type-checking is done at compile-time. If you do this: List<Cheesecake> list = new ArrayList<Cheesecake>(); then the generic types can be checked at compile-time. This erases to: List list = new ArrayList(); which is no different to any other up-cast (e.g. Object o = new Integer(5);).

Categories : Java

How to I check whether a given variable value is of type string
Most types has a predicate in CL and even if a string is a sequence of chars it exists a function, stringp, that does exactly what you want. (stringp "getlydownthestream") ; ==> T It says in the documentation that that would be the same as writing (typep "ifyouseeacrocodile" 'string) ; ==> T

Categories : String

Type casting using type parameter
That's what a ClassTag if for: import reflect.ClassTag def convert[T : ClassTag](key: String): Option[T] = { val ct = implicitly[ClassTag[T]] someJavaMethod(key) match { case ct(x) => Some(x) case _ => None } } It can be used as an extractor to test and cast to the proper type at the same time. Example: scala> def someJavaMethod(s: String): AnyRef = "e" someJavaMethod: (s: String)AnyRef [...] scala> convert[Int]("key") res4: Option[Int] = None scala> convert[String]("key") res5: Option[String] = Some(e) Edit: note however that a ClassTag does not automatically unbox boxed primitives. So, for example, convert[Int]("a") would never work, because the java method returns AnyRef, it would have to be convert[java.lang.Integer]("a"), and so on for other pri

Categories : Scala

Best way to assign database value to a String type variable?
Your code will not work since myDataRow("column1") is not Nothing but DBNull.Value. I would use the strongly typed Field extension method which also supports nullable types; Dim string1 = If(myDataRow.Field(Of String)("column1"), "") If you want to use the old way: Dim string1 = If(myDataRow.IsNull("column1"), "", DirectCast(myDataRow("column1"), String))

Categories : Dotnet

How can I deserialize a JSON string into a class with a variable having a different type?
A simple adjustment would be to use dictionaries like this: public class Answer { public bool Correct { get; set; } public bool Response { get; set; } public Dictionary<string, string> Text { get; set; } public string ImageFile { get; set; } public Dictionary<string, string> Explanation { get; set; } } Deserialize and access the values like this; var answers = JsonConvert.DeserializeObject<List<Answer>>(detailsJSON); foreach (var answer in answers) { Console.WriteLine(answer.Text["TextWithHtml"]); Console.WriteLine(answer.Explanation["TextWithHtml"]); }

Categories : C#

Confused with the following type casting in c#
Because D is not derived from B. Hell, even if it was, you could only go from D to B, not the other way. This is because they are completely separate classes. The fact that they have the exact same properties (none) changed nothing.

Categories : C#

Casting to generic type in C#
I would personally recommend encapsulating your access to the dictionary with a separate singleton class that then wraps your dictionary getters and setters, something like a RepositoryStore class. I'd recommend changing Dictionary<Type, Type> to Dictionary<Type, object>, and then handle the casting within the RepositoryStore; something like so? Update (using Types and Lazy<T>) If you're using .NET 4, you could take full advantage of the Lazy class, and change the dictionary type to be IDictionary<Type, Lazy<object>>. I've amended my original answer to reflect how this might work: class RepositoryStore { private IDictionary<Type, Lazy<object>> Repositories { get; set; } public RepositoryStore() { this.Repositories = new Dic

Categories : C#

Better ways for type casting in C#
Case 1 - both ways are equal, 1st way being little bit faster. Case 2 - 1st way could be dangerous, since int.ToString() uses Culture.CurrentCulture as an argument (so results can vary from computer to computer): as in: someInt.ToString() == someInt.ToString(CultureInfo.CurrentCulture);

Categories : C#

C# type-casting sender
You don't need is when you use as because as will return the actual object of desired type if it's castable to that type, otherwise the null value is returned. Just checking if it's null would be the most optimized way: private void OnSomeEvent(IVehicle sender, ISomeArgs args){ Car _car = sender as Car; if(_car != null){ if(_car.numWheels == 4 && _car.hasGas){ _car.drive(); } } }

Categories : C#

Need help to avoid type casting
Make Rule generic: public interface Rule<T extends DataProvider> { public void execute(T dataProvider); } And then public class Rule1 implements Rule<Rule1dataProvider> { @Override public void execute(Rule1dataProvider dataProvider) { // ... } }

Categories : Java

type casting with struct
typedef struct dev { short id; char name[5]; int size; } dev; Is probably not aligned the way you think it is. There is compiler dependent padding between the fields. Google "struct padding" or something like that. This should show you the field offsets: dev foo; printf("offset of id is %d ", (char *)&foo.id - (char *)&foo); printf("offset of name is %d ", (char *)&foo.name[0] - (char *)&foo); printf("offset of size is %d ", (char *)&foo.size - (char *)&foo);

Categories : C

Explicit type casting in C++
Try: _beginthread((void(_cdecl*)(void*)) services, 0, NULL); What you were doing was explicitly casting the function pointer to a non-function pointer type (void *). This was OK. But the _beginthread function expects as its first parameter a function pointer of the correct type mentioned in the error message. So you need to fix your cast. If you're about to downvote this answer, I'd appreciate to know the reason why. I know it would be much better if user2754070 wanted to change the prototype of services (see my comments below). However, what I'm suggesting works (the answer was accepted) and, as far as I know, it is safe and standard practice in C libraries spawning threads. If you think it's not, please explain why and I'll consider deleting the answer.

Categories : C++

Primitive type casting
All compound assignment operators not only performs the operation, but also cast automatically their result to the type of the left-hand side variable. So your += not only adds variables and assign the result - it also cast the result to the right type.

Categories : Java

Casting to an unknown type
You can always templatize the callback function. template<typename Iterator> size_t callbackFunc(char*, size_t, size_t, void *userdata) { Iterator it = *static_cast<Iterator*>(userdata); // ... rest of code ... }

Categories : C++

MessageBox type casting to int
MessageBox.Show() returns DialogResult value which is enum type so this casting returns you underlying type of the enumeration elements(default is int ) casted to int

Categories : C#

How to base64 encode/decode a variable with string type in Python 3?
You need to encode the unicode string. If it's just normal characters, you can use ASCII. If it might have other characters in it, or just for general safety, you probably want utf-8. >>> import base64 >>> s = "12345" >>> s2 = base64.b64encode(s) Traceback (most recent call last): File "<stdin>", line 1, in <module> File ". . . /lib/python3.3/base64.py", line 58, in b64encode raise TypeError("expected bytes, not %s" % s.__class__.__name__) TypeError: expected bytes, not str >>> s2 = base64.b64encode(s.encode('ascii')) >>> print(s2) b'MTIzNDU=' >>>

Categories : Python

Type casting when exceeding the limit
Since a and b are int, their product a*b is int also. But the product is so big that it overflows and you get an incorrect value.The cast is needed so that the product is also long long. By the way, you don't need to cast both operands. Just one is enough: long long result = a * (long long)b; The other one is promoted to long long also. See this online demo. By the way, prefer C++-style cast over C-style cast: long long result = a * static_cast<long long>(b); Hope that helps.

Categories : C++

Custom type casting in Java
Consider the following class hierarchy. public class Mammal And a few subclasses.. public class Dog extends Mammal public class Cat extends Mammal Essentially, what you want to do, is to take a Dog, and make it a Cat. Clearly a dog is not a Cat, thus this cast can not ever work. A dog is a mammal, though. This cast is fine. Cat is a mammal too, so this cast is fine too. But cat can never be a dog, nor can dog ever be a cat. What you can do, is to create a constructor for ScalarFloat that would take an instance of ScalarInt and build an instance of ScalarFloat from that, conversion this way would not incur a loss of precision. But converting from a float to an int would incur a loss of precision, thus this is something you might not want to do..

Categories : Java

Type casting in PHP - security and efficiency
You shouldn't worry about the types, php will make them as needed, when you have to use the types when calculating, validate them using three === (type specific comparison) that they are still valid as that type of cast them to the desired type when needed 1 === 1 = true 1 === "1" = false 1 === true = false true === true = true false === false = true "hello" === "hello" = true etc... type casting $numberofpizzas = $_POST['number']; $price = 16; $totalprice = $price * (int)$numberofpizzas

Categories : PHP

C# object runtime type casting
Compile time type of prop.GetType() would always be an object.. If you are sure about the type you are using you can use dynamic type instead dynamic proplist=prop; foreach (dynamic item in proplist) { item.method1(); item.method2(); item.method3(); }

Categories : C#

Type casting before inserting in database?
$i = 1; // PHP Casts to integer because the lack of quote marks for example. $i = "1"; // PHP Casts to string because of the quote marks $i = 1.39; // PHP Casts to float because of the decimal place These are an automatic data cast when you have created the variable, so there is no need to have a secondary cast for your variable, just review over the MySQL manual to see the limitations/max byte size of a smallint. Ensure that you make the servers criteria and you wont have a problem http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html

Categories : PHP

Is there a way of casting a pointer to an array type?
I think this is what you are looking for. For the heap, a two-dimensional array int[M][N] decays to int(*)[N]. To pass it by reference, dereference it (see m below): #include <iostream> using namespace std; void func(int (&x)[2]) { cout << x[0] << ' ' << x[1] << endl; } int main() { // on the heap auto m = new int[1][2]; m[0][0] = 1; m[0][1] = 2; auto n = new int[1][3]; n[0][0] = 4; n[0][1] = 5; n[0][2] = 6; // on the stack int o[2] = {7,8}; int p[3] = {9,10}; func(*m); //func(*n); // doesn't compile, wrong size func(o); //func(p); // doesn't compile, wrong size } Output: 1 2 7 8

Categories : C++

Casting to derived type during Runtime
This is exactly what dynamic_cast is for: void SomeMethod(QObject *ptr) { A *a = dynamic_cast<A *>(ptr); if (a) { DoStuffA(a); return; } B *b = dynamic_cast<B *>(ptr); if (b) { DoStuffB(b); return; } C *c = dynamic_cast<C *>(ptr); if (c) { DoStuffC(c); return; } DoStuffNOTA(ptr); } Since you're using Qt, you'd probably want to use qobject_cast instead of dynamic_cast,* but otherwise everything is the same. However, all that repetition is, as usually, a sign that you're doing something wrong. You can eliminate a lot of it by using templates, but usually, you usually don't want to do this at all. Instead, use the "double dispatch" (aka "reverse dispatch") pattern. The whole reason we have virtual functions, and OO in general, is to avoid typ

Categories : C++

How does pointer type casting work in c
To answer your questions: cp points to the beginning of the newly allocated memory. However, up will contain the same address as cp. Note it is bad form to try and assign a pointer from one type to a different type without "casting" it first - just to tell the compiler you really meant to do such a dangerous thing. Typically assigning between types can cause all kinds of problems - as a result compilers will throw warnings if you do this without casting. The casting, however, doesn't actually have any effect on the program code itself - it is more a method of the programmer telling the compiler they really meant what they did. By the way, the pointer up is allocated on the stack in your function. Assigning a value to up actually places the value in the memory location on the stack. S

Categories : C

Casting to parent type -- Java
No, the object would behave the same regardless of the type of reference through which you call the method. This is by design - it allows subclasses to override methods of their superclasses. In your example, the upcast before assignment has no effect - it will happen implicitly as part of the assignment. Parent p = (Parent) new Child(); The caller can't force an object to ignore its method overrides. This is a good thing. Otherwise, a child could never enforce its own internal invariants. If you want to allow the caller to choose whether to call the parent method or the child method, then your API can provide two methods. Both the parent and the child can determine how to support each.

Categories : Java

Casting type right in XAML code?
I see two possibilities: Recreate your DropShadowEffect in your setter, recreating the object's Effect. Give your DropShadowEffect a name, and reference the object directly using TargetName: <Setter TargetName="dropShadow" Property="ShadowDepth" Value="0.5" />

Categories : C#

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

Conditional Operator ?: with Nullable type Casting
null can represent any object-based datatype. You need to cast null as a datatype so it know what you are talking about. int? x = (value.HasValue) ? value.Value : (int?)null; I know, it sounds a bit strange. To answer the questions in the comments: Why is it not implicit though? Yeah, I get that. But why do I not have to cast it in a If Else block? Let's walk through the code. Your else statement looks like this: else x = null; This means you are assigning the value of null to x. This is valid, because x is a int?, which takes nulls. The difference comes when you have the ternary operator. It says: "assign the value of the operator into x". The question (and the reason for your error) is, what datatype is the result of the ternary operator? From your code, you can't be

Categories : C#

Java generics and casting a generic type
You need to do a double cast: return (Function<Reference<T>, T>)(Function<?, ?>)ToData.INSTANCE; See also my recent answer using this pattern (from Joshua Bloch's Effective Java item 27, "favor generic methods") as an example of a valid unchecked cast. As I point out there, you should also consider suppressing the unchecked cast warning: @SuppressWarnings("unchecked") // this is safe for any T final Function<Reference<T>, T> withNarrowedTypes = (Function<Reference<T>, T>)(Function<?, ?>)ToData.INSTANCE; return withNarrowedTypes;

Categories : Java

Dynamic casting to a generic interface type
No. You cannot cast an expression to a type that is not known at compile time. (By "known", I mean resolvable to a Type whose generic type parameters are closed.) Having said that, I think it may be possible by using the expression API. The idea is that you would build a lambda expression of the type you determined (which can be strongly-typed), compile it, then execute it on your object to perform the cast. If you 100% need to do this, that's the direction I'd look.

Categories : C#

Java generic method type casting
This works perfect, nothing special, normal use of generics gt.<String>echoV(); //this line works well Here do we have something less obvious. Because generic method are defined at runtime does the jvm not know what kind of Class the generic method will return at compiletime, hence the classTypeException gt.<String>echoV().getClass();//this line leads to a type cast exception you should allocated it to a variable first, because the jvm does know the type of the variable at compiletime String s = gt.<String>echoV(); s.getClass();

Categories : Java

Issue with type casting the argument of the constructor
I don't get an error, I get a warning C4930: 'Foo f(int)': prototyped function not called (was a variable definition intended?) Try this instead: Foo1 f1(int(pi)); and look up the most vexing parse, as suggested in the comments. You have declared a function, rather than called the constructor.

Categories : C++

Casting generic type with interface constraint
Wrapper<Foo> needs to be Wrapper<IFoo>. Then you should be able to cast it. And it needs to implement the interface too. The cast below works... I don't think you can cast an objects generic type parameter to a different type (i.e. IWrapper<Foo> to IWrapper<IFoo>). void Main() { var foo = new Wrapper(); var t = foo as IWrapper<IFoo>; t.Dump(); } public interface IFoo {} public class Foo : IFoo {} public interface IWrapper<T> where T : IFoo {} public class Wrapper : IWrapper<IFoo> {}

Categories : C#



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