Rectangle 27 31

As of TypeScript 0.9 the lib.d.ts file uses specialized overload signatures that return the correct types for calls to getElementsByTagName.

// No type assertions needed
var script: HTMLScriptElement = document.getElementsByTagName('script')[0];
alert(script.type);

TypeScript: casting HTMLElement - Stack Overflow

typescript
Rectangle 27 21

First, you don't mention what platform you're targeting. Although recent Windows versions (Win2000, WinXP, Vista and Win7) support both Multibyte and Unicode versions of system calls using strings, the Unicode versions are faster (the multibyte versions are wrappers that convert to Unicode, call the Unicode version, then convert any returned strings back to mutlibyte). So if you're making a lot of these types of calls the Unicode will be faster.

Just because you're not planning on explicitly supporting additional languages, you should still consider supporting Unicode if your application saves and displays text entered by the users. Just because your application is unilingual, it doesn't follow that all it's users will be unilingual too. They may be perfectly happy to use your English language GUI, but might want to enter names, comments or other text in their own language and have them displayed properly.

"you should still consider supporting Unicode if your application saves and displays text entered by the users" - and if your application wants to deal with paths with arbitrary characters - and if it deals in any way with paths, it should.

This is exactly what I wanted to hear.. that one is a wrapper for the other. Unicode all the way baby.

visual c++ - C++ project type: unicode vs multi-byte; pros and cons - ...

c++ visual-c++ unicode ansi
Rectangle 27 2

You can use reflection to get all types in an assembly that implements a specific interface and then instantiate those types and call the methods on those instances through the interface.

var types = this.GetType().Assembly.GetTypes()
                                   .Where(t=>t.GetInterfaces().Contains(typeof(IGetNews)));
foreach (var type  in types)
{
    var instance = (IGetNews) Activator.CreateInstance(type);
    instance.SomeNews("news");
}

You would not need the reflection process for each frame, instead you would check on Awake and then add the found method to a container on a manager object. It gets a bit more cumbersome and less straight-forward to use in this case I would think. Also, it requires the addition of a manager, which is actually what Unity does for all MonoBehaviour callbacks.

HI fafase, nah you have to do it every frame if you want to simulate what unity does, using reflection as Mark explains. The components in question could be created/destroyed at any moment in the game :/ (unless I misunderstand you somehow)

c# - In Unity, how does Unity magically call all "Interfaces"? - Stack...

c# unity3d interface
Rectangle 27 9

Unions original purpose was to save space when you want to be able to be able to represent different types, what we call a variant type see Boost.Variant as a good example of this.

The other common use is type punning the validity of this is debated but practically most compiler support it, we can see that gcc documents its support:

The practice of reading from a different union member than the one most recently written to (called type-punning) is common. Even with -fstrict-aliasing, type-punning is allowed, provided the memory is accessed through the union type. So, the code above works as expected.

Pascal Cuoq has argued that defect report 283 clarified this was allowed in C. Defect report 283 added the following footnote as clarification:

If the member used to access the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called "type punning"). This might be a trap representation.

in C11 that would be footnote 95.

Although in the std-discussion mail group topic Type Punning via a Union the argument is made this is underspecified, which seems reasonable since DR 283 did not add new normative wording, just a footnote:

This is, in my opinion, an underspecified semantic quagmire in C. Consensus has not been reached between implementors and the C committee as to exactly which cases have defined behavior and which do not[...]

[...]the C standard's rules break the type-based alias analysis optimizations which current implementations perform.

it breaks some optimizations. The second argument against this is that using memcpy should generate identical code and is does not break optimizations and well defined behavior, for example this:

std::int64_t n;
std::memcpy(&n, &d, sizeof d);
union u1
{
  std::int64_t n;
  double d ;
} ;

u1 u ;
u.d = d ;

and we can see using godbolt this does generate identical code and the argument is made if your compiler does not generate identical code it should be considered a bug:

If this is true for your implementation, I suggest you file a bug on it. Breaking real optimizations (anything based on type-based alias analysis) in order to work around performance issues with some particular compiler seems like a bad idea to me.

The undefined behavior mailing list discussion: Type punning to avoid copying covers a lot of the same ground and we can see how grey the territory can be.

The claim that memcpy produces identical code ignores the fact that more efficient code could be generated if compilers would document patterns where aliasing would be recognized, in which case a compiler would only have to make a small number of mildly-pessimistic (but likely accurate) presumptions, whereas memcpy would often force a compiler to make more pessimistic presumptions. The code for memcpy itself may look fine, but its effects on the code around it not so much.

It's worth noting that with C++17 we're getting std::variant as a variant type

It might also be good to mention that std::memcpy is only valid if the types are TriviallyCopyable

@supercat if you could provide a godbolt example that shows this effect, it would be very helpful. As I understand Richard's position this should not be the case, perhaps it is a bug then.

uint16_t *outptr; void store_double_halfword(uint32_t dat) { uint32_t *dp = (uint32_t*)outptr; outptr = dp+1; memcpy(dp, &dat, sizeof (uint32_t)); }     void store_loop1(uint32_t *src){ for (int i=0; i<100; i++) store_next_word1(src[i]); }
outptr
memcpy
uint16_t*
uint16_t
uint32_t

c++ - Unions and type-punning - Stack Overflow

c++ c unions type-punning
Rectangle 27 2

The type of variable 'teacher' here is typeof(Person) and this type does not know anything about Teacher class and does not try to look for any methods in derived types. To call method of Teacher class you should cast your variable: (person as Teacher).ShowInfo().

To call specific method based on value type you should use keyword 'virtual' in your base class and override virtual methods in derived classes. This approach allows to implement derived classes with or without overriding of virtual methods. Methods of base class will be called for types without overided virtuals.

public class Program
{
    private static void Main(string[] args)
    {
        Person teacher = new Teacher();
        teacher.ShowInfo();

        Person incognito = new IncognitoPerson ();
        incognito.ShowInfo();

        Console.ReadLine();
    }
}

public class Person
{
    public virtual void ShowInfo()
    {
        Console.WriteLine("I am Person");
    }
}

public class Teacher : Person
{
    public override void ShowInfo()
    {
        Console.WriteLine("I am Teacher");
    }
}

public class IncognitoPerson : Person
{

}

c# - Why does calling a method in my derived class call the base class...

c# class derived-class
Rectangle 27 82

Andy Prowl has nicely covered design issues. This is, of course, very important, but I believe the original question concerns more performance issues related to std::function.

First of all, a quick remark on the measurement technique: The 11ms obtained for calc1 has no meaning at all. Indeed, looking at the generated assembly (or debugging the assembly code), one can see that VS2012's optimizer is clever enough to realize that the result of calling calc1 is independent of the iteration and moves the call out of the loop:

for (int i = 0; i < 1e8; ++i) {
}
calc1([](float arg){ return arg * 0.5f; });

Furthermore, it realises that calling calc1 has no visible effect and drops the call altogether. Therefore, the 111ms is the time that the empty loop takes to run. (I'm surprised that the optimizer has kept the loop.) So, be careful with time measurements in loops. This is not as simple as it might seem.

As it has been pointed out, the optimizer has more troubles to understand std::function and doesn't move the call out of the loop. So 1241ms is a fair measurement for calc2.

Notice that, std::function is able to store different types of callable objects. Hence, it must perform some type-erasure magic for the storage. Generally, this implies a dynamic memory allocation (by default through a call to new). It's well known that this is a quite costly operation.

The standard (20.8.11.2.1/5) encorages implementations to avoid the dynamic memory allocation for small objects which, thankfully, VS2012 does (in particular, for the original code).

To get an idea of how much slower it can get when memory allocation is involved, I've changed the lambda expression to capture three floats. This makes the callable object too big to apply the small object optimization:

float a, b, c; // never mind the values
// ...
calc2([a,b,c](float arg){ return arg * 0.5f; });

For this version, the time is approximately 16000ms (compared to 1241ms for the original code).

Finally, notice that the lifetime of the lambda encloses that of the std::function. In this case, rather than storing a copy of the lambda, std::function could store a "reference" to it. By "reference" I mean a std::reference_wrapper which is easily build by functions std::ref and std::cref. More precisely, by using:

auto func = [a,b,c](float arg){ return arg * 0.5f; };
calc2(std::cref(func));

I wrote about that a while ago:

As I said in the article, the arguments don't quite apply for VS2010 due to its poor support to C++11. At the time of the writing, only a beta version of VS2012 was available but its support for C++11 was already good enough for this matter.

I find this interesting indeed, wanting to make a proof of a code speed using toy examples that get optimized away by the compiler because they don't have any side effects. I would say that one rarely can make a bet on these kinds of measurements, without some real/production code.

@ Ghita: In this example, to prevent the code to be optimized away, calc1 could take a float argument that would be the result of the previous iteration. Something like x = calc1(x, [](float arg){ return arg * 0.5f; });. In addition, we must ensure that calc1 uses x. But, this isn't enough yet. We need to create a side effect. For instance, after the measurement, printing x on the screen. Even though, I agree that using toy codes for timimg measurements cannot always give a perfect indication of what is going to happen with real/production code.

It seems to me, too, that the benchmark constructs the std::function object inside the loop, and calls calc2 in the loop. Regardless that the compiler may or may not optimize this out, (and that the constructor could be as simple as storing a vptr), I'd be more interested in a case where the function is constructed once, and passed to another function which calls it in a loop. I.e. the call overhead rather than the construct time (and the call of 'f' and not of calc2). Also would be interested if calling f in a loop (in calc2), rather than once, would benefit from any hoisting.

Great answer. 2 things: nice example of a valid use for std::reference_wrapper (to coerce templates; it's not just for general storage), and it's funny to see VS's optimiser failing to discard an empty loop... as I noticed with this GCC bug re volatile.

c++ - std::function vs template - Stack Overflow

c++ templates c++11 std-function
Rectangle 27 11

If you take a little bit of time to understand the WebTarget API, as well as the different types returned from calls to WebTarget's method, you should get a better understanding of how to make calls. It may be a little confusing, as almost all the example use method chaining, as it's a very convenient way, but doing this, you miss all the actual classes involved in create and sending the request. Let break it down a bit

WebTarget target = client.target(getBaseURI()).path("rest").path("orders");

WebTarget.path() simply returns the WebTarget. Nothing interesting there.

target.path("oneOrder").request().accept(MediaType.APPLICATION_JSON).get(String.class)
WebTarget.request()
Invocation.Builder.accept(..)
Invocation.Builder
  • Invocation.Builder.get() calls its super class's SyncInvoker.get(), which makes the actual request, and returns a type, based on the argument we provide to get(Class returnType)

What you're doing with get(String.class) is saying that the response stream should be deserialized into a Sting type response. This is not a problem, as JSON is inherently just a String. But if you want to unmarshal it to a POJO, then you need to have a MessageBodyReader that knows how to unmarshal JSON to your POJO type. Jackson provides a MessageBodyReader in it's jackson-jaxrs-json-provider dependency

<dependency>
  <groupId>com.fasterxml.jackson.jaxrs</groupId>
  <artifactId>jackson-jaxrs-json-provider</artifactId>
  <version>2.4.0</version>
</dependency>

Most implementations will provider a wrapper for this module, like jersey-media-json-jackson for Jersey or resteasy-jackson-provider for Resteasy. But they are still using the underlying jackson-jaxrs-json-provider.

That being said, once you have that module on the classpath, is should be automatically registered, so the MessageBodyReader will be available. If not you can register it explicitly with the client, like client.register(JacksonJaxbJsonProvider.class). Once you have the Jackson support configured, then you can simply do something like

MyPojo myPojo = client.target(..).path(...).request().accept(..).get(MyPojo.class);

As for posting/sending data, you can again look at the different Invocation.Builder methods. For instance

Invocation.Builder builder = target.request();

If we want to post, look at the different post methods available. We can use

Response post(Entity<?> entity)
Response response = builder.post(Entity.json(myPojo));

You'll notice the Entity. All the post methods accept an Entity, and this is how the request will know what type the entity body should be, and the client will invoke the approriate MessageBodyWriter as well as set the appropriate header

<T> T post(Entity<?> entity, Class<T> responseType) - There's another overload, where we can specify the type to unmarshal into, instead of getting back a Response. We could do

MyPojo myPojo = builder.post(Entity.json(myPojo), MyPojo.class)

Note that with Response, we call its readEntity(Class pojoType) method to read from the Response, the entity body. The advantage of this, is that the Response object comes with a lot of useful information we can use, like headers and such. Personally, I always get the Response

Response response = builder.get();
    MyPojo pojo = response.readEntity(MyPojo.class);

As an aside, for your particular code you are showing, you most likely want to make it a @POST method. Remember @GET is mainly for retrieving data, PUT for updating, and POST for creating. That is a good rule of thumb to stick to, when first starting out. So you might change the method to

@Path("orders")
public class OrdersResource  {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes({MediaType.APPLICATION_JSON})
    public Response createOrder(@Context UriInfo uriInfo, Order input) {
       Order order = orderService.createOrder(input);
       URI uri = uriInfo.getAbsolutePathBuilder().path(order.getId()).build();
       return Response.create(uri).entity(order).build();
    }
}
WebTarget target = client.target(BASE).path("orders");
Response response = target.request().accept(...).post(Entity.json(order));
Order order = response.readEntity(Order.class);

Note the above is for Jersey/JAX-RS 2 client, which your original code is using. But now after your post of your web.xml and your exception, it appears you are using Jersey 1. So I am completely confused. For further help, I'll need some clarification. See my comment for the original post

java - REST service that accepts and returns object. How to write clie...

java rest jersey jersey-client
Rectangle 27 1

You can use a union. There are surely only a finite number of function types that you call via this pointer, and you can put them all in the union.

c - Pointers to any function? - Stack Overflow

c function-pointers
Rectangle 27 217

tolist()
import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]

Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the "nearest compatible Python type" (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you'll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)

If your list is float32 tolist will convert it to floatss - that's not desired probably. Using list(myarray) doesn't suffer from this - why should we prefer tolist ?

@Mr_and_Mrs_D are you suggesting that, despite having floats in your array, you'd like to have the resulting list be integers? That's sort of a whole different question... and of course you'd have to specify that despite being float32 values, they're all going to be integral. Anyway, if you had that situation, I guess doing myarray.astype(np.int32).tolist() would be an option, and explicit about what you're trying to accomplish. (And lastly, list(array_of_type_float32) doesn't give integers here when I tried it... so I don't know what you're asking.)

float32_array = np.array([0.51764709], np.float32); print(float32_array.tolist()); print(list(float32_array))

Okay, so the one converts to [float] and the other uses the numpy scalar float32 type still, as [np.float32]. Fine. Good to know, but I guess whether it's desirable or not depends on each specific case. For what it's worth, I suspect that generally when someone (like the OP) asks for conversion to a list, they implicitly mean a list of regular Python data types, in this case either floats or integers, and not a list of numpy scalar types. Thanks for pointing this out: I've edited the answer to include a note about that.

Converting NumPy array into Python List structure? - Stack Overflow

python numpy
Rectangle 27 1

One thing that could be clarified is the meaning of phone type. Does it refer to the situations and types of calls the phone is used for? Or the location of the phone? Is a work-phone one that is physically located at the office all the time (like a typical stationary/landline phone), or could a mobile phone which you take with you also be a work-phone if you use it for work related calls/tasks from home?

If phone type refers to physical location, then perhaps "Phone Location" would be the right term. In this case "office" might be a more precise term than "work".

If phone type refers to situation/type of calls, then perhaps "Phone Usage" would be the right term. In this case "personal" might be a better term than "home", and you might remove the "mobile" option.

A more generic term to cover both cases would be "Phone Context", but the ambiguity (are they asking me for location or usage?) might be confusing for some users.

Also, it is worth considering whether the options should be mutually exclusive or not. For example, I only have a mobile phone, which I use for everything, both personal and work. If you were asking me for location, I would select "mobile". If you were asking me for usage then I would select both "work" and "personal".

forms semantics telephone
Rectangle 27 3

For simple types such as int, there is no difference. For class types, what you call "constructor syntax" is known as direct initialization, and what you call "assignment syntax" as copy initialization. You cannot use copy initialization unless the class supports copy, so the tendency is to prefer direct initialization (with the caveat that then one must worry about the most vexing parse problem). Some people then argue in favor of the direct initialization syntax everywhere, on grounds of homogeneity: use the same format everywhere.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

c++ - Differences between constructor syntax and assignment syntax for...

c++
Rectangle 27 42

There are actually several different methods you can call to compare object instances. Given two object instances a and b, you could write:

Object.Equals(a,b) will (by default) perform reference equality comparison on reference types and bitwise comparison on value types. From the MSDN documentation:

The default implementation of Equals supports reference equality for reference types, and bitwise equality for value types. Reference equality means the object references that are compared refer to the same object. Bitwise equality means the objects that are compared have the same binary representation.

Note that a derived type might override the Equals method to implement value equality. Value equality means the compared objects have the same value but different binary representations.

Note the last paragraph above ... we'll discuss this a bit later.

Object.ReferenceEquals(a,b) performs reference equality comparison only. If the types passed are boxed value types, the result is always false.

a.Equals(b) calls the virtual instance method of Object, which the type of a could override to do anything it wants. The call is performed using virtual dispatch, so the code that runs depends on the runtime type of a.

a == b invokes the static overloaded operator of the **compile-time type* of a. If the implementation of that operator invokes instance methods on either a or b, it may also depend on the runtime types of the parameters. Since the dispatch is based on the types in the expression, the following may yield different results:

Frog aFrog = new Frog();
Frog bFrog = new Frog();
Animal aAnimal = aFrog;
Animal bAnimal = bFrog;
// not necessarily equal...
bool areEqualFrogs = aFrog == bFrog;
bool areEqualAnimals = aAnimal = bAnimal;

So, yes, there is vulnerability for check for nulls using operator ==.

==

The instance method Equals() is no better here. While the default implementation performs reference/bitwise equality checks, it is possible for a type to override the Equals() member method, in which case this implementation will be called. A user supplied implementation could return whatever it wants, even when comparing to null.

But what about the static version of Object.Equals() you ask? Can this end up running user code? Well, it turns out that the answer is YES. The implementation of Object.Equals(a,b) expands to something along the lines of:

((object)a == (object)b) || (a != null && b != null && a.Equals(b))
class Foo {
    public override bool Equals(object obj) { return true; }  }

var a = new Foo();
var b = new Foo();
Console.WriteLine( Object.Equals(a,b) );  // outputs "True!"

As a consequence, it's possible for the statement: Object.Equals(a,b) to run user code when neither of the types in the call are null. Note that Object.Equals(a,b) does not call the instance version of Equals() when either of the arguments is null.

Object.Equals(a,b)

If you need an iron clad gaurantee of comparing a reference to null without any other code running, you want Object.ReferenceEquals():

Object.ReferenceEquals(item, null);

This method makes the intent extremently clear - you are specifically expecting the result to be the comparison of two references for reference equality. The benefit here over using something like Object.Equals(a,null), is that it's less likely that someone will come along later and say:

a.Equals(null)
a == null

Let's inject some pragmatism here, however. So far we've talked about the potential for different modalities of comparison to yield different results. While this is certainly the case, there are certain types where it's safe to write a == null. Built-in .NET classes like String and Nullable<T> have well defined semantics for comparison. Furthermore, they are sealed - preventing any change to their behavior through inheritance. The following is quite common (and correct):

string s = ...
if( s == null ) { ... }
if( ReferenceEquals(s,null) ) { ... }

So in certain limited cases, using == is safe, and appropriate.

Questions like: "should I always/never do X" imply a knowledge gap about the nuances of the subject in question. I felt that a bit more detail would be helpful here to clarify why I don't think a simple answer is meaningful.

The static object.Equals(a,b) method can, in fact, call the overloaded/virtual Equals method on object a. If I recall correctly, it does something like ((object)a == (object)b) || (a != null && b != null && a.Equals(b)). (This is irrelevant when comparing to null, which is what the OP asks about, but is relevant to the general case.)

@LukeH: I added some narrative to talk about this case. I was originally focusing on just the instace-to-null comparison, but it's worth explaining this as well. Thanks for the feedback.

IMHO, IN PRACTICE you should use "a == b", unless you KNOW you want reference comparison. If a type does not support "==" operator, then use Object.Equals(a, b). I recommend NEVER using "a.Equals(b)" because that causes exception if a is null. If a type were to be implemented that failed to handle Object.Equals correctly, that would be a bug in that implementation, not a bug in your use of it. Don't go to contortions trying to avoid the possibility that someone wrote a bad class.

c# - Equals(item, null) or item == null - Stack Overflow

c# null equals robustness
Rectangle 27 3

All Framework objects inherit from System.Object (though it is possible to declare a type in MSIL which doesn't).

The object.ToString() method is a virtual method.

The special rule for value types which attempt to call a method from System.Object is this:

If the value type has overridden the method (as int and all numeric types do with ToString()) then the value type is not boxed ("converted" or "wrapped" to object), but the implementation method is called directly.

If the value type did not provide an implementation for such method (for example, a custom struct), the value type is boxed, and the base implemented mathod is called.

As for details about boxing/unboxing, there's plenty of information in msdn.

C# supports value types and reference types, but are they all objects?...

c# value-type reference-type
Rectangle 27 4

You can emulate the AppEngine datastore interface using reflect; usually I say minimize reflection, but you (and AppEngine and other ORMs) have no other great option here to present the interface you want. For something emulating Get you:

reflect.Value
ValueOf()
  • get the type of the thing you want to create
reflect.Zero
  • optionally fill in some data with reflect.Field(), etc.
  • use reflect.Indirect() and Value.Set() to set the original through the pointer.

A trivial example that just zeroes a struct through a pointer is at http://play.golang.org/p/g7dNlrG_vr and copied here:

GetMulti
package main

import (
    "fmt"
    "reflect"
)

func main() {
    s := []int{}
    getMultiZeroes(&s, 10)
    fmt.Println(s)
}

func getMultiZeroes(slicePtrIface interface{}, howMany int) {
    // enter `reflect`-land
    slicePtrValue := reflect.ValueOf(slicePtrIface)
    // get the type
    slicePtrType := slicePtrValue.Type()
    // navigate from `*[]T` to `T`
    sliceElemType := slicePtrType.Elem().Elem() // crashes if input type not `*[]T`
    // we'll need this to Append() to
    sliceValue := reflect.Indirect(slicePtrValue)
    // and this to Append()
    sliceElemValue := reflect.Zero(sliceElemType)

    // append requested number of zeroes
    for i := 0; i < howMany; i++ {
        // s := append(s, v)
        sliceValue.Set(reflect.Append(sliceValue, sliceElemValue))
    }
}

In live code (as opposed to testing like you're doing), it'd be faster to use a type switch (as Martin suggested) so that specialized native code runs for each type; that might also be handy if you have different behavior by type. An example for GetMulti is at http://play.golang.org/p/q-9WyUqv6P and below:

package main

import "fmt"

func main() {
    s := []int{}
    getZeroes(&s)
    fmt.Println(s)

    fails := []float32{}
    getZeroes(&fails)
}

func getZeroes(slicePtrIface interface{}) {
    switch sp := slicePtrIface.(type) {
    case *[]int:
        (*sp) = append((*sp), 0, 0)
    case *[]string:
        (*sp) = append((*sp), "", "")
    default:
        panic(fmt.Sprintf("getZeroes: passed type %T, which is not a pointer to a slice of a supported type", slicePtrIface))
    }
}

You could even trivially combine the two; write custom code for common types and call the slow reflect-based version in the default case. Demo at http://play.golang.org/p/6qw52B7eC3 (not copying because it's a such a simple stitching together of the two above).

There happened to be another recent question on how to make a value to pass to GetMulti, rather than emulating the GetMulti itself, if that comes up.

"Go lacks pass by reference" is useful to know, but also needs some elaboration. Go has pointers, and other types like slices that contain pointers to data. The sense in which there isn't "pass by reference" is just that Go will never change a value argument (int, struct) into a pointer implicitly. C++ reference arguments do exactly that: C++ void f(i int&) { i++; } changes i in the caller without the caller explicitly passing in a pointer at the callsite. func (i int) { i++ } doesn't.

In Go, you can look at the types passed to a function call and tell what data it can change. With C++ reference arguments or some languages' "pass by reference" semantics, any call might change locals; you can't tell without looking up the declarations.

For purposes of avoiding unnecessary copying of data, there are already pointers in the implementations of slice, string, map, interface, and channel values. Of those types, pointers, slices, and maps will actually let you modify data through them. Also, like in C++, Go's this-like receiver parameter can be a pointer without an explicit & in the calling code. There's more about this in Russ Cox's godata post and this summary on when you need a pointer or not.

just realized you might be doing Get and this only talked about GetMulti, so I added an example without the extra slice-related bits.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

go - Setting An Interface{} Parameter By Reference - Stack Overflow

interface go
Rectangle 27 2

I've had the same issues, and it seems to just be that primefaces doesn't allow it type of thing. My end goal is being able to move the 'selectOneMenu' tables out of the columns and put them in the headers, but at the moment here is what I have done.

It's due to the way that primefaces seems to access it's structures preparing them to be ready for the filters.

What I have done is created a 'hidden' p:inputText field with id = 'globalFilter' and made id display:none...

Then created 2 search fields (One using a selecOneMenu and one just a inputText field). Then used the onchange or onkeyup functions of those types to call my javascript functions which use jQuery to update the hidden filed to the value selected and then call the crpTable feature.

<script type="text/javascript">

        function doFilter1()
        {
            $("#globalFilter").val($("#globalFilter1").val());
            widgetVarTableId.filter();
        };
        function doFilter2()
        {
            $("#globalFilter").val($("#globalFilter2").val());
            widgetVarTableId.filter();
        };

</script>

<style>
   .myGlobalFilter {
      display:none;       
   }

</style>
<p:inputText id="globalFilter" styleClass="myGlobalFilter"/>

<h:outputText value="filter one: "/>
<h:selectOneMenu id="globalFilter1" onchange="doFilter1();">
   <f:selectItems value="#{formBean.filterOptions}" />
</h:selectOneMenu>

<h:outputText value="filter two: "/>
<p:inputText id="globalFilter2" onkeyup="doFilter2();">

This works as I expect.. however short coming of using the primefaces .filter()- is that you can't change it to be 'exact' 'startsWith' etc, it's always 'contains' with out modifying PF source code.

brilliant work around thank you, although the misfortune is the "contains".

jsf - Global filter with won't work - ...

jsf java-ee primefaces filter datatable
Rectangle 27 2

Return a different view

Use Moho's answer above if your intention is to redirect between actions. Naturally this incurs a round trip to the browser. During this round trip your ViewBag will be lost, but you could always use TempData.

If you want to simulate a redirect but without the round trip, you will have to write a tiny bit of custom code. See this article to learn how.

If your intention is to return the Index view from the GetSigmaDateInfo action, all you have to do is change the return statement at the end as follows:

return View("Index");  //Or substitute the name of the desired view

This avoids a second round trip to the browser, and preserves your ViewBag. The Index view can inspect any ViewBag values set by GetSigmaDateInfo, so there is no need to pass the data directly.

If there is more going on here (it's not entirely clear from your post), one proven technique is to refactor your code so that instead of two methods you have three methods. I'll explain.

Currently you have two actions, and you are thinking of the problem as one action calling another action. Instead, I suggest you think of it as two actions that do not have to call each other but which have logic in common.

What do you do when you have two functions that have logic in common? You refactor: remove the common logic, put it in a third function, and modify the two original functions to call that new function instead of having the logic in two places.

In this case the third function can be a new controller method (it must be marked private so that it cannot be called as an action) or you could consider writing a private helper class that contains the new function. Both are fine. I used the latter option in my example below.

public ActionResult Index()
{
    //Perform action-specific validation and logic here
    var result = DBHelper.GetSigmaData();  //Not sure what your intention is here
    ViewBag.SigmaData = result;
    //Do something with the result here
    return View();
}

and

[HttpPost]
public ActionResult GetSigmaDateInfo(string dp)
{
    //Perform action-specific validation and logic here
    var result = DBHelper.GetSigmaData(dp);
    ViewBag.SigmaData = result;
    //Do something with the result here
    return View();
}

and finally your common logic

static internal class DBHelper
{
    static public DateTime GetSigmaData(string dp = null)
    {
        DateTime SelectedDate = Convert.ToDateTime(dp);
        DateTime SelectedDateDayShiftStart = SelectedDate.AddHours(7);
        DateTime SelectedDateDayShiftEnd = SelectedDate.AddHours(19);

        var SigmaData =
            from n in db.tbl_dppITHr
            where n.ProductionHour >= SelectedDateDayShiftStart
            where n.ProductionHour <= SelectedDateDayShiftEnd
            select n;

        return SigmaData;
    }
}

Using this approach you avoid modifying the Index method to accept an optional argument. You probably don't want to do that. If you change the Index method you change the types of calls that you expose to the end user.

asp.net - Passing one item in a controller method to another method in...

asp.net asp.net-mvc-4
Rectangle 27 2

Return a different view

Use Moho's answer above if your intention is to redirect between actions. Naturally this incurs a round trip to the browser. During this round trip your ViewBag will be lost, but you could always use TempData.

If you want to simulate a redirect but without the round trip, you will have to write a tiny bit of custom code. See this article to learn how.

If your intention is to return the Index view from the GetSigmaDateInfo action, all you have to do is change the return statement at the end as follows:

return View("Index");  //Or substitute the name of the desired view

This avoids a second round trip to the browser, and preserves your ViewBag. The Index view can inspect any ViewBag values set by GetSigmaDateInfo, so there is no need to pass the data directly.

If there is more going on here (it's not entirely clear from your post), one proven technique is to refactor your code so that instead of two methods you have three methods. I'll explain.

Currently you have two actions, and you are thinking of the problem as one action calling another action. Instead, I suggest you think of it as two actions that do not have to call each other but which have logic in common.

What do you do when you have two functions that have logic in common? You refactor: remove the common logic, put it in a third function, and modify the two original functions to call that new function instead of having the logic in two places.

In this case the third function can be a new controller method (it must be marked private so that it cannot be called as an action) or you could consider writing a private helper class that contains the new function. Both are fine. I used the latter option in my example below.

public ActionResult Index()
{
    //Perform action-specific validation and logic here
    var result = DBHelper.GetSigmaData();  //Not sure what your intention is here
    ViewBag.SigmaData = result;
    //Do something with the result here
    return View();
}

and

[HttpPost]
public ActionResult GetSigmaDateInfo(string dp)
{
    //Perform action-specific validation and logic here
    var result = DBHelper.GetSigmaData(dp);
    ViewBag.SigmaData = result;
    //Do something with the result here
    return View();
}

and finally your common logic

static internal class DBHelper
{
    static public DateTime GetSigmaData(string dp = null)
    {
        DateTime SelectedDate = Convert.ToDateTime(dp);
        DateTime SelectedDateDayShiftStart = SelectedDate.AddHours(7);
        DateTime SelectedDateDayShiftEnd = SelectedDate.AddHours(19);

        var SigmaData =
            from n in db.tbl_dppITHr
            where n.ProductionHour >= SelectedDateDayShiftStart
            where n.ProductionHour <= SelectedDateDayShiftEnd
            select n;

        return SigmaData;
    }
}

Using this approach you avoid modifying the Index method to accept an optional argument. You probably don't want to do that. If you change the Index method you change the types of calls that you expose to the end user.

asp.net - Passing one item in a controller method to another method in...

asp.net asp.net-mvc-4
Rectangle 27 2

s => s.GetType().GetProperty(sortField)

When you try to access the result set of the IQueryable, it gets translated to SQL and the query gets run against your database (rather than being run in memory). The problem is that obviously your database knows nothing about your types, can't call any methods on them, and certainly can't perform any reflection on them.

You'll need to build your own expression tree which can be translated into SQL. The expression API is quite complicated and you'll need to do quite a bit of reading if you want to really get it. Here's a good starting point on creating dynamic queries using the expression API for you.

Thankfully your specific case is reasonably simple and there are worked examples of it here, here, and here, but I really do recommend doing some reading on it to understand what's going on. If you just copy-paste then you or someone else will end up having to maintain it and having a really sad time.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

c# - Dynamic IQueryable order by using string - Stack Overflow

c# .net dynamic expression iqueryable
Rectangle 27 7

This is a good place for application of the Visitor design pattern.

The beauty of this pattern is you can call unrelated code on different subclasses of a superclass without having to do weird casts everywhere or putting tons of unrelated methods into the superclass.

This works by creating a Visitor object and allowing our Vehicle class to accept() the visitor.

You can also create many types of Visitor and call unrelated code using the same methods, just a different Visitor implementation, which makes this design pattern very powerful when creating clean classes.

public class VisitorDemo {

    // We'll use this to mark a class visitable.
    public static interface Visitable {

        void accept(Visitor visitor);
    }

    // This is the visitor
    public static interface Visitor {

        void visit(Boat boat);

        void visit(Car car);

    }

    // Abstract
    public static abstract class Vehicle implements Visitable {

            // NO OTHER RANDOM ABSTRACT METHODS!

    }

    // Concrete
    public static class Car extends Vehicle {

        public void doCarStuff() {
            System.out.println("Doing car stuff");
        }

        @Override
        public void accept(Visitor visitor) {
            visitor.visit(this);
        }

    }

    // Concrete
    public static class Boat extends Vehicle {

        public void doBoatStuff() {
            System.out.println("Doing boat stuff");
        }

        @Override
        public void accept(Visitor visitor) {
            visitor.visit(this);
        }

    }

    // Concrete visitor
    public static class StuffVisitor implements Visitor {

        @Override
        public void visit(Boat boat) {
            boat.doBoatStuff();
        }

        @Override
        public void visit(Car car) {
            car.doCarStuff();
        }
    }

    public static void main(String[] args) {
        // Create our garage
        Vehicle[] garage = {
            new Boat(),
            new Car(),
            new Car(),
            new Boat(),
            new Car()
        };

        // Create our visitor
        Visitor visitor = new StuffVisitor();

        // Visit each item in our garage in turn
        for (Vehicle v : garage) {
            v.accept(visitor);
        }
    }

}

As you can see, StuffVisitor allows you to call different code on Boat or Car depending on which implementation of visit is called. You can also create other implementations of the Visitor to call different code with the same .visit() pattern.

Also notice that using this method, there is no use of instanceof or any hacky class checking. The only duplicated code between classes is the method void accept(Visitor).

If you want to support 3 types of concrete subclasses for example, you can just add that implementation into the Visitor interface too.

java - Do I really have a car in my garage? - Stack Overflow

java inheritance
Rectangle 27 2

To pass "arguments", you have to get the Constructor of the class matching the desired parameter types, and invoke the call on that one, like this:

private <T> T createInstance(Class<T> concreteClass, String stringArg){
    return concreteClass.getConstructor(String.class).newInstance(stringArg);
}

//usage
SomeClass s = createInstance(SomeClass, "testString");

//equals
SomeClass s = new SomeClass("testString");

//where SomeClass HAS to serve:
public SomeClass(String s){
  ...
}
getConstructor(Class<?>... parameterTypes)
concreteClass.getConstructor(Integer.class, String.class, List.class)
public SomeClass(Integer i, String s, List l)

I am wondering whether we could accept (Object... args) as second parameter for createInstance. Something like this Class[] types = new Class[args.length]; for(int i = 0; i < args.length; i++) { types[i] = args[i].getClass(); } return c.getConstructor(types).newInstance(args);

@MingtaoZhang You would need to convert each object to its classType to obtain the constructor. getConstructor takes Class<?>... - not (wrong syntax): ?...

java - Generic Return Type? - Stack Overflow

java generics syntax