Rectangle 27 4

The problem is the validator not the mapping!

at org.hibernate.validator.NotEmptyValidator.isValid(NotEmptyValidator.java:36)

The Annotation @NotEmpty contains @Size(min = 1) and @Size supports only String, Collection, Map and Array.

java - How to persist an object that has an enumeration field - Stack ...

java hibernate persistence enumeration
Rectangle 27 1

postNotification: while it reach the end of the enumeration

This is not about "unable to enumerate assets on devices", because of the async of enumerating ALAssetsGroup.

According to apple's document about enumerateGroupsWithTypes:usingBlock:failureBlock: of ALAssetsLibrary, this is an async method, will not get full data stored in array after it run.

This method is asynchronous. When groups are enumerated, the user may be asked to confirm the application's access to the data; the method, though, returns immediately. You should perform whatever work you want with the assets in enumerationBlock.

I do want to know when it is done. so that I have found an answer for knowing when the progress is done, and execute a block (cf. Create my own completion blocks in iOS). Even though this is not about the notification, but still gave me a hint to work it out.

[_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos  
                              usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
                                  if(group){
                                      // add into the array you are going to use
                                  }
                                  else
                                  {
                                      // the last one will be nil, 
                                      // it also means the enumeration is done
                                      // post notification then
                                      [[NSNotificationCenter defaultCenter] postNotificationName:kEnumerateGroupCompleteNotification]; 
                                  }
                              }
                            failureBlock:nil]; // leave nil here for make subject out

First, using the empty NSArray, which is the retained array we are using at previous step, in the ~DataSource protocol of UICollectionView or UITableView.

Second, adding an observer to the UIViewController, using @selector pass to this method to trigger the instance's reloadData to get the complete array just enumerating out. And the data will be shown on the view.

// In a UIViewController's implementation 

- (void)viewDidLoad{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reloadTableView:)
                                                 name:kEnumerateGroupCompleteNotification
                                               object:nil];
}

-(void)reloadTableView:(NSNotification*) notification {

    // reloadData after receive the notification
    [_tableView reloadData];

}

This is the way how I achieve my requirement. I have addressed ALAssetsGroup only above, but it will be the same in ALAssets's enumeration.

ALAssetsLibraryChangedNotification

And a great thank for Ramshad's answer, I have accessing ALAssetsLibrary as your suggestion in my static library now.

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

ios - Unable to enumerate groups/results while using ALAssetsLibrary i...

ios static-libraries alassetslibrary
Rectangle 27 1

postNotification: while it reach the end of the enumeration

This is not about "unable to enumerate assets on devices", because of the async of enumerating ALAssetsGroup.

According to apple's document about enumerateGroupsWithTypes:usingBlock:failureBlock: of ALAssetsLibrary, this is an async method, will not get full data stored in array after it run.

This method is asynchronous. When groups are enumerated, the user may be asked to confirm the application's access to the data; the method, though, returns immediately. You should perform whatever work you want with the assets in enumerationBlock.

I do want to know when it is done. so that I have found an answer for knowing when the progress is done, and execute a block (cf. Create my own completion blocks in iOS). Even though this is not about the notification, but still gave me a hint to work it out.

[_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos  
                              usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
                                  if(group){
                                      // add into the array you are going to use
                                  }
                                  else
                                  {
                                      // the last one will be nil, 
                                      // it also means the enumeration is done
                                      // post notification then
                                      [[NSNotificationCenter defaultCenter] postNotificationName:kEnumerateGroupCompleteNotification]; 
                                  }
                              }
                            failureBlock:nil]; // leave nil here for make subject out

First, using the empty NSArray, which is the retained array we are using at previous step, in the ~DataSource protocol of UICollectionView or UITableView.

Second, adding an observer to the UIViewController, using @selector pass to this method to trigger the instance's reloadData to get the complete array just enumerating out. And the data will be shown on the view.

// In a UIViewController's implementation 

- (void)viewDidLoad{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reloadTableView:)
                                                 name:kEnumerateGroupCompleteNotification
                                               object:nil];
}

-(void)reloadTableView:(NSNotification*) notification {

    // reloadData after receive the notification
    [_tableView reloadData];

}

This is the way how I achieve my requirement. I have addressed ALAssetsGroup only above, but it will be the same in ALAssets's enumeration.

ALAssetsLibraryChangedNotification

And a great thank for Ramshad's answer, I have accessing ALAssetsLibrary as your suggestion in my static library now.

ios - Unable to enumerate groups/results while using ALAssetsLibrary i...

ios static-libraries alassetslibrary
Rectangle 27 196

One big difference is that Enumerations come with support for instantiating them from some name String. For example:

object Currency extends Enumeration {
   val GBP = Value("GBP")
   val EUR = Value("EUR") //etc.
}
val ccy = Currency.withName("EUR")

This is useful when wishing to persist enumerations (for example, to a database) or create them from data residing in files. However, I find in general that enumerations are a bit clumsy in Scala and have the feel of an awkward add-on, so I now tend to use case objects. A case object is more flexible than an enum:

sealed trait Currency { def name: String }
case object EUR extends Currency { val name = "EUR" } //etc.

case class UnknownCurrency(name: String) extends Currency
trade.ccy match {
  case EUR                   =>
  case UnknownCurrency(code) =>
}

Regarding "UnknownCurrency(code)" pattern, there are other ways to handle not finding a currency code string than "breaking" the closed set nature of the Currency type. UnknownCurrency being of type Currency can now sneak into other parts of an API.

It's advisable to push that case outside Enumeration and make the client deal with an Option[Currency] type that would clearly indicate there is really a matching problem and "encourage" the user of the API to sort it out him/herself.

To follow up on the other answers here, the main drawbacks of case objects over Enumerations are:

The other difference is that Enumeration enum is ordered out of the box, whereas case object based enum obviosly not

Another point for case objects is if you care about java interoperability. The Enumeration would return the values as Enumeration.Value, thus 1) requiring scala-library, 2) losing the actual type information.

@oxbow_lakes Regarding point 1, specifically this part "...I've found it extremely rare in practice that this is required": Apparently you rarely do much UI work. This is an extremely common use case; displaying a (drop-down) list of valid enumeration members from which to pick.

Case objects vs Enumerations in Scala - Stack Overflow

scala enumeration case-class
Rectangle 27 24

The advantages of using case classes over Enumerations are:

  • When using sealed case classes, the Scala compiler can tell if the match is fully specified e.g. when all possible matches are espoused in the matching declaration. With enumerations, the Scala compiler cannot tell.
  • Case classes naturally supports more fields than a Value based Enumeration which supports a name and ID.

The advantages of using Enumerations instead of case classes are:

  • Enumerations are a bit easier to understand for someone new to Scala since they are prevalent in other languages

So in general, if you just need a list of simple constants by name, use enumerations. Otherwise, if you need something a bit more complex or want the extra safety of the compiler telling you if you have all matches specified, use case classes.

Case objects vs Enumerations in Scala - Stack Overflow

scala enumeration case-class
Rectangle 27 10

If you don't need to iterate over enum values or do some other enum-ish stuff, I'd advise using ADTs instead of Enumeration.

sealed abstract class Enum {
  def method: String = this match {
    case One => "1"
    case Two => "2"
    case Three => "3"
  }
}
case object One extends Enum
case object Two extends Enum
case object Three extends Enum

This approach has one advantage over Enumeration that compiler will warn you when you forget one or more cases in the match expression.

While this gives the benefit of providing exhaustive pattern matching, it introduces the possibility of human error by requiring the integer value be explicitly defined. IOW, if someone were to add a case object of Four and then extend the match with case Four => "3", the reverse map won't work as there are now two case objects at the same ordinal value.

java - How to add a method to Enumeration in Scala? - Stack Overflow

java scala enums enumeration
Rectangle 27 644

Another solution if the text is not the same to the enumeration value:

public enum Blah {
  A("text1"),
  B("text2"),
  C("text3"),
  D("text4");

  private String text;

  Blah(String text) {
    this.text = text;
  }

  public String getText() {
    return this.text;
  }

  public static Blah fromString(String text) {
    for (Blah b : Blah.values()) {
      if (b.text.equalsIgnoreCase(text)) {
        return b;
      }
    }
    return null;
  }
}
throw new IllegalArgumentException("No constant with text " + text + " found")
return null

@Sangdol Could you enlight us why returning null is better?

@Sangdol usually it's a good thing to check what SUN - oops - Oracle is doing in the same situation. And as Enum.valueOf() is showing it IS best practice to throw a Exception in this case. Because it is an exceptional situation. "Performance optimization" is a bad excuse to write unreadable code ;-)

Well, you could also make use of @Nullable annotation to make it "readable" ;-)

java - Lookup enum by string value - Stack Overflow

java enums
Rectangle 27 639

Another solution if the text is not the same to the enumeration value:

public enum Blah {
  A("text1"),
  B("text2"),
  C("text3"),
  D("text4");

  private String text;

  Blah(String text) {
    this.text = text;
  }

  public String getText() {
    return this.text;
  }

  public static Blah fromString(String text) {
    for (Blah b : Blah.values()) {
      if (b.text.equalsIgnoreCase(text)) {
        return b;
      }
    }
    return null;
  }
}
throw new IllegalArgumentException("No constant with text " + text + " found")
return null

@Sangdol Could you enlight us why returning null is better?

@Sangdol usually it's a good thing to check what SUN - oops - Oracle is doing in the same situation. And as Enum.valueOf() is showing it IS best practice to throw a Exception in this case. Because it is an exceptional situation. "Performance optimization" is a bad excuse to write unreadable code ;-)

Well, you could also make use of @Nullable annotation to make it "readable" ;-)

java - Lookup enum by string value - Stack Overflow

java enums
Rectangle 27 638

Another solution if the text is not the same to the enumeration value:

public enum Blah {
  A("text1"),
  B("text2"),
  C("text3"),
  D("text4");

  private String text;

  Blah(String text) {
    this.text = text;
  }

  public String getText() {
    return this.text;
  }

  public static Blah fromString(String text) {
    for (Blah b : Blah.values()) {
      if (b.text.equalsIgnoreCase(text)) {
        return b;
      }
    }
    return null;
  }
}
throw new IllegalArgumentException("No constant with text " + text + " found")
return null

@Sangdol Could you enlight us why returning null is better?

@Sangdol usually it's a good thing to check what SUN - oops - Oracle is doing in the same situation. And as Enum.valueOf() is showing it IS best practice to throw a Exception in this case. Because it is an exceptional situation. "Performance optimization" is a bad excuse to write unreadable code ;-)

Well, you could also make use of @Nullable annotation to make it "readable" ;-)

java - Lookup enum by string value - Stack Overflow

java enums
Rectangle 27 24

I know others have already answered with a correct answer, however, if you're wanting to use the enumerations in a combo box, you may want to go the extra yard and associate strings to the enum so that you can provide more detail in the displayed string (such as spaces between words or display strings using casing that doesn't match your coding standards)

public enum States
{
    California,
    [Description("New Mexico")]
    NewMexico,
    [Description("New York")]
    NewYork,
    [Description("South Carolina")]
    SouthCarolina,
    Tennessee,
    Washington
}

As a bonus, he also supplied a utility method for enumerating the enumeration that I've now updated with Jon Skeet's comments

Jon also pointed out that in C# 3.0 it can be simplified to something like this (which is now getting so light-weight that I'd imagine you could just do it in-line):

public static IEnumerable<T> EnumToList<T>()
    where T : struct
{
    return Enum.GetValues(typeof(T)).Cast<T>();
}

// Using above method
statesComboBox.Items = EnumToList<States>();

// Inline
statesComboBox.Items = Enum.GetValues(typeof(States)).Cast<States>();

@Ray - I was going to post a link to the same blog post :-) I've used his utility many times over and it works like a charm!

A few improvements (might take a few comments, I'm afraid): 1) The method could add the "where T : struct" constraint to make the ArgumentException less likely (though still possible). 2) The foreach can use "foreach(T val in enumValArray)" instead of formatting and then reparsing.

If you're using .NET 3.5, this can be done with just: return Enum.GetValues(typeof(T)).Cast<T>(); That doesn't bother building a list, either :)

Thanks Jom.. BTW, got you book -- and once my team return it to me, I'll read it! ;-) They seem to like it...

c# - Is there a way to iterate through all enum values? - Stack Overfl...

c# enumeration
Rectangle 27 24

I know others have already answered with a correct answer, however, if you're wanting to use the enumerations in a combo box, you may want to go the extra yard and associate strings to the enum so that you can provide more detail in the displayed string (such as spaces between words or display strings using casing that doesn't match your coding standards)

public enum States
{
    California,
    [Description("New Mexico")]
    NewMexico,
    [Description("New York")]
    NewYork,
    [Description("South Carolina")]
    SouthCarolina,
    Tennessee,
    Washington
}

As a bonus, he also supplied a utility method for enumerating the enumeration that I've now updated with Jon Skeet's comments

Jon also pointed out that in C# 3.0 it can be simplified to something like this (which is now getting so light-weight that I'd imagine you could just do it in-line):

public static IEnumerable<T> EnumToList<T>()
    where T : struct
{
    return Enum.GetValues(typeof(T)).Cast<T>();
}

// Using above method
statesComboBox.Items = EnumToList<States>();

// Inline
statesComboBox.Items = Enum.GetValues(typeof(States)).Cast<States>();

@Ray - I was going to post a link to the same blog post :-) I've used his utility many times over and it works like a charm!

A few improvements (might take a few comments, I'm afraid): 1) The method could add the "where T : struct" constraint to make the ArgumentException less likely (though still possible). 2) The foreach can use "foreach(T val in enumValArray)" instead of formatting and then reparsing.

If you're using .NET 3.5, this can be done with just: return Enum.GetValues(typeof(T)).Cast<T>(); That doesn't bother building a list, either :)

Thanks Jom.. BTW, got you book -- and once my team return it to me, I'll read it! ;-) They seem to like it...

c# - Is there a way to iterate through all enum values? - Stack Overfl...

c# enumeration
Rectangle 27 351

The problem with taking IEnumerable as a parameter is that it tells callers "I wish to enumerate this". It doesn't tell them how many times you wish to enumerate.

I can change the objects parameter to be List and then avoid the possible multiple enumeration but then I don't get the highest object that I can handle.

The goal of taking the highest object is noble, but it leaves room for too many assumptions. Do you really want someone to pass a LINQ to SQL query to this method, only for you to enumerate it twice (getting potentially different results each time?)

The semantic missing here is that a caller, who perhaps doesn't take time to read the details of the method, may assume you only iterate once - so they pass you an expensive object. Your method signature doesn't indicate either way.

By changing the method signature to IList/ICollection, you will at least make it clearer to the caller what your expectations are, and they can avoid costly mistakes.

Otherwise, most developers looking at the method might assume you only iterate once. If taking an IEnumerable is so important, you should consider doing the .ToList() at the start of the method.

It's a shame .NET doesn't have an interface that is IEnumerable + Count + Indexer, without Add/Remove etc. methods, which is what I suspect would solve this problem.

+1 for the lack of "reade list" in .net

@DanNeely I would suggest IReadOnlyCollection(T) (new with .net 4.5) as the best interface to convey the idea that it is an IEnumerable(T) which is intended to be enumerated multiple times. As this answer states, IEnumerable(T) itself is so generic that it may even refer to un-resetable content which cannot be enumerated over again without side effects. But IReadOnlyCollection(T) implies re-iterability.

If you do the .ToList() at the start of the method, you first have to check if the parameter is not null. That means you'll get two places where you throw an ArgumentException: if the parameter is null and if it doesn't have any items.

I read this article on the semantics of IReadOnlyCollection<T> vs IEnumerable<T> and then posted a question about using IReadOnlyCollection<T> as a parameter, and in which cases. I think the conclusion I eventually came to is the logic to follow. That it should be used where enumeration is expected, not necessarily where there could be multiple enumeration.

c# - Handling warning for possible multiple enumeration of IEnumerable...

c# .net performance resharper
Rectangle 27 93

When a subscriber unsubscribes you are changing contents of the collection of Subscribers during enumeration.

There are several ways to fix this, one being changing the for loop to use an explicit .ToList():

public void NotifySubscribers(DataRecord sr)  
{
    foreach(Subscriber s in subscribers.Values.ToList())
    {
                                              ^^^^^^^^^  
        ...

+1, but Jared was faster. Thanks to both of you.

I see what you are saying about unsubscribing in the catch section - but this would only be a secondary error if something else caused the call-back to fail. I will look at this more closely.

c# - Collection was modified; enumeration operation may not execute - ...

c# wcf concurrency dictionary thread-safety
Rectangle 27 8

Another disadvantage of case classes versus Enumerations when you will need to iterate or filter across all instances. This is a built-in capability of Enumeration (and Java enums as well) while case classes don't automatically support such capability.

In other words: "there's no easy way to get a list of the total set of enumerated values with case classes".

Case objects vs Enumerations in Scala - Stack Overflow

scala enumeration case-class
Rectangle 27 6

someone must already have an elegant solution to this problem

There are lots of problems that have no elegant solution (and many that have no solution at all). What makes you think this problem has one? This assumption is very faulty. The closest you can get is to use a wrapper class.

class FloatingPointEnum {
    float f;
    FloatingPointEnum(float arg) : f(arg) {}
public:
    static const FloatingPointEnum Value1;
    static const FloatingPointEnum Value2;
    operator float() const { return f; }
};
const FloatingPointEnum FloatingPointEnum::Value1(0.1234f);
const FloatingPointEnum FloatingPointEnum::Value2(0.6789f);

Thank you for your relatively elegant answer. With regards to your comment on "someone must already have an elegant solution to this problem": Time and again, the internet community has shown me a number of elegant solutions to problems. I figured it was better to ask than go through the process of reinventing the wheel and starting off with a square.

That's fair enough, and I'm not gonna say you were wrong to ask, but it's not good to assume a solution exists.

C++ "Floating Point Enum" - Stack Overflow

c++ floating-point enumeration c++03
Rectangle 27 4

Scala's Enumeration does not allow properties and/or methods to be added to values in your enumeration. With this new MyEnumeration you can.

abstract class MyEnumeration {
  // "Value" must be the name of the class defining your values type Value
  type Value

  // Contains your values in definition order
  private val vals = collection.mutable.LinkedHashMap[String, Value]()

  // A mixin for your values class to automatically collect the values
  protected trait ValuesCollector { self: Value =>
    private val ordinal = vals.size

    vals += (fieldNames(ordinal) -> self)

    def getName = fieldNames(ordinal)
    override def toString = getName
  }

  def apply(ordinal: Int) = vals(fieldNames(ordinal))
  def apply(fldName: String) = vals(fldName)

  def values = vals.values
  def namedValues: collection.Map[String, Value] = vals

  // Getting the field names through reflection.
  // Copied from scala.Enumeration
  private val fieldNames = getClass.getMethods filter (m =>
    m.getParameterTypes.isEmpty &&
    classOf[ValuesCollector].isAssignableFrom(m.getReturnType) &&
    m.getDeclaringClass != classOf[MyEnumeration]) map (_.getName)

}

Here you see the Planet example in Scala.

object Planet extends MyEnumeration {

  case class Value(val mass: Double, val radius: Double) extends ValuesCollector {
    // universal gravitational constant  (m3 kg-1 s-2)
    private val G = 6.67300E-11;

    def surfaceGravity = G * mass / (radius * radius)
    def surfaceWeight(otherMass: Double) = otherMass * surfaceGravity

  }

  val MERCURY = Value(3.303e+23, 2.4397e6)
  val VENUS = Value(4.869e+24, 6.0518e6)
  val EARTH = Value(5.976e+24, 6.37814e6)
  val MARS = Value(6.421e+23, 3.3972e6)
  val JUPITER = Value(1.9e+27, 7.1492e7)
  val SATURN = Value(5.688e+26, 6.0268e7)
  val URANUS = Value(8.686e+25, 2.5559e7)
  val NEPTUNE = Value(1.024e+26, 2.4746e7)
  val PLUTO = Value(1.27e+22, 1.137e6)

}

object PlanetTest {
  def main(args: Array[String]) {
    val earthWeight = 175
    val mass = earthWeight/Planet.EARTH.surfaceGravity
    for (p <- Planet.values) println("Your weight on %s is %f" format (p, p.surfaceWeight(mass)))
    /* Your weight on MERCURY is 66.107583
     * Your weight on VENUS is 158.374842
     * Your weight on EARTH is 175.000000
     * Your weight on MARS is 66.279007
     * Your weight on JUPITER is 442.847567
     * Your weight on SATURN is 186.552719
     * Your weight on URANUS is 158.397260
     * Your weight on NEPTUNE is 199.207413
     * Your weight on PLUTO is 11.703031
     */
  }

}

java - How to add a method to Enumeration in Scala? - Stack Overflow

java scala enums enumeration
Rectangle 27 4

I've seen various versions of making a case class mimic an enumeration. Here is my version:

trait CaseEnumValue {
    def name:String
}

trait CaseEnum {
    type V <: CaseEnumValue
    def values:List[V]
    def unapply(name:String):Option[String] = {
        if (values.exists(_.name == name)) Some(name) else None
    }
    def unapply(value:V):String = {
        return value.name
    }
    def apply(name:String):Option[V] = {
        values.find(_.name == name)
    }
}

Which allows you to construct case classes that look like the following:

abstract class Currency(override name:String) extends CaseEnumValue {
}

object Currency extends CaseEnum {
    type V = Site
    case object EUR extends Currency("EUR")
    case object GBP extends Currency("GBP")
    var values = List(EUR, GBP)
}

Maybe someone could come up with a better trick than simply adding a each case class to the list like I did. This was all I could come up with at the time.

@jho I've been trying to work through your solution as-is, but it won't compile. In the second code snippit, there is a reference to Site in "type V = Site". I am not sure to what that is referring to clear up the compilation error. Next, why are you providing the empty braces for "abstract class Currency"? Couldn't they just be left off? Finally, why are you using a var in "var values = ..."? Doesn't this mean that clients could at any time from anywhere in the code assign a new List to values? Wouldn't it be far preferable to make it a val instead of a var?

Case objects vs Enumerations in Scala - Stack Overflow

scala enumeration case-class
Rectangle 27 290

You can convert the int back to an enumeration member with a simple cast, and then call ToString():

int value = GetValueFromDb();
EnumDisplayStatus enumDisplayStatus = (EnumDisplayStatus)value;
string stringValue = enumDisplayStatus.ToString();
enum Foo { A = 1, B= 1 }

@dbkk the documentation states that with regards to enums "your code should not make any assumptions about which string will be returned." because of the precise situation you quote. see msdn.microsoft.com/en-us/library/16c1xs4z.aspx

c# - Enum String Name from Value - Stack Overflow

c# enums
Rectangle 27 2

Seems like this is exactly why it is often recommended to use accessor methods instead of directly referencing members. Your problem is that the code allows access to the map before it is initialized. Block arbitrary access to the map, and hide it behind an accessor method that makes sure it is initialized.

import java.util.Map;
import java.util.HashMap;

public enum EnumTest {
  FOO, BAR, BAZ;

  private static Map<String,EnumTest> map = null;

  public synchronized static Map getMap() {
    if (map == null) {
      map = new HashMap<String,EnumTest>();
      for ( EnumTest e : EnumTest.values() ) {
        map.put( e.name(), e );
      }
    }

    return map;
  }

  public static void main(String[] args) {
    System.out.println( EnumTest.getMap().size() );
  }
}

enums - Force Initialization of an enumerated type in Java - Stack Ove...

java enums enumeration
Rectangle 27 114

In Swift, you can use Extensions to add new functionality to existing classes, structs and enumeration types.

They differ from Objective-C categories in a few ways, mainly:

  • You don't need to import an Extension explicitly. If you define an extension to add new functionality to an existing type, the new functionality will be available on all existing instances of that type, even if they were created before the extension was defined.
  • As stated above, they work not only with classes, but with other types as well.
  • Add computed properties and computed static properties
  • Define and use new nested types
  • Make an existing type conform to a protocol

The basic syntax to declare an extension is as follows:

extension SomeType {
    // new functionality to add to SomeType goes here
}

Check Apple's documentation for more information on how to use Extensions in Swift.

How to create swift class for category? - Stack Overflow

swift swift-extensions